<?php
require_once APP_PATH . '/Core/BaseController.php';
require_once APP_PATH . '/Models/User.php';
require_once APP_PATH . '/Core/CSRF.php';

class AuthController extends BaseController {

    private User $userModel;

    public function __construct() {
        $this->userModel = new User();
    }

    // ── GET /login ─────────────────────────────────────────────
    public function loginForm(): void {
        $this->view('auth.login', [
            'title'     => 'Sign In — BOAFO',
            'error'     => $this->getFlash('error'),
            'success'   => $this->getFlash('success'),
            'old_email' => $this->getFlash('old_email'),
        ], 'auth');
    }

    // ── POST /login ─────────────────────────────────────────────
    public function login(): void {
        CSRF::check();

        $email    = trim($this->input('email', ''));
        $password = $this->input('password', '');

        $errors = $this->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        if (!empty($errors)) {
            $this->flash('error', array_values($errors)[0]);
            $this->flash('old_email', $email);
            $this->redirect(APP_URL . '/login');
        }

        $user = $this->userModel->findByEmail($email);

        if (!$user) {
            $this->flash('error', 'Invalid email or password.');
            $this->flash('old_email', $email);
            $this->redirect(APP_URL . '/login');
        }

        // Check if locked
        if ($this->userModel->isLocked($user)) {
            $this->flash('error', 'Account temporarily locked due to too many failed attempts. Please try in 15 minutes.');
            $this->redirect(APP_URL . '/login');
        }

        if (!password_verify($password, $user['password_hash'])) {
            $this->userModel->incrementLoginAttempts($user['id']);
            $this->flash('error', 'Invalid email or password.');
            $this->flash('old_email', $email);
            $this->redirect(APP_URL . '/login');
        }

        if (!$user['email_verified']) {
            $this->flash('error', 'Please verify your email address before logging in. Check your inbox.');
            $this->redirect(APP_URL . '/login');
        }

        if ($user['status'] !== 'active') {
            $this->flash('error', 'Your account is ' . $user['status'] . '. Please contact support.');
            $this->redirect(APP_URL . '/login');
        }

        $this->userModel->recordLogin($user['id']);
        Auth::login($user);

        // Redirect to intended URL or dashboard
        $intended = $_SESSION['intended_url'] ?? null;
        unset($_SESSION['intended_url']);
        $this->redirect($intended ?: APP_URL . '/dashboard');
    }

    // ── GET /register ───────────────────────────────────────────
    public function registerForm(): void {
        $this->view('auth.register', [
            'title'   => 'Create Account — BOAFO',
            'errors'  => $this->getFlash('errors') ?? [],
            'old'     => $this->getFlash('old') ?? [],
        ], 'auth');
    }

    // ── POST /register ──────────────────────────────────────────
    public function register(): void {
        CSRF::check();

        $data = [
            'first_name'       => trim($this->input('first_name', '')),
            'last_name'        => trim($this->input('last_name', '')),
            'email'            => trim($this->input('email', '')),
            'phone'            => trim($this->input('phone', '')),
            'password'         => $this->input('password', ''),
            'password_confirm' => $this->input('password_confirm', ''),
            'role'             => $this->input('role', 'student'),
        ];

        $errors = $this->validate([
            'first_name' => 'required|max:100',
            'last_name'  => 'required|max:100',
            'email'      => 'required|email',
            'password'   => 'required|min:8',
            'role'       => 'required|in:student,mentor,tutor',
        ]);

        if ($data['password'] !== $data['password_confirm']) {
            $errors['password_confirm'] = 'Passwords do not match.';
        }

        if ($this->userModel->findByEmail($data['email'])) {
            $errors['email'] = 'This email address is already registered.';
        }

        if (!empty($errors)) {
            $this->flash('errors', $errors);
            $this->flash('old', $data);
            $this->redirect(APP_URL . '/register');
        }

        $userId = $this->userModel->createUser($data);

        // Create role-specific profile
        $this->createRoleProfile($userId, $data['role']);

        // For development: auto-verify (remove in production)
        if (APP_ENV === 'development') {
            $this->userModel->verifyEmail(
                $this->userModel->find($userId)['verify_token']
            );
            $this->flash('success', 'Account created! You can now sign in.');
        } else {
            $verifyToken = $this->userModel->find($userId)['verify_token'];
            // In production: send email with verify link
            $this->flash('success', 'Registration successful! Please check your email to verify your account.');
        }

        $this->redirect(APP_URL . '/login');
    }

