<?php
// loginUsingCredentialsWithoutGooglePassenger.php
// مسار مخصص لفاحصي التطبيق (الركاب) يعمل بدون JWT Interceptors

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

$email = filterRequest("email");
$password = filterRequest("password");
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');
$audience = filterRequest('aud') ?: 'siro_passenger';

if (!$email || !$password) {
    echo json_encode(["status" => "failure", "message" => "Email and password are required"]);
    exit();
}

try {
    $con = Database::get('main');
    
    // تشفير الإيميل للبحث في قاعدة البيانات
    $encryptedEmail = $encryptionHelper->encryptData($email);

    $sql = "SELECT
                p.`id`,
                p.`phone`,
                p.`email`,
                p.`gender`,
                p.`status`,
                p.`birthdate`,
                p.`site`,
                p.`first_name`,
                p.`last_name`,
                p.`sosPhone`,
                p.`education`,
                p.`employmentType`,
                p.`maritalStatus`,
                phone_verification_passenger.verified,
                invitesToPassengers.isInstall,
                invitesToPassengers.inviteCode,
                invitesToPassengers.isGiftToken
            FROM passengers p
            LEFT JOIN phone_verification_passenger 
                ON phone_verification_passenger.phone_number = p.phone
            LEFT JOIN invitesToPassengers 
                ON invitesToPassengers.inviterPassengerPhone = p.phone
            WHERE p.email = :email AND p.password = :password
            LIMIT 1";

    $stmt = $con->prepare($sql);
    $stmt->bindParam(':email', $encryptedEmail);
    // نفترض أن كلمة المرور تُخزن بنص صريح للفاحصين أو يتم معالجتها مسبقاً (حسب آلية فلاتر القديمة)
    $stmt->bindParam(':password', $password);
    $stmt->execute();

    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    $count = $stmt->rowCount();

    if ($count > 0) {
        // فك تشفير البيانات للرد
        if(isset($data['phone'])) $data['phone'] = $encryptionHelper->decryptData($data['phone']);
        if(isset($data['email'])) $data['email'] = $encryptionHelper->decryptData($data['email']);
        if(isset($data['gender'])) $data['gender'] = $encryptionHelper->decryptData($data['gender']);
        if(isset($data['birthdate'])) $data['birthdate'] = $encryptionHelper->decryptData($data['birthdate']);
        if(isset($data['site'])) $data['site'] = $encryptionHelper->decryptData($data['site']);
        if(isset($data['first_name'])) $data['first_name'] = $encryptionHelper->decryptData($data['first_name']);
        if(isset($data['last_name'])) $data['last_name'] = $encryptionHelper->decryptData($data['last_name']);
        if(isset($data['sosPhone'])) $data['sosPhone'] = $encryptionHelper->decryptData($data['sosPhone']);
        if(isset($data['education'])) $data['education'] = $encryptionHelper->decryptData($data['education']);
        if(isset($data['employmentType'])) $data['employmentType'] = $encryptionHelper->decryptData($data['employmentType']);
        if(isset($data['maritalStatus'])) $data['maritalStatus'] = $encryptionHelper->decryptData($data['maritalStatus']);

        // توليد الـ JWT بصلاحية (tester) لتميزهم عن المستخدمين الفعليين
        $jwtService = new JwtService($redis);
        $jwt = $jwtService->generateAccessToken($data['id'], 'tester', $audience, $fingerprint);

        echo json_encode([
            "status" => "success",
            "jwt" => $jwt,
            "data" => [$data] // مطابق لنسق التطبيق الذي يتوقع مصفوفة
        ], JSON_UNESCAPED_UNICODE);

    } else {
        echo json_encode([
            "status" => "failure",
            "message" => "Invalid credentials"
        ]);
    }

} catch (Exception $e) {
    error_log("Error in loginUsingCredentialsWithoutGooglePassenger: " . $e->getMessage());
    echo json_encode([
        "status" => "failure",
        "message" => "Server error"
    ]);
}
exit();
