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



$id          = filterRequest("id");            // مفضّل

$first_name  = filterRequest("first_name");
$last_name   = filterRequest("last_name");
$new_phone   = filterRequest("phone");

if (empty($id) ) { jsonError("Provide id or phone_lookup"); exit; }
if ($first_name === null && $last_name === null && $new_phone === null) {
    jsonError("Nothing to update"); exit;
}

$sets   = [];
$params = [];
 	$new_phone  = $encryptionHelper->encryptData($new_phone);
	$first_name  = $encryptionHelper->encryptData($first_name);
	$last_name  = $encryptionHelper->encryptData($last_name);

    $enc_norm = $encryptionHelper->encryptData($norm);
if ($first_name !== null) { $sets[] = "first_name = :first_name"; $params['first_name'] = trim($first_name); }
if ($last_name  !== null) { $sets[] = "last_name  = :last_name";  $params['last_name']  = trim($last_name);  }
if ($new_phone  !== null) { 
    $sets[] = "phone      = :phone";      
    $params['phone'] = trim($new_phone);

    // منع تكرار الهاتف على راكب آخر
    $q = $con->prepare("SELECT id FROM passengers WHERE phone = :ph LIMIT 1");
    $q->execute(['ph' => $params['phone']]);
    $row = $q->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        if (!empty($id) && $row['id'] != $id) { jsonError("Phone already used by another passenger"); exit; }
        if (empty($id) && $row['id'] != $phoneLookup) { jsonError("Phone already used by another passenger"); exit; }
    }
}

$whereSql    = "";
$whereParams = [];
if (!empty($id))       { $whereSql = "id = :pid";   $whereParams['pid']   = $id; }
else                   { $whereSql = "phone = :plk"; $whereParams['plk']  = $phoneLookup; }

$sql = "UPDATE passengers SET ".implode(", ", $sets).", updated_at = CURRENT_TIMESTAMP WHERE $whereSql";
$stmt = $con->prepare($sql);
$ok = $stmt->execute(array_merge($params, $whereParams));

if ($ok && $stmt->rowCount() > 0) { jsonSuccess(null, "Passenger updated"); }
else                              { jsonError("No change or passenger not found"); }