
<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/app_helpers.php';

function api_json($data, int $status = 200): void {
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

function api_bearer_token(): string {
    $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
    if (preg_match('/Bearer\s+(.*)$/i', $header, $m)) return trim($m[1]);
    return trim((string)($_GET['api_token'] ?? ''));
}

function api_require_client(PDO $db): array {
    $token = api_bearer_token();
    if ($token === '') api_json(['success'=>false,'message'=>'Missing Bearer token'],401);
    try {
        $db->exec("CREATE TABLE IF NOT EXISTS api_clients (
            id INT AUTO_INCREMENT PRIMARY KEY,
            client_name VARCHAR(120) NOT NULL,
            token_hash VARCHAR(255) NOT NULL,
            permissions JSON NULL,
            is_active TINYINT(1) NOT NULL DEFAULT 1,
            last_used_at DATETIME NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY uq_api_clients_name (client_name),
            INDEX idx_api_clients_active (is_active)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    } catch (Throwable $e) {}
    $stmt = $db->query("SELECT * FROM api_clients WHERE is_active = 1");
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $client) {
        if (password_verify($token, $client['token_hash'])) {
            $db->prepare('UPDATE api_clients SET last_used_at = NOW() WHERE id = :id')->execute([':id'=>(int)$client['id']]);
            return $client;
        }
    }
    api_json(['success'=>false,'message'=>'Invalid API token'],403);
}

function api_body(): array {
    $raw = file_get_contents('php://input');
    $data = json_decode($raw ?: '{}', true);
    return is_array($data) ? $data : [];
}
