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

if ($role !== 'admin' && $role !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized: Admin access required']);
    exit;
}

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

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

if (empty($id)) { jsonError("Passenger ID is required"); exit; }
if ($first_name === null && $last_name === null && $new_phone === null) {
    jsonError("Nothing to update"); exit;
}

$sets   = [];
$params = [];

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

    // منع تكرار الهاتف على راكب آخر
    $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 && $row['id'] != $id) {
        jsonError("Phone already used by another passenger");
        exit;
    }
}

$whereSql    = "id = :pid";
$whereParams = ['pid' => $id];

$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"); }