<?php
/**
 * jwtconnect.php — Unified Authentication Gateway (بوابة المصادقة الموحدة)
 * 
 * ═══════════════════════════════════════════════════════════════
 * SECURITY UPGRADE: هذا الملف أصبح بوابة مصادقة إجبارية.
 * كل طلب يجب أن يمر بأحد المسارات التالية:
 *
 *   Path 1: S2S API Key     → X-S2S-Api-Key header
 *   Path 2: Payment Key     → PAYMENT_KEY header  
 *   Path 3: Webhook Token   → X-Auth-Token header
 *   Path 4: Cron Key / CLI  → X-Cron-Key header أو CLI execution
 *   Path 5: Nabeh API Key   → X-API-Key header (server-to-server من منصة نبه)
 *   Path 6: JWT (default)   → Authorization: Bearer <token>
 *
 * أي طلب بدون أي مصادقة → يُرفض تلقائياً من authenticateJWT()
 * ═══════════════════════════════════════════════════════════════
 */

// Load environment variables from .env file
require_once realpath(__DIR__ . '/../vendor/autoload.php');
require_once 'load_env.php';
$env_file = '/home/intaleq-wallet/env/.env';
loadEnvironment($env_file);

// Get environment variables (You don't need user/pass for JWT auth itself)
$secretKey = getenv('SECRET_KEY'); // Only need the secret key now

// --- CORS Headers ---
$allowedOrigins = [
    
    'https://wallet.siromove.com',
    'https://wallet-syria.siromove.com',
    'https://wallet-egypt.siromove.com',
    'https://wallet-jordan.siromove.com',
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins)) {
    header("Access-Control-Allow-Origin: $origin");
} else {
    header("Access-Control-Allow-Origin: https://walletintaleq.intaleq.xyz");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-S2S-Api-Key, PAYMENT_KEY, X-Auth-Token, X-Cron-Key, X-HMAC-Auth, X-Device-FP, X-API-Key");
header('Content-Type: application/json');

// Handle preflight requests (OPTIONS)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

$dbname = getenv('dbname');

// --- Database Connection ---
try {
    $dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8mb4";
    $options = [
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"
    ];
    $user = getenv('USER');
    $pass = getenv('PASS');
    $con = new PDO($dsn, $user, $pass, $options);

    // --- Load Functions ---
    include "functions.php";

    // ═══════════════════════════════════════════════════════════
    // UNIFIED AUTHENTICATION GATEWAY (بوابة المصادقة الموحدة)
    // ═══════════════════════════════════════════════════════════

    $authMethod = null;
    $decodedToken = null;

    // --- Path 1: S2S API Key (server-to-server calls) ---
    $s2sKey = $_SERVER['HTTP_X_S2S_API_KEY'] ?? '';
    $expectedS2s = getenv('S2S_SHARED_KEY');
    
    if (!empty($s2sKey) && !empty($expectedS2s) && hash_equals($expectedS2s, $s2sKey)) {
        $authMethod = 'S2S';
    }

    // --- Path 2: Payment Key (transfer endpoint) ---
    if (!$authMethod) {
        $paymentKey = $_SERVER['HTTP_PAYMENT_KEY'] ?? '';
        $expectedPayment = getenv('PAYMENT_KEY');
        
        if (!empty($paymentKey) && !empty($expectedPayment) && hash_equals($expectedPayment, $paymentKey)) {
            $authMethod = 'PAYMENT_KEY';
        }
    }

    // --- Path 3: Webhook Auth Token (MTN/Cliq external services) ---
    if (!$authMethod) {
        $webhookToken = $_SERVER['HTTP_X_AUTH_TOKEN'] ?? '';
        $expectedWebhook = getenv('WEBHOOK_AUTH_TOKEN');
        
        if (!empty($expectedWebhook) && !empty($webhookToken) && hash_equals($expectedWebhook, $webhookToken)) {
            $authMethod = 'WEBHOOK';
        }
    }

    // --- Path 4: Cron Key / CLI execution ---
    if (!$authMethod) {
        // 4a: CLI execution (php script.php directly)
        if (php_sapi_name() === 'cli' || php_sapi_name() === 'cli-server') {
            $authMethod = 'CLI';
        } else {
            // 4b: HTTP cron call with key header
            $cronKey = $_SERVER['HTTP_X_CRON_KEY'] ?? '';
            $expectedCron = getenv('CRON_KEY');
            
            if (!empty($cronKey) && !empty($expectedCron) && hash_equals($expectedCron, $cronKey)) {
                $authMethod = 'CRON';
            }
        }
    }

    // --- Path 5: Nabeh API Key (server-to-server من منصة نبه) ---
    if (!$authMethod) {
        $nabehKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
        $expectedNabeh = getenv('NABEH_API_KEY');

        if (!empty($nabehKey) && !empty($expectedNabeh) && hash_equals($expectedNabeh, $nabehKey)) {
            $authMethod = 'NABEH';
        }
    }

    // --- Path 6 (DEFAULT): JWT Authentication ---
    // إذا لم يتم التعرف على أي مسار آخر، يُفرض JWT.
    // authenticateJWT() ستُرجع 401 وتوقف التنفيذ إذا لم يكن هناك JWT صالح.
    if (!$authMethod) {
        $decodedToken = authenticateJWT();
        $authMethod = 'JWT';
    }

} catch (PDOException $e) {
    error_log($e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'A database error occurred.']);
    exit;
}
?>