<?php
// middleware.php
function verifyApiRequest() {
    $headers = getallheaders();
    
    $apiKey = $headers['x-api-key'] ?? '';
    $timestamp = $headers['x-ts'] ?? 0;
    $clientSign = $headers['x-sign'] ?? '';
    
    $secretApiKey = "my-secret-api-key-123"; // Frontend JS se match kiya hua
    $signSalt = "FIXRESULT_PUBLIC_SALT";
    
    // Check API Key
    if ($apiKey !== $secretApiKey) {
        header('HTTP/1.1 401 Unauthorized');
        echo json_encode(["success" => false, "message" => "Invalid API Key"]);
        exit;
    }
    
    // Timestamp verification (Reject requests older than 5 minutes for security)
    $currentTs = time();
    if (abs($currentTs - (int)$timestamp) > 300) {
        header('HTTP/1.1 403 Forbidden');
        echo json_encode(["success" => false, "message" => "Request expired"]);
        exit;
    }
    
    // Signature Validation (SHA-256)
    $serverSign = hash('sha256', $apiKey . $timestamp . $signSalt);
    if (!hash_equals($serverSign, $clientSign)) {
        header('HTTP/1.1 403 Forbidden');
        echo json_encode(["success" => false, "message" => "Invalid Signature"]);
        exit;
    }
}
?>