<?php
// ============================================================
// loginFirstTimeDriver.php — توكن التسجيل الأول (السائق)
// ============================================================

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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: https://intaleqapp.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]));
    $passwordnewpassenger = getenv('passwordnewpassenger');

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

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

    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;

    $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;
    }

    $secretKey = trim(file_get_contents('/home/intaleq-api/.secret_key'));
    $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);
}