<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Auth Controller
 *
 * Handles user authentication: login, registration, and logout.
 */
class AuthController extends Controller
{
    /**
     * Display the login form.
     *
     * Redirects to dashboard if the user is already logged in.
     *
     * @return void
     */
    public function loginForm(): void
    {
        if (isLoggedIn()) {
            if (isAdmin()) {
                redirect('/admin');
            }
            redirect('/dashboard');
        }

        $this->view('auth/login', [
            'title'      => 'Login - Gmind Institute',
            'currentNav' => 'login',
        ]);
    }

    /**
     * Process the login form submission.
     *
     * Validates CSRF token, verifies credentials against the database,
     * and logs the user in on success.
     *
     * @return void
     */
    public function login(): void
    {
        $this->validateCsrf();

        $email    = sanitize($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($email) || empty($password)) {
            flash('error', 'Please enter your email and password.');
            redirect('/login');
        }

        $userModel = $this->model('User');
        $user = $userModel->getByEmail($email);

        if ($user === null || !password_verify($password, $user['password'])) {
            flash('error', 'Invalid email or password.');
            redirect('/login');
        }

        if (!(bool) $user['is_active']) {
            flash('error', 'Your account has been deactivated. Please contact administration.');
            redirect('/login');
        }

        // Log the user in
        \login([
            'id'     => $user['id'],
            'name'   => $user['name'],
            'email'  => $user['email'],
            'role'   => $user['role'],
            'avatar' => $user['photo'] ?? null,
        ]);

        if ($user['role'] === 'admin') {
            redirect('/admin');
        }

        redirect('/dashboard');
    }

    /**
     * Display the registration form.
     *
     * Redirects to dashboard if the user is already logged in.
     *
     * @return void
     */
    public function registerForm(): void
    {
        if (isLoggedIn()) {
            redirect('/dashboard');
        }

        $this->view('auth/register', [
            'title'      => 'Register - Gmind Institute',
            'currentNav' => 'register',
        ]);
    }

    /**
     * Process the registration form submission.
     *
     * Validates CSRF token, creates a new user account with
     * student role, and auto-logs the user in.
     *
     * @return void
     */
    public function register(): void
    {
        $this->validateCsrf();

        $name     = sanitize($_POST['name'] ?? '');
        $email    = sanitize($_POST['email'] ?? '');
        $phone    = sanitize($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        // Basic validation
        if (empty($name) || empty($email) || empty($password)) {
            flash('error', 'Please fill in all required fields.');
            redirect('/register');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address.');
            redirect('/register');
        }

        if (strlen($password) < 6) {
            flash('error', 'Password must be at least 6 characters long.');
            redirect('/register');
        }

        if ($password !== $confirmPassword) {
            flash('error', 'Passwords do not match.');
            redirect('/register');
        }

        // Check if email already exists
        $userModel = $this->model('User');
        $existingUser = $userModel->getByEmail($email);

        if ($existingUser !== null) {
            flash('error', 'An account with this email already exists.');
            redirect('/register');
        }

        try {
            // Create student user
            $userId = $userModel->createStudent([
                'name'     => $name,
                'email'    => $email,
                'password' => $password,
                'phone'    => $phone,
            ]);

            // Auto-login the new user
            \login([
                'id'     => $userId,
                'name'   => $name,
                'email'  => $email,
                'role'   => 'student',
                'avatar' => null,
            ]);

            flash('success', 'Welcome to Gmind Institute! Your account has been created.');
            redirect('/dashboard');
        } catch (\Throwable $e) {
            error_log('Registration error: ' . $e->getMessage());
            flash('error', 'Something went wrong. Please try again later.');
            redirect('/register');
        }
    }

    /**
     * Log out the current user.
     *
     * Destroys the session and redirects to the home page.
     *
     * @return void
     */
    public function logout(): void
    {
        \logout();
    }
}
