<?php

require_once __DIR__ . '/constants.php';

function get_auth_token(): string {
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
    if (!$authHeader && function_exists('getallheaders')) {
        $allHeaders = getallheaders();
        $authHeader = $allHeaders['Authorization'] ?? $allHeaders['authorization'] ?? '';
    }
    if (str_starts_with($authHeader, 'Bearer ')) {
        return substr($authHeader, 7);
    }
    return '';
}

function supabase_rest(string $method, string $endpoint, array $data = [], ?string $token = null): array {
    $url = SUPABASE_URL . '/rest/v1/' . ltrim($endpoint, '/');
    $headers = [
        'Content-Type: application/json',
        'apikey: ' . SUPABASE_ANON_KEY,
        'Authorization: Bearer ' . ($token ?: SUPABASE_ANON_KEY),
    ];

    if ($method === 'GET' && !empty($data)) {
        $url .= '?' . http_build_query($data);
        $data = [];
    }

    if ($method === 'POST' || $method === 'PATCH') {
        $headers[] = 'Prefer: return=representation';
    }

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    } elseif ($method === 'PATCH') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    } elseif ($method === 'DELETE') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    unset($ch);

    return [
        'status' => $httpCode,
        'data' => json_decode($response, true),
    ];
}

function check_feature_flag(string $flag): bool {
    $res = supabase_rest('GET', "feature_flags?id=eq.{$flag}&select=is_enabled", [], SUPABASE_SERVICE_KEY);
    return !empty($res['data']) && $res['data'][0]['is_enabled'] === true;
}

function supabase_auth(string $endpoint, array $data = [], ?string $token = null, string $method = 'POST'): array {
    $url = SUPABASE_URL . '/auth/v1/' . ltrim($endpoint, '/');
    $headers = [
        'Content-Type: application/json',
        'apikey: ' . SUPABASE_ANON_KEY,
    ];

    if ($token) {
        $headers[] = 'Authorization: Bearer ' . $token;
    }

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    unset($ch);

    return [
        'status' => $httpCode,
        'data' => json_decode($response, true),
    ];
}
