<?php
declare(strict_types=1);

// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

class Profile extends Controller {
    
    public function __construct() {
        if (!isLoggedIn()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }
    }

    public function index(): void {
        $userModel = $this->model('User');
        $user = $userModel->getUserById((int)$_SESSION['user_id']);

        $data = [
            'title' => 'My Profile',
            'user' => $user, // CRITICAL: This passes the user object to prevent the view crash
            'name' => $user->name,
            'email' => $user->email,
            'contact_number' => $user->contact_number ?? '',
            'address_street' => $user->address_street ?? '',
            'address_suburb' => $user->address_suburb ?? '',
            'address_city' => $user->address_city ?? '',
            'address_state' => $user->address_state ?? '',
            'address_zip' => $user->address_zip ?? '',
            'address_country' => $user->address_country ?? '',
            'totp_enabled' => $user->totp_enabled,
            'name_err' => '',
            'email_err' => '',
            'qr_code_url' => '',
            'setup_secret' => '',
        ];

        if (isset($_GET['setup2fa']) && $user->totp_enabled == 0) {
            $data['setup_secret'] = generateTOTPSecret();
            $appName = getSettings()['app_name'] ?? SITENAME;
            $data['qr_code_url'] = getTOTPQRCodeUrl($appName, $user->email, $data['setup_secret']);
        }

        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_info'])) {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            $data['name'] = trim($_POST['name']);
            $data['email'] = trim($_POST['email']);
            $data['contact_number'] = trim($_POST['contact_number'] ?? '');
            $data['address_street'] = trim($_POST['address_street'] ?? '');
            $data['address_suburb'] = trim($_POST['address_suburb'] ?? '');
            $data['address_city'] = trim($_POST['address_city'] ?? '');
            $data['address_state'] = trim($_POST['address_state'] ?? '');
            $data['address_zip'] = trim($_POST['address_zip'] ?? '');
            $data['address_country'] = trim($_POST['address_country'] ?? '');

            if (empty($data['email'])) {
                $data['email_err'] = 'Please enter an email address';
            } elseif ($data['email'] != $user->email && $userModel->findUserByEmail($data['email'])) {
                $data['email_err'] = 'This email is already taken by another account';
            }

            if (empty($data['name'])) {
                $data['name_err'] = 'Please enter your name';
            }

            if (empty($data['email_err']) && empty($data['name_err'])) {
                $updateData = [
                    'id' => $_SESSION['user_id'], 
                    'name' => $data['name'], 
                    'email' => $data['email'],
                    'contact_number' => $data['contact_number'],
                    'address_street' => $data['address_street'],
                    'address_suburb' => $data['address_suburb'],
                    'address_city' => $data['address_city'],
                    'address_state' => $data['address_state'],
                    'address_zip' => $data['address_zip'],
                    'address_country' => $data['address_country']
                ];
                
                if ($userModel->updateProfile($updateData)) {
                    $_SESSION['user_name'] = $data['name'];
                    $_SESSION['user_email'] = $data['email'];

                    systemLog('PROFILE_UPDATED', 'User updated their personal profile.');
                    flash('system_msg', 'Profile updated successfully!', 'success');
                    
                    header('Location: ' . URLROOT . '/profile/index');
                    exit;
                }
            }
        }

        $this->view('profile/index', $data);
    }

    public function manage2FA(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $userId = (int)$_SESSION['user_id'];

            $db = new Database();

            if (isset($_POST['disable_2fa'])) {
                $db->query("UPDATE users SET totp_enabled = 0, totp_secret = NULL WHERE id = :id");
                $db->bind(':id', $userId);
                $db->execute();
                
                systemLog('2FA_DISABLED', 'User disabled Two-Factor Authentication.');
                flash('system_msg', 'Two-Factor Authentication has been disabled.', 'success');
            } 
            elseif (isset($_POST['verify_2fa']) && isset($_POST['setup_secret'])) {
                $secret = trim($_POST['setup_secret']);
                $code = trim($_POST['auth_code']);

                if (verifyTOTPCode($secret, $code)) {
                    $db->query("UPDATE users SET totp_enabled = 1, totp_secret = :secret WHERE id = :id");
                    $db->bind(':secret', $secret);
                    $db->bind(':id', $userId);
                    $db->execute();

                    $userModel = $this->model('User');
                    $_SESSION['new_backup_codes'] = $userModel->generateBackupCodes($userId);

                    systemLog('2FA_ENABLED', 'User successfully enabled Two-Factor Authentication.');
                    flash('system_msg', 'Two-Factor Authentication successfully activated! Please save your backup codes below.', 'success');
                } else {
                    flash('system_msg', 'Invalid authentication code. Please try scanning the QR code again.', 'error');
                }
            }

            header('Location: ' . URLROOT . '/profile/index');
            exit;
        }
    }

    public function updatePassword(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $userModel = $this->model('User');

            $data = [
                'old_password' => trim($_POST['old_password']),
                'new_password' => trim($_POST['new_password']),
                'confirm_password' => trim($_POST['confirm_password']),
            ];

            $currentUser = $userModel->getUserById((int)$_SESSION['user_id']);
            
            if (empty($data['old_password']) || !password_verify($data['old_password'], $currentUser->password)) {
                flash('system_msg', 'Incorrect current password.', 'error');
            } elseif (empty($data['new_password']) || strlen($data['new_password']) < 6) {
                flash('system_msg', 'New password must be at least 6 characters.', 'error');
            } elseif ($data['new_password'] !== $data['confirm_password']) {
                flash('system_msg', 'New passwords do not match.', 'error');
            } else {
                $updateData = [
                    'id' => $_SESSION['user_id'],
                    'password' => password_hash($data['new_password'], PASSWORD_DEFAULT)
                ];

                if ($userModel->updatePassword($updateData)) {
                    systemLog('PASSWORD_CHANGED', 'User successfully changed their password.');
                    flash('system_msg', 'Password updated successfully!', 'success');
                } else {
                    flash('system_msg', 'Something went wrong updating your password.', 'error');
                }
            }
            
            header('Location: ' . URLROOT . '/profile/index');
            exit;
        }
    }
}