<?php
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../models/Game.php';
require_once __DIR__ . '/../models/SiteSettings.php';
require_once __DIR__ . '/../helpers/EmailHelper.php';
require_once __DIR__ . '/../helpers/TurnstileHelper.php';

class UserController {
    private $userModel;
    private $gameModel;
    private $siteSettings;
    private $emailHelper;
    private $turnstileHelper;

    public function __construct() {
        $this->userModel = new User();
        $this->gameModel = new Game();
        $this->siteSettings = new SiteSettings();
        $this->emailHelper = new EmailHelper();
        $this->turnstileHelper = new TurnstileHelper();
    }

    /**
     * Display registration form
     */
    public function registerPage() {
        // If already logged in, redirect to profile
        if (isset($_SESSION['user_id'])) {
            header('Location: /profile');
            exit;
        }

        $error = '';
        $success = '';
        $settings = $this->siteSettings->getAllSettings();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = $_POST['username'] ?? '';
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';
            $name = $_POST['name'] ?? '';
            $turnstileToken = $_POST['cf-turnstile-response'] ?? '';

            // Validate inputs
            if (empty($username) || empty($email) || empty($password) || empty($confirmPassword)) {
                $error = 'All fields are required';
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = 'Invalid email format';
            } elseif (strlen($password) < 8) {
                $error = 'Password must be at least 8 characters long';
            } elseif ($password !== $confirmPassword) {
                $error = 'Passwords do not match';
            } elseif ($this->turnstileHelper->isEnabled() && !$this->turnstileHelper->validateResponse($turnstileToken)) {
                $error = 'CAPTCHA verification failed. Please try again.';
            } else {
                // Register user
                $result = $this->userModel->register($username, $email, $password, $name);

                if ($result['success']) {
                    // Send verification email
                    $this->emailHelper->sendVerificationEmail($email, $result['user_id'], $result['verification_token']);

                    $success = 'Registration successful! Please check your email to verify your account. You must verify your email before you can log in. If you don\'t see the email in your inbox, please check your spam or junk folder.';
                } else {
                    $error = $result['message'];
                }
            }
        }

        include __DIR__ . '/../views/user/register.php';
    }

    /**
     * Display login form
     */
    public function loginPage() {
        // If already logged in, redirect to profile
        if (isset($_SESSION['user_id'])) {
            header('Location: /profile');
            exit;
        }

        $error = '';
        $settings = $this->siteSettings->getAllSettings();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? '';
            $rememberMe = isset($_POST['remember_me']);
            $turnstileToken = $_POST['cf-turnstile-response'] ?? '';

            // Validate CAPTCHA if enabled
            if ($this->turnstileHelper->isEnabled() && !$this->turnstileHelper->validateResponse($turnstileToken)) {
                $error = 'CAPTCHA verification failed. Please try again.';
            } else {
                // Authenticate user
                $user = $this->userModel->authenticate($username, $password);

            if ($user) {
                // Check if we got an error about email verification
                if (isset($user['error']) && $user['error'] === 'email_not_verified') {
                    $error = 'Please verify your email before logging in. Check your inbox and spam/junk folder for the verification email.';

                    // Get user details to resend verification email if needed
                    $userId = $user['user_id'];
                    $userDetails = $this->userModel->getUserById($userId);

                    if ($userDetails && !empty($userDetails['verification_token'])) {
                        // Resend verification email
                        $this->emailHelper->sendVerificationEmail($userDetails['email'], $userId, $userDetails['verification_token']);
                        $error .= ' We have resent the verification email to your address.';
                    }
                } else {
                    // Set session variables
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['user_role'] = $user['role'];

                    // Set remember me cookie if requested
                    if ($rememberMe) {
                        $token = bin2hex(random_bytes(32));
                        setcookie('remember_user', $token, time() + 30 * 24 * 60 * 60, '/');
                        $_SESSION['remember_token'] = password_hash($token, PASSWORD_DEFAULT);
                    }

                    // Redirect to profile
                    header('Location: /profile');
                    exit;
                }
            } else {
                $error = 'Invalid username/email or password';
            }
            }
        }

        include __DIR__ . '/../views/user/login.php';
    }

    /**
     * Logout user
     */
    public function logout() {
        // Clear session
        unset($_SESSION['user_id']);
        unset($_SESSION['username']);
        unset($_SESSION['user_role']);

        // Clear remember me cookie
        if (isset($_COOKIE['remember_user'])) {
            setcookie('remember_user', '', time() - 3600, '/');
        }

        // Redirect to home
        header('Location: /');
        exit;
    }

    /**
     * Display forgot password form
     */
    public function forgotPasswordPage() {
        // If already logged in, redirect to profile
        if (isset($_SESSION['user_id'])) {
            header('Location: /profile');
            exit;
        }

        $error = '';
        $success = '';
        $settings = $this->siteSettings->getAllSettings();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'] ?? '';

            if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = 'Please enter a valid email address';
            } else {
                // Create password reset token
                $token = $this->userModel->createPasswordResetToken($email);

                if ($token) {
                    // Send password reset email
                    $this->emailHelper->sendPasswordResetEmail($email, $token);

                    $success = 'Password reset link has been sent to your email';
                } else {
                    $error = 'Email not found';
                }
            }
        }

        include __DIR__ . '/../views/user/forgot-password.php';
    }

    /**
     * Display reset password form
     */
    public function resetPasswordPage() {
        // If already logged in, redirect to profile
        if (isset($_SESSION['user_id'])) {
            header('Location: /profile');
            exit;
        }

        $error = '';
        $success = '';
        $settings = $this->siteSettings->getAllSettings();

        $email = $_GET['email'] ?? '';
        $token = $_GET['token'] ?? '';

        if (empty($email) || empty($token)) {
            $error = 'Invalid reset link';
        } else {
            // Verify token
            $valid = $this->userModel->verifyPasswordResetToken($email, $token);

            if (!$valid) {
                $error = 'Invalid or expired reset link';
            }
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($error)) {
            $password = $_POST['password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';

            if (empty($password) || strlen($password) < 8) {
                $error = 'Password must be at least 8 characters long';
            } elseif ($password !== $confirmPassword) {
                $error = 'Passwords do not match';
            } else {
                // Reset password
                $result = $this->userModel->resetPassword($email, $token, $password);

                if ($result) {
                    $success = 'Password has been reset successfully. You can now login with your new password.';
                } else {
                    $error = 'Failed to reset password';
                }
            }
        }

        include __DIR__ . '/../views/user/reset-password.php';
    }

    /**
     * Verify email
     */
    public function verifyEmail() {
        $id = $_GET['id'] ?? '';
        $token = $_GET['token'] ?? '';

        $error = '';
        $success = '';
        $settings = $this->siteSettings->getAllSettings();

        if (empty($id) || empty($token)) {
            $error = 'Invalid verification link';
        } else {
            // Verify email
            $result = $this->userModel->verifyEmail($id, $token);

            if ($result) {
                $success = 'Email verified successfully. You can now login.';
            } else {
                $error = 'Invalid verification link';
            }
        }

        include __DIR__ . '/../views/user/verify-email.php';
    }

    /**
     * Display user profile
     */
    public function profilePage() {
        // Check if user is logged in
        if (!isset($_SESSION['user_id'])) {
            header('Location: /login');
            exit;
        }

        $userId = $_SESSION['user_id'];
        $user = $this->userModel->getUserById($userId);
        $gameHistory = $this->userModel->getUserGameHistory($userId);
        $favoriteGames = $this->userModel->getUserFavoriteGames($userId);
        $settings = $this->siteSettings->getAllSettings();

        $error = '';
        $success = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $action = $_POST['action'] ?? '';

            if ($action === 'update_profile') {
                $name = $_POST['name'] ?? '';
                $email = $_POST['email'] ?? '';
                $username = $_POST['username'] ?? '';

                // Update profile
                $data = [
                    'name' => $name,
                    'email' => $email,
                    'username' => $username
                ];

                $result = $this->userModel->updateProfile($userId, $data);

                if ($result) {
                    $success = 'Profile updated successfully';
                    $user = $this->userModel->getUserById($userId); // Refresh user data
                } else {
                    $error = 'Failed to update profile';
                }
            } elseif ($action === 'change_password') {
                $currentPassword = $_POST['current_password'] ?? '';
                $newPassword = $_POST['new_password'] ?? '';
                $confirmPassword = $_POST['confirm_password'] ?? '';

                // Verify current password
                if (!password_verify($currentPassword, $user['password'])) {
                    $error = 'Current password is incorrect';
                } elseif (empty($newPassword) || strlen($newPassword) < 8) {
                    $error = 'New password must be at least 8 characters long';
                } elseif ($newPassword !== $confirmPassword) {
                    $error = 'New passwords do not match';
                } else {
                    // Update password
                    $result = $this->userModel->updatePassword($userId, $newPassword);

                    if ($result) {
                        $success = 'Password changed successfully';
                    } else {
                        $error = 'Failed to change password';
                    }
                }
            } elseif ($action === 'export_data') {
                $this->userModel->exportUserData($userId);
                exit; // Stop script execution after download
            } elseif ($action === 'delete_account') {
                $result = $this->userModel->deleteAccount($userId);

                if ($result) {
                    // Log the user out and redirect to homepage
                    $this->logout();
                } else {
                    $error = 'Failed to delete account. Please try again.';
                }
            }
        }

        include __DIR__ . '/../views/user/profile.php';
    }

    /**
     * Record game play
     */
    public function recordGamePlay() {
        // Check if user is logged in
        if (!isset($_SESSION['user_id'])) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'User not logged in']);
            exit;
        }

        $userId = $_SESSION['user_id'];
        $gameId = $_POST['game_id'] ?? 0;

        if (empty($gameId)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Game ID is required']);
            exit;
        }

        // Record game play
        $result = $this->userModel->recordGamePlay($userId, $gameId);

        header('Content-Type: application/json');
        echo json_encode(['success' => $result]);
        exit;
    }

    /**
     * Toggle game favorite status
     */
    public function toggleFavorite() {
        // Check if user is logged in
        if (!isset($_SESSION['user_id'])) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'User not logged in']);
            exit;
        }

        $userId = $_SESSION['user_id'];
        $gameId = $_POST['game_id'] ?? 0;

        if (empty($gameId)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Game ID is required']);
            exit;
        }

        // Toggle favorite status
        $result = $this->userModel->toggleGameFavorite($userId, $gameId);

        header('Content-Type: application/json');
        echo json_encode([
            'success' => $result['success'],
            'status' => $result['status'],
            'is_favorited' => $result['status'] === 'added'
        ]);
        exit;
    }

    /**
     * Check if a game is favorited by the current user
     */
    public function isGameFavorited() {
        // Check if user is logged in
        if (!isset($_SESSION['user_id'])) {
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'is_favorited' => false]);
            exit;
        }

        $userId = $_SESSION['user_id'];
        $gameId = $_GET['game_id'] ?? 0;

        if (empty($gameId)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Game ID is required']);
            exit;
        }

        // Check if game is favorited
        $isFavorited = $this->userModel->isGameFavorited($userId, $gameId);

        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'is_favorited' => $isFavorited]);
        exit;
    }
}
