<?php
// Secure Cryptographic API Protection Guard

define('SECRET_SIGNATURE_KEY', 'GlobInvestAdminSecureKey2026#TokenPlatform');

function verifyApiSignature() {
    $headers = getallheaders();
    
    // Extract signature validation headers cleanly
    $clientSignature = $headers['X-Signature'] ?? $headers['x-signature'] ?? '';
    $clientTimestamp = $headers['X-Timestamp'] ?? $headers['x-timestamp'] ?? '';
    
    if (empty($clientSignature) || empty($clientTimestamp)) {
        header("HTTP/1.1 401 Unauthorized");
        echo json_encode(["success" => false, "message" => "Security Headers Missing"]);
        exit;
    }
    
    // 1. Prevent Replay Attacks: Reject requests older than 5 minutes (300 seconds)
    $serverTimestamp = time();
    if (abs($serverTimestamp - intval($clientTimestamp)) > 300) {
        header("HTTP/1.1 403 Forbidden");
        echo json_encode(["success" => false, "message" => "Request Expired. Sync your device clock."]);
        exit;
    }
    
    // 2. Extract incoming request body payload byte stream
    $requestBody = file_get_contents('php://input');
    
    // 3. Recalculate HMAC signature on the server side using the SHA256 algorithm
    $expectedSignature = hash_hmac('sha256', $clientTimestamp . $requestBody, SECRET_SIGNATURE_KEY);
    
    // 4. Perform binary safe comparison string checks
    if (!hash_equals($expectedSignature, $clientSignature)) {
        header("HTTP/1.1 403 Forbidden");
        echo json_encode(["success" => false, "message" => "Invalid Security Signature Hash"]);
        exit;
    }
}

// Automatically execute validation check rule on file inclusion
verifyApiSignature();