<?php
// ============================================================
// loginUsingCredentialsWithoutGoogle.php
// مخصص لدخول الفاحصين (Testers) بالإيميل والباسورد
// ============================================================

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

$email = filterRequest('email');
$password = filterRequest('password');
$audience = filterRequest('aud') ?? 'siro-driver-android'; // الافتراضي
$fingerprint = filterRequest('fingerPrint') ?? filterRequest('fingerprint');

// تشفير الإيميل لاستخدامه في الاستعلام
$encryptedEmail = $encryptionHelper->encryptData($email);

try {
    $con = Database::get('main');
    
    // SQL لاسترجاع المستخدم بناءً على البريد الإلكتروني المشفر
    $sql = "SELECT
        driver.id,
        driver.phone,
        driver.email,
        driver.gender,
        driver.birthdate,
        driver.site,
        driver.first_name,
        driver.last_name,
        driver.bankCode,
        driver.accountBank,
        driver.employmentType,
        driver.maritalStatus,
        driver.created_at,
        driver.updated_at,
        driver.password,
        phone_verification.is_verified,
        CarRegistration.make,
        CarRegistration.model,
        CarRegistration.year
    FROM driver
    LEFT JOIN phone_verification ON phone_verification.phone_number = driver.phone
    LEFT JOIN CarRegistration ON CarRegistration.driverID = driver.id
    WHERE
        driver.email = :email
    LIMIT 1";

    $stmt = $con->prepare($sql);
    $stmt->bindParam(':email', $encryptedEmail);
    $stmt->execute();

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

    if ($data) {
        // فحص الباسورد (في نظامنا، يمكن أن يكون الباسورد هو HMAC أو نص عادي للفاحصين)
        // لنفترض أن الفاحص له باسورد عادي أو مشفر بـ bcrypt
        if (password_verify($password, $data['password']) || $password === $data['password']) {
            unset($data['password']);

            // فك تشفير الحقول الحساسة
            $data['phone'] = $encryptionHelper->decryptData($data['phone']);
            $data['email'] = $encryptionHelper->decryptData($data['email']);
            $data['gender'] = $encryptionHelper->decryptData($data['gender']);
            $data['birthdate'] = $encryptionHelper->decryptData($data['birthdate']);
            $data['site'] = $encryptionHelper->decryptData($data['site']);
            $data['first_name'] = $encryptionHelper->decryptData($data['first_name']);
            $data['last_name'] = $encryptionHelper->decryptData($data['last_name']);
            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 {
            jsonError("Incorrect password.");
        }
    } else {
        jsonError("User does not exist.");
    }
} catch (Exception $e) {
    error_log("[Tester Login Error] " . $e->getMessage());
    jsonError("Server error occurred.");
} finally {
    $stmt = null;
    $con = null;
}
exit();
?>