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

$id = filterRequest("id");

// تحقق من وجود بيانات
if (empty($_POST)) {
    jsonError("No passenger data provided for update.");
    exit;
}

// الحقول الحساسة التي يجب تشفيرها
$fieldsToEncrypt = ["phone", "email", "gender", "birthdate", "site", "first_name", "last_name", "sosPhone"];

// بناء الحقول والمعاملات
$columnValues = [];
$params = [];

foreach ($fieldsToEncrypt as $field) {
    if (isset($_POST[$field])) {
        $value = filterRequest($field);
        $encryptedValue = $encryptionHelper->encryptData($value);
        $columnValues[] = "`$field` = ?";
        $params[] = $encryptedValue;
    }
}

// تحقق من أن هناك حقول للتحديث
if (empty($columnValues)) {
    jsonError("No valid encrypted passenger data provided for update.");
    exit;
}

// تركيب جملة SQL
$setClause = implode(", ", $columnValues);
$params[] = $id;

$sql = "UPDATE `passengers` SET $setClause WHERE `id` = ?";

try {
    $stmt = $con->prepare($sql);

    foreach ($params as $index => $value) {
        $stmt->bindValue($index + 1, $value);
    }

    if ($stmt->execute()) {
        jsonSuccess(null, "Passenger data updated successfully with encryption");
    } else {
        jsonError("Failed to update passenger data");
    }

} catch (PDOException $e) {
    jsonError("Database error: " . $e->getMessage());
}
?>