<?php
require_once __DIR__ . '/Database.php';

/**
 * Authentication via PHP sessions (replaces NextAuth)
 */
class Auth {
    public static function start(): void {
        if (session_status() === PHP_SESSION_NONE) {
            $lifetime = defined('SESSION_LIFETIME') ? SESSION_LIFETIME : 86400;
            ini_set('session.cookie_lifetime', (string)$lifetime);
            ini_set('session.gc_maxlifetime', (string)$lifetime);
            session_start();
        }
    }

    public static function login(string $username, string $password): bool {
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM Admin WHERE username = :username");
        $stmt->execute([':username' => $username]);
        $admin = $stmt->fetch();

        if (!$admin) return false;
        if (!password_verify($password, $admin['password'])) return false;

        $_SESSION['admin_id'] = $admin['id'];
        $_SESSION['admin_name'] = $admin['username'];
        $_SESSION['admin_role'] = 'admin';
        $_SESSION['admin_login_time'] = time();
        return true;
    }

    public static function logout(): void {
        self::start();
        $_SESSION = [];
        if (ini_get("session.use_cookies")) {
            $p = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $p["path"], $p["domain"], $p["secure"], $p["httponly"]);
        }
        session_destroy();
    }

    public static function isAdmin(): bool {
        self::start();
        if (!isset($_SESSION['admin_role']) || $_SESSION['admin_role'] !== 'admin') return false;
        $lifetime = defined('SESSION_LIFETIME') ? SESSION_LIFETIME : 86400;
        if (isset($_SESSION['admin_login_time']) && (time() - $_SESSION['admin_login_time']) > $lifetime) {
            self::logout();
            return false;
        }
        return true;
    }

    public static function requireAdmin(): void {
        if (!self::isAdmin()) {
            http_response_code(401);
            echo json_encode(['error' => 'غير مصرح. يرجى تسجيل الدخول أولاً']);
            exit;
        }
    }

    public static function getSession(): ?array {
        self::start();
        if (!self::isAdmin()) return null;
        return [
            'user' => [
                'id' => $_SESSION['admin_id'] ?? '',
                'name' => $_SESSION['admin_name'] ?? '',
                'role' => $_SESSION['admin_role'] ?? '',
            ]
        ];
    }

    public static function createDefaultAdmin(string $password): void {
        $db = Database::getInstance();
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $id = 'admin-' . bin2hex(random_bytes(8));
        try {
            $stmt = $db->prepare("INSERT OR IGNORE INTO Admin (id, username, password) VALUES (:id, 'admin', :pw)");
            $stmt->execute([':id' => $id, ':pw' => $hash]);
        } catch (PDOException $e) {
            // Admin might already exist
        }
    }
}