<?php
declare(strict_types=1);

require_once __DIR__ . '/../Config/database.php';
require_once __DIR__ . '/../Config/functions.php';

class AuthController
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }

    /* --------------------------------------------------------------------------
       LOGIN HANDLER
    -------------------------------------------------------------------------- */
    public function login(string $email, string $password, bool $remember = false): bool
    {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE email = :email AND status = 'active' LIMIT 1");
        $stmt->execute(['email' => $email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password_hash'])) {
            // ✅ Regenerate session to prevent fixation
            session_regenerate_id(true);

            $_SESSION['user_id']       = $user['id'];
            $_SESSION['user_name']     = $user['name'];
            $_SESSION['role']          = $user['role'];
            $_SESSION['last_activity'] = time();

            /* --------------------------------------------------
               REMEMBER ME TOKEN (optional persistent login)
            -------------------------------------------------- */
            if ($remember) {
                $token  = bin2hex(random_bytes(32));
                $hashed = password_hash($token, PASSWORD_DEFAULT);

                // Add column if missing (optional setup)
                try {
                    $this->db->prepare("ALTER TABLE users ADD COLUMN remember_token VARCHAR(255) NULL")->execute();
                } catch (Throwable $e) {
                    // ignore if already exists
                }

                $this->db->prepare("UPDATE users SET remember_token = :token WHERE id = :id")
                         ->execute(['token' => $hashed, 'id' => $user['id']]);

                setcookie('remember_me', $user['id'] . ':' . $token, [
                    'expires'  => time() + (86400 * 30), // 30 days
                    'path'     => '/',
                    'secure'   => false, // true if HTTPS
                    'httponly' => true,
                    'samesite' => 'Lax',
                ]);
            }

            return true;
        }

        return false;
    }

    /* --------------------------------------------------------------------------
       AUTO LOGIN (via remember_me cookie)
    -------------------------------------------------------------------------- */
    public function autoLogin(): bool
    {
        if (!empty($_SESSION['user_id'])) {
            return true;
        }

        if (empty($_COOKIE['remember_me'])) {
            return false;
        }

        [$userId, $token] = explode(':', $_COOKIE['remember_me']) + [null, null];
        if (!$userId || !$token) return false;

        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id AND status = 'active' LIMIT 1");
        $stmt->execute(['id' => $userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && isset($user['remember_token']) && password_verify($token, $user['remember_token'])) {
            // Restore session
            session_regenerate_id(true);
            $_SESSION['user_id']       = $user['id'];
            $_SESSION['user_name']     = $user['name'];
            $_SESSION['role']          = $user['role'];
            $_SESSION['last_activity'] = time();
            return true;
        }

        return false;
    }

    /* --------------------------------------------------------------------------
       LOGOUT HANDLER
    -------------------------------------------------------------------------- */
    public function logout(): void
    {
        // Remove persistent cookie
        if (isset($_COOKIE['remember_me'])) {
            setcookie('remember_me', '', time() - 3600, '/');
        }

        // Destroy session safely
        session_unset();
        session_destroy();
    }

    /* --------------------------------------------------------------------------
       SESSION TIMEOUT HANDLER (default: 15 min)
       Redirects to logout page with reason=timeout
    -------------------------------------------------------------------------- */
    public static function checkSessionTimeout(int $timeoutSeconds = 900): void
    {
        if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeoutSeconds) {
            session_unset();
            session_destroy();

            // ✅ Redirect to logout page with timeout reason
            header("Location: router.php?page=logout&reason=timeout");
            exit;
        }

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