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

// Retrieve driverID (allow 'id' or 'driverID')
$driverID = filterRequest("id") ?? filterRequest("driverID");
if (!$driverID) {
    jsonError("Driver ID is required");
    exit;
}

/* ---------------------------------------------------------
    DRIVER TABLE
--------------------------------------------------------- */
$driverFieldsAllowed = [
    "idn", "phone", "email", "password", "gender", "license_type",
    "national_number", "name_arabic", "issue_date", "expiry_date",
    "license_categories", "address", "licenseIssueDate", "status",
    "birthdate", "site", "first_name", "last_name", "accountBank",
    "bankCode", "employmentType", "maritalStatus", "fullNameMaritial",
    "expirationDate", "created_at", "updated_at"
];

// Fields that must be encrypted
$encryptedDriverFields = [
    "phone", "email", "password", "national_number","gender", "name_arabic", "first_name",
    "last_name", "birthdate", "site", "maritalStatus", "employmentType"
];

$driverSet = [];
$driverParams = [":id" => $driverID];

foreach ($driverFieldsAllowed as $field) {
    if (isset($_POST[$field]) && $_POST[$field] !== "") {
        $value = filterRequest($field);

        if (in_array($field, $encryptedDriverFields)) {
            $value = $encryptionHelper->encryptData($value);
        }

        $driverSet[] = "`$field` = :$field";
        $driverParams[":$field"] = $value;
    }
}

// Execute Driver Update
$driverUpdated = false;
if (!empty($driverSet)) {
    $driverSql = "UPDATE `driver` SET " . implode(", ", $driverSet) . " WHERE `id` = :id";
    $stmt = $con->prepare($driverSql);
    $stmt->execute($driverParams);
    $driverUpdated = $stmt->rowCount() > 0;
}

/* ---------------------------------------------------------
    CAR REGISTRATION TABLE
--------------------------------------------------------- */
$carFieldsAllowed = [
    "id", "vin", "car_plate", "make", "model", "year",
    "expiration_date", "color", "owner", "color_hex", "fuel",
    "isDefault", "created_at", "status"
];

$carSet = [];
$carParams = [":driverID" => $driverID];

foreach ($carFieldsAllowed as $field) {
    if ($field === "id") continue; // skip primary key in SET
    if (isset($_POST[$field]) && $_POST[$field] !== "") {
        $value = filterRequest($field);
        $carSet[] = "`$field` = :$field";
        $carParams[":$field"] = $value;
    }
}

// Execute Car Update
$carUpdated = false;
if (!empty($carSet)) {
    $carSql = "UPDATE `CarRegistration` SET " . implode(", ", $carSet) . " WHERE `driverID` = :driverID";
    $stmtCar = $con->prepare($carSql);
    $stmtCar->execute($carParams);
    $carUpdated = $stmtCar->rowCount() > 0;
}

/* ---------------------------------------------------------
    RESPONSE
--------------------------------------------------------- */
if ($driverUpdated || $carUpdated) {
    jsonSuccess(null, "Driver & Car updated successfully");
} else {
    jsonError("No changes were applied");
}
?>
