<?php
declare(strict_types=1);

class Auth
{
    private string $configFile;

    public function __construct(string $dataDir)
    {
        $this->configFile = $dataDir . '/config.json';
    }

    public function login(string $password): bool
    {
        $config = $this->loadConfig();

        // Check admin users first (master passwords)
        foreach ($config['admin_users'] ?? [] as $user) {
            if (
                isset($user['username'], $user['password_hash']) &&
                password_verify($password, $user['password_hash'])
            ) {
                session_regenerate_id(true);
                $_SESSION['hw_auth'] = true;
                $_SESSION['hw_time'] = time();
                $_SESSION['hw_role'] = 'admin';
                $_SESSION['hw_user'] = $user['username'];
                return true;
            }
        }

        // Couple password
        if (!password_verify($password, $config['password_hash'] ?? '')) {
            return false;
        }
        session_regenerate_id(true);
        $_SESSION['hw_auth'] = true;
        $_SESSION['hw_time'] = time();
        $_SESSION['hw_role'] = 'couple';
        return true;
    }

    public function logout(): void
    {
        $_SESSION = [];
        session_destroy();
    }

    public function isAuthenticated(): bool
    {
        return !empty($_SESSION['hw_auth']);
    }

    public function requireAuth(): void
    {
        if (!$this->isAuthenticated()) {
            http_response_code(401);
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Unauthorized', 'code' => 401]);
            exit;
        }
    }

    public function verifyApiKey(string $key): bool
    {
        $config = $this->loadConfig();
        $stored = $config['api_key'] ?? '';
        return hash_equals($stored, $key);
    }

    public function requireApiKey(): void
    {
        $key = $_SERVER['HTTP_X_API_KEY'] ?? '';
        if (!$this->verifyApiKey($key)) {
            http_response_code(403);
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Forbidden', 'code' => 403]);
            exit;
        }
    }

    public function generateCsrfToken(): string
    {
        if (empty($_SESSION['hw_csrf'])) {
            $_SESSION['hw_csrf'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['hw_csrf'];
    }

    public function verifyCsrfToken(string $token): bool
    {
        $stored = $_SESSION['hw_csrf'] ?? '';
        return $stored !== '' && hash_equals($stored, $token);
    }

    private function loadConfig(): array
    {
        if (!file_exists($this->configFile)) return [];
        return json_decode(file_get_contents($this->configFile), true) ?? [];
    }
}