<?php
// ============================================================
// loginFirstTimeDriver.php — توكن التسجيل الأول (السائق)
// تم التحديث: استخدام One-Time Registration Tokens
// ============================================================

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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: https://siromove.com');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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('allowedDriver1');
    $allowed2 = getenv('allowedDriver2');
    $allowedAudiences = array_values(array_filter([$allowed1, $allowed2]));

    if (empty($id) || empty($password) || empty($audience)) {
        jsonError('Missing input fields.', 400);
    }

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

    // ✅ FIX H-06: استخدام One-Time Registration Token عبر Redis بدلاً من كلمة مرور ثابتة
    $useOneTimeToken = getenv('USE_ONE_TIME_REG_TOKEN') === 'true';
    
    if ($useOneTimeToken && $redis) {
        // التحقق من وجود توكن صالح في Redis
        $storedToken = $redis->get("reg_token:{$id}");
        if (!$storedToken || !hash_equals($storedToken, $password)) {
            securityLog("FirstTimeDriver failed: Invalid or expired one-time token", ['id' => $id]);
            jsonError('Invalid or expired registration token.', 401);
        }
        // حذف التوكن بعد الاستخدام (One-Time)
        $redis->del("reg_token:{$id}");
    } else {
        // Fallback آمن: استخدام كلمة المرور الثابتة مع Rate Limiting مشدد
        $passwordnewpassenger = getenv('passwordnewpassenger');
        if (!password_verify($password, $passwordnewpassenger)) {
            securityLog("FirstTimeDriver login failed (password)", ['id' => $id]);
            jsonError('Invalid credentials.', 401);
        }
    }

    $fpPepper = getenv('FP_PEPPER') ?: '';
    $fpHash = (!empty($fingerprint) && !empty($fpPepper))
        ? hash('sha256', $fingerprint . $fpPepper)
        : null;

    // ✅ FIX C-02: استخدام getenv بدلاً من file_get_contents الثابت
    $keyPath = getenv('JWT_SECRET_KEY_PATH');
    if ($keyPath && file_exists($keyPath)) {
        $secretKey = trim(file_get_contents($keyPath));
    } else {
        $secretKey = getenv('JWT_SECRET_KEY') ?: '';
    }

    $payload = [
        'user_id'    => 'new',
        'sub'        => $id,
        'token_type' => 'registration',
        'exp'        => time() + 450, 
        'iat'        => time(),
        'iss'        => getenv('APP_ISSUER') ?: 'Tripz',
        'aud'        => $audience,
        'jti'        => bin2hex(random_bytes(16)),
    ];

    if ($fpHash !== null) {
        $payload['fingerPrint'] = $fpHash;
    }

    $jwt = Firebase\JWT\JWT::encode($payload, $secretKey, 'HS256');

    jsonSuccess([
        'jwt'        => $jwt,
        'expires_in' => 450,
    ]);

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