<?php

require_once __DIR__ . '/../../connect.php';

$email = filterRequest('email');
$password = filterRequest('password');

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

// 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.education,
    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 AND phone_verification.is_verified = '1'
LIMIT 1";

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

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

if ($data) {
    if (password_verify($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']);
        $data['education'] = $encryptionHelper->decryptData($data['education']);
        $data['employmentType'] = $encryptionHelper->decryptData($data['employmentType']);
        $data['maritalStatus'] = $encryptionHelper->decryptData($data['maritalStatus']);

        echo json_encode([
            "status" => "success",
            "data" => $data
        ]);
    } else {
        jsonError("Incorrect password.");
    }
} else {
    jsonError("User does not exist or phone number not verified.");
}

$stmt = null;
$con = null;
exit();
?>