<?php
namespace Tshen\Controllers;
use Tshen\Database;
use function Tshen\view;
use function Tshen\redirect;
use function Tshen\require_auth;
use function Tshen\auth_user;
use function Tshen\flash;

class UserController {
    public function updateProfile() {
        require_auth();
        if (!\Tshen\csrf_check()) { 
            flash('error', 'Invalid request.'); 
            return redirect('/profile'); 
        }
        
        $user = auth_user();
        $userId = $user['id'];
        
        // Get form data
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $gender = trim($_POST['gender'] ?? '');
        $bio = trim($_POST['bio'] ?? '');
        
        // Update user profile in database
        try {
            // Check if user profile exists
            $profile = Database::run('SELECT * FROM user_profiles WHERE user_id = ?', [$userId])->fetch();
            
            if ($profile) {
                // Update existing profile
                Database::run(
                    'UPDATE user_profiles SET first_name = ?, last_name = ?, phone = ?, address = ?, gender = ?, bio = ? WHERE user_id = ?',
                    [$firstName, $lastName, $phone, $address, $gender, $bio, $userId]
                );
            } else {
                // Create new profile
                Database::run(
                    'INSERT INTO user_profiles (user_id, first_name, last_name, phone, address, gender, bio) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [$userId, $firstName, $lastName, $phone, $address, $gender, $bio]
                );
            }
            
            flash('success', 'Profile updated successfully.');
        } catch (\PDOException $e) {
            flash('error', 'Failed to update profile. Please try again.');
        }
        
        return redirect('/profile');
    }
    
    public function updatePassword() {
        require_auth();
        if (!\Tshen\csrf_check()) { 
            flash('error', 'Invalid request.'); 
            return redirect('/profile'); 
        }
        
        $user = auth_user();
        $userId = $user['id'];
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        // Validate passwords
        if (!$currentPassword || !$newPassword || !$confirmPassword) {
            flash('error', 'All password fields are required.');
            return redirect('/profile');
        }
        
        if ($newPassword !== $confirmPassword) {
            flash('error', 'New passwords do not match.');
            return redirect('/profile');
        }
        
        // Verify current password
        $userRow = Database::run('SELECT password FROM users WHERE id = ?', [$userId])->fetch();
        if (!$userRow || !password_verify($currentPassword, $userRow['password'])) {
            flash('error', 'Current password is incorrect.');
            return redirect('/profile');
        }
        
        // Update password
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        Database::run('UPDATE users SET password = ? WHERE id = ?', [$hashedPassword, $userId]);
        
        flash('success', 'Password updated successfully.');
        return redirect('/profile');
    }
    
    public function uploadProfilePicture() {
        require_auth();
        
        // Handle GET requests by redirecting to profile page
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            return redirect('/profile');
        }
        
        // For POST requests, continue with upload logic
        if (!\Tshen\csrf_check()) { 
            flash('error', 'Invalid request.'); 
            return redirect('/profile'); 
        }
        
        $user = auth_user();
        $userId = $user['id'];
        
        // Check if file was uploaded
        if (!isset($_FILES['profile_picture']) || $_FILES['profile_picture']['error'] !== UPLOAD_ERR_OK) {
            flash('error', 'No file uploaded or upload error.');
            return redirect('/profile');
        }
        
        $file = $_FILES['profile_picture'];
        
        // Validate file type using finfo (more reliable than trusting client-provided type)
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);

        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif'];
        if (!in_array($mime, $allowedTypes)) {
            flash('error', 'Only JPG, PNG, GIF, WEBP and AVIF files are allowed.');
            return redirect('/profile');
        }
        
        // Validate file size (max 2MB)
        if ($file['size'] > 2 * 1024 * 1024) {
            flash('error', 'File size must be less than 2MB.');
            return redirect('/profile');
        }
        
        // Create uploads directory if it doesn't exist
        $uploadDir = __DIR__ . '/../../public/uploads/profiles/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        // Ensure directory has proper permissions
        chmod($uploadDir, 0777);
        
        // Generate unique filename
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'profile_' . $userId . '_' . time() . '.' . $extension;
        $filepath = $uploadDir . $filename;
        
        // Move uploaded file
        if (move_uploaded_file($file['tmp_name'], $filepath)) {
            // Update profile picture in database
            try {
                // Set the web-accessible path to the image
                $webPath = '/uploads/profiles/' . $filename;
                
                $profile = Database::run('SELECT * FROM user_profiles WHERE user_id = ?', [$userId])->fetch();
                
                if ($profile) {
                    // Update existing profile with profile picture
                    Database::run(
                        'UPDATE user_profiles SET profile_picture = ? WHERE user_id = ?',
                        [$webPath, $userId]
                    );
                } else {
                    // Insert new profile with required fields to avoid NULL constraint errors
                    Database::run(
                        'INSERT INTO user_profiles (user_id, profile_picture, first_name, last_name, phone, address, gender, bio) 
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
                        [$userId, $webPath, '', '', '', '', '', '']
                    );
                }
                
                flash('success', 'Profile picture updated successfully.');
            } catch (\PDOException $e) {
                flash('error', 'Failed to update profile picture in database.');
            }
        } else {
            flash('error', 'Failed to upload file.');
        }
        
        return redirect('/profile');
    }
    
    public function getProfile() {
        require_auth();
        $user = auth_user();
        $userId = $user['id'];
        
        // Get user data
        $userData = Database::run('SELECT email, credits FROM users WHERE id = ?', [$userId])->fetch();
        
        // Get profile data
        $profileData = Database::run('SELECT * FROM user_profiles WHERE user_id = ?', [$userId])->fetch();
        if ($profileData && !empty($profileData['profile_picture'])) {
            if (strpos($profileData['profile_picture'], '/public') === 0) {
                $profileData['profile_picture'] = substr($profileData['profile_picture'], 7);
            }
        }

        if (!$profileData) {
            $profileData = [
                'first_name' => '',
                'last_name' => '',
                'phone' => '',
                'address' => '',
                'gender' => '',
                'bio' => '',
                // store profile_picture as a path relative to the public folder
                'profile_picture' => '/icon.png'
            ];
        }
        
        return view('profile', [
            'title' => 'Profile',
            'user' => $userData,
            'profile' => $profileData
        ]);
    }
}