<?php
// ============================================================
// loginJwtWalletDriver.php — توكن محفظة السائق
// ============================================================

require_once __DIR__ . '/core/bootstrap.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: https://walletintaleq.intaleq.xyz');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Device-FP');

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

try {
    $limiter = new RateLimiter($redis);
    $limiter->enforce(RateLimiter::identifier(), 'login');

    $id          = filterRequest('id');
    $password    = filterRequest('password');
    $audience    = filterRequest('aud');
    $fingerPrint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');

    $allowed1 = getenv('allowedWallet1');
    $allowed2 = getenv('allowedWallet2');
    $allowedAudiences = array_values(array_filter([$allowed1, $allowed2]));
    $passwordnewpassenger = getenv('passwordnewpassenger');
    $fpPepper = getenv('FP_PEPPER') ?: '';

    if (empty($id) || empty($password) || empty($audience) || empty($fingerPrint)) {
        jsonError('Missing required parameters', 400);
    }

    if (!in_array($audience, $allowedAudiences, true)) {
        jsonError('Invalid audience', 400);
    }

    if (!password_verify($password, $passwordnewpassenger)) {
        securityLog("WalletDriver login failed (password)", ['id' => $id]);
        jsonError('Invalid credentials', 401);
    }

    $con = Database::get('main');

    $stmt = $con->prepare('
        SELECT captain_id, fingerPrint
        FROM driverToken
        WHERE captain_id = :captain_id
        LIMIT 1
    ');
    $stmt->execute([':captain_id' => $id]);
    $tokenData = $stmt->fetch();

    $storedFp = $tokenData['fingerPrint'] ?? '';

    if (empty($storedFp)) {
        jsonError('Device fingerprint not registered', 403);
    }

    $fpVerified = false;
    if (!empty($fpPepper)) {
        $expectedHash = hash('sha256', $fingerPrint . $fpPepper);
        $fpVerified   = hash_equals($storedFp, $expectedHash);
        if (!$fpVerified) {
            $fpVerified = hash_equals($storedFp, $fingerPrint);
        }
    } else {
        $fpVerified = hash_equals($storedFp, $fingerPrint);
    }

    if (!$fpVerified) {
        securityLog("WalletDriver FP mismatch", ['id' => $id]);
        jsonError('Device verification failed', 403);
    }

    $limiter->reset(RateLimiter::identifier(), 'login');

    $fpHash = hash('sha256', $fingerPrint . $fpPepper);

    $payload = [
        'user_id'     => $id,
        'fingerPrint' => $fpHash,
        'exp'         => time() + 300, // 5 دقائق تم إصلاحه (كان 60)
        'iat'         => time(),
        'iss'         => 'Tripz-Wallet',
        'aud'         => $audience,
        'jti'         => bin2hex(random_bytes(16)),
    ];

    $secretKey = trim(file_get_contents('/home/siro-api/.secret_key_pay'));
    $jwt = Firebase\JWT\JWT::encode($payload, $secretKey, 'HS256');

    $hmac = hash_hmac('sha256', $id, getenv('SECRET_KEY_HMAC'));

    jsonSuccess([
        'status'     => 'success',
        'jwt'        => $jwt,
        'hmac'       => $hmac,
        'expires_in' => 300, // تم التعديل
    ]);

} catch (PDOException $e) {
    securityLog("LoginWalletDriver PDO Error", ['msg' => $e->getMessage()]);
    jsonError('Database error', 500);
} catch (Exception $e) {
    securityLog("LoginWalletDriver Error", ['msg' => $e->getMessage()]);
    jsonError('Server error', 500);
}