<?php
declare(strict_types=1);

require_once __DIR__ . '/../core/Controller.php';
require_once __DIR__ . '/../core/CSRF.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../services/PermissionService.php';
require_once __DIR__ . '/../includes/audit_helper.php';

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | SHOW LOGIN FORM
    |--------------------------------------------------------------------------
    */
    public function login(): void
    {
        session_start();

        if (isset($_SESSION['admin_id'])) {
            redirect('/admin');
        }

        $csrf = CSRF::generate();

        $this->view('auth/login', [
            'csrf' => $csrf
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | HANDLE LOGIN
    |--------------------------------------------------------------------------
    */
    public function authenticate(): void
    {
        session_start();

        if (!CSRF::verify($_POST['_csrf'] ?? null)) {
            http_response_code(419);
            die("Invalid CSRF token.");
        }

        global $pdo;

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

        if (!$email || !$password) {
            die("Email and password required.");
        }

        // Basic brute force protection
        if (isset($_SESSION['login_attempts']) && $_SESSION['login_attempts'] >= 5) {
            die("Too many login attempts. Try again later.");
        }

        $stmt = $pdo->prepare("
            SELECT a.*, r.name AS role_name
            FROM admins a
            LEFT JOIN roles r ON a.role_id = r.id
            WHERE a.email = ?
            LIMIT 1
        ");
        $stmt->execute([$email]);

        $admin = $stmt->fetch();

        if (!$admin || !password_verify($password, $admin['password'])) {

            $_SESSION['login_attempts'] =
                ($_SESSION['login_attempts'] ?? 0) + 1;

            logAudit('Authentication', 'Failed Login Attempt');

            die("Invalid credentials.");
        }

        /*
        |--------------------------------------------------------------------------
        | SUCCESSFUL LOGIN
        |--------------------------------------------------------------------------
        */

        session_regenerate_id(true);

        $_SESSION['admin_id']   = (int)$admin['id'];
        $_SESSION['admin_name'] = $admin['name'];
        $_SESSION['admin_role'] = $admin['role_name'] ?? 'viewer';
        $_SESSION['login_attempts'] = 0;
        $_SESSION['last_activity'] = time();

        logAudit('Authentication', 'Admin Login');

        redirect('/admin');
    }

    /*
    |--------------------------------------------------------------------------
    | LOGOUT
    |--------------------------------------------------------------------------
    */
    public function logout(): void
    {
        session_start();

        if (isset($_SESSION['admin_id'])) {
            logAudit('Authentication', 'Admin Logout');
        }

        $_SESSION = [];

        if (ini_get("session.use_cookies")) {

            $params = session_get_cookie_params();

            setcookie(
                session_name(),
                '',
                time() - 42000,
                $params["path"],
                $params["domain"],
                $params["secure"],
                $params["httponly"]
            );
        }

        session_destroy();
        session_regenerate_id(true);

        redirect('/login');
    }

    /*
    |--------------------------------------------------------------------------
    | SESSION TIMEOUT CHECK
    |--------------------------------------------------------------------------
    */
    public static function checkSessionTimeout(): void
    {
        session_start();

        $timeout = 1800; // 30 minutes

        if (isset($_SESSION['last_activity']) &&
            (time() - $_SESSION['last_activity'] > $timeout)) {

            session_unset();
            session_destroy();
            redirect('/login');
        }

        $_SESSION['last_activity'] = time();
    }
}
