<?php

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

$phone = filterRequest("phone");

// تنظيف الرقم من أي مسافات أو رموز زائدة
$phone = preg_replace('/[^0-9]/', '', $phone);

// احتمالات الرقم (بالصفر الدولي أو بدونه)
$phoneVariants = [];
$phoneVariants[] = $phone; // كما هو (مثلاً 0992952235)

if (str_starts_with($phone, '0')) {
    $phoneVariants[] = '963' . substr($phone, 1); // تحويل 09 إلى 9639
} elseif (str_starts_with($phone, '963')) {
    $phoneVariants[] = '0' . substr($phone, 3); // تحويل 9639 إلى 09
}

// Encrypt each variant to see if any match the encrypted column
$encVariants = [];
foreach ($phoneVariants as $v) {
    $encVariants[] = $encryptionHelper->encryptData($v);
}

error_log("[GIFT_CHECK] Received Phone: " . $phone);
error_log("[GIFT_CHECK] Variants: " . implode(', ', $phoneVariants));

// بناء استعلام يبحث عن كل الاحتمالات (المشفرة وغير المشفرة)
$placeholders = [];
$params = [];

foreach ($encVariants as $i => $ev) {
    $placeholders[] = "phone = :enc$i";
    $params[":enc$i"] = $ev;
}
foreach ($phoneVariants as $i => $pv) {
    $placeholders[] = "phone = :raw$i";
    $params[":raw$i"] = $pv;
}

$sql = "SELECT * FROM `driver` WHERE " . implode(" OR ", $placeholders);

$stmt = $con->prepare($sql);
foreach ($params as $key => $val) {
    $stmt->bindValue($key, $val);
}

$stmt->execute();

if ($stmt->rowCount() > 0) {

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Decrypt sensitive fields
    foreach ($rows as &$row) {
        if (!empty($row['phone'])) {
            $row['phone'] = $encryptionHelper->decryptData($row['phone']);
        }
      if (!empty($row['name_arabic'])) {
            $row['name_arabic'] = $encryptionHelper->decryptData($row['name_arabic']);
        }
    }

    jsonSuccess($rows);

} else {
    jsonError("No recent driver location activity found");
}

?>
