<?php

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

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

// تشفير الحقول المطلوبة قبل الاستعلام
$email = $encryptionHelper->encryptData($email);
$phone = $encryptionHelper->encryptData($phone);

$sql = "SELECT
    driver.id,
    driver.phone,
    driver.email,
    driver.password,
    driver.gender,
    driver.birthdate,
    driver.site,
    driver.first_name,
    driver.last_name,
    driver.education,
    driver.employmentType,
    driver.maritalStatus,
    driver.created_at,
    driver.updated_at,
    email_verifications.verified
FROM
    driver
LEFT JOIN email_verifications ON email_verifications.email = driver.email
WHERE
    driver.phone = :phone AND driver.email = :email";

$stmt = $con->prepare($sql);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':phone', $phone);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();

if ($count > 0) {
    $stored_password = $data[0]['password'];
    if (password_verify($password, $stored_password)) {

        // فك التشفير للحقول الحساسة
        $data[0]['phone']           = $encryptionHelper->decryptData($data[0]['phone']);
        $data[0]['email']           = $encryptionHelper->decryptData($data[0]['email']);
        $data[0]['gender']          = $encryptionHelper->decryptData($data[0]['gender']);
        $data[0]['birthdate']       = $encryptionHelper->decryptData($data[0]['birthdate']);
        $data[0]['site']            = $encryptionHelper->decryptData($data[0]['site']);
        $data[0]['first_name']      = $encryptionHelper->decryptData($data[0]['first_name']);
        $data[0]['last_name']       = $encryptionHelper->decryptData($data[0]['last_name']);
        $data[0]['education']       = $encryptionHelper->decryptData($data[0]['education']);
        $data[0]['employmentType']  = $encryptionHelper->decryptData($data[0]['employmentType']);
        $data[0]['maritalStatus']   = $encryptionHelper->decryptData($data[0]['maritalStatus']);

        unset($data[0]['password']); // لا نرجّع الباسورد
        jsonSuccess($data);
    } else {
        jsonError("Incorrect password.");
    }
} else {
    jsonError("User does not exist.");
}
?>