    private function createRoleProfile(int $userId, string $role): void {
        $db = Database::getInstance();
        if ($role === 'student') {
            $db->prepare("INSERT INTO student_profiles (user_id) VALUES (?)")->execute([$userId]);
        } elseif ($role === 'mentor') {
            $db->prepare("INSERT INTO mentor_profiles (user_id) VALUES (?)")->execute([$userId]);
        } elseif ($role === 'tutor') {
            $db->prepare("INSERT INTO tutor_profiles (user_id) VALUES (?)")->execute([$userId]);
        }
    }

    // ── GET /verify-email/{token} ───────────────────────────────
    public function verifyEmail(string $token): void {
        $verified = $this->userModel->verifyEmail($token);
        if ($verified) {
            $this->flash('success', 'Email verified! You can now sign in.');
        } else {
            $this->flash('error', 'Invalid or expired verification link.');
        }
        $this->redirect(APP_URL . '/login');
    }

    // ── GET /forgot-password ─────────────────────────────────────
    public function forgotForm(): void {
        $this->view('auth.forgot', [
            'title'   => 'Forgot Password — BOAFO',
            'error'   => $this->getFlash('error'),
            'success' => $this->getFlash('success'),
        ], 'auth');
    }

    // ── POST /forgot-password ────────────────────────────────────
    public function forgot(): void {
        CSRF::check();

        $email = trim($this->input('email', ''));
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->flash('error', 'Please enter a valid email address.');
            $this->redirect(APP_URL . '/forgot-password');
        }

        $user = $this->userModel->findByEmail($email);
        if ($user) {
            $token = $this->userModel->setResetToken($user['id']);
            $resetUrl = APP_URL . '/reset-password/' . $token;
            // In production: send email with $resetUrl
            // For development, just show the link
            if (APP_ENV === 'development') {
                $this->flash('success', "Password reset link (dev only): <a href='{$resetUrl}'>{$resetUrl}</a>");
                $this->redirect(APP_URL . '/forgot-password');
            }
        }

        // Always show success to prevent email enumeration
        $this->flash('success', 'If that email is registered, you will receive a password reset link shortly.');
        $this->redirect(APP_URL . '/forgot-password');
    }

    // ── GET /reset-password/{token} ──────────────────────────────
    public function resetForm(string $token): void {
        $user = $this->userModel->findByResetToken($token);
        if (!$user) {
            $this->flash('error', 'Invalid or expired reset link. Please request a new one.');
            $this->redirect(APP_URL . '/forgot-password');
        }
        $this->view('auth.reset', [
            'title'  => 'Reset Password — BOAFO',
            'token'  => $token,
            'error'  => $this->getFlash('error'),
        ], 'auth');
    }

    // ── POST /reset-password/{token} ─────────────────────────────
    public function reset(string $token): void {
        CSRF::check();

        $user = $this->userModel->findByResetToken($token);
        if (!$user) {
            $this->flash('error', 'Invalid or expired reset link.');
            $this->redirect(APP_URL . '/forgot-password');
        }

        $password = $this->input('password', '');
        $confirm  = $this->input('password_confirm', '');

        if (strlen($password) < 8) {
            $this->flash('error', 'Password must be at least 8 characters.');
            $this->redirect(APP_URL . '/reset-password/' . $token);
        }

        if ($password !== $confirm) {
            $this->flash('error', 'Passwords do not match.');
            $this->redirect(APP_URL . '/reset-password/' . $token);
        }

        $this->userModel->updatePassword($user['id'], $password);
        $this->flash('success', 'Password reset successfully. Please sign in.');
        $this->redirect(APP_URL . '/login');
    }

    // ── GET /logout ───────────────────────────────────────────────
    public function logout(): void {
        Auth::logout();
        $this->redirect(APP_URL . '/login');
    }
}
