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

$id = filterRequest("id");

$allowedFields = [
    "kazan", "comfortPrice", "speedPrice", "deliveryPrice",
    "freePrice", "latePrice", "heavyPrice", "adminId", "naturePrice", "fuelPrice", "familyPrice"
];

$setParts = [];
$params = [];

foreach ($allowedFields as $field) {
    if (isset($_POST[$field])) {
        $value = filterRequest($field);
        $setParts[] = "`$field` = :$field";
        $params[":$field"] = $value;
    }
}

if (empty($setParts)) {
    jsonError("No valid fields to update.");
    exit;
}

$sql = "UPDATE `kazan` SET " . implode(", ", $setParts) . " WHERE `id` = :id";
$params[":id"] = $id;

$stmt = $con->prepare($sql);
$stmt->execute($params);

$userIdToLog = $user_id ?? 'unknown_admin';

// تسجيل العملية في السجل دائماً
$auditResult = logAudit($con, $userIdToLog, "تحديث عمولة/أسعار النظام (Kazan)", "kazan", $id, $params);

$debugLog = "[" . date('Y-m-d H:i:s') . "] Kazan Update Triggered. User: $userIdToLog. Audit Result: " . ($auditResult === true ? 'SUCCESS' : $auditResult) . "\n";
file_put_contents(__DIR__ . '/audit_debug.txt', $debugLog, FILE_APPEND);

if ($stmt->rowCount() > 0) {
    jsonSuccess(null, "Kazan data updated successfully. Audit: " . ($auditResult === true ? 'OK' : $auditResult));
} else {
    jsonSuccess(null, "Kazan data remains unchanged or updated. Audit: " . ($auditResult === true ? 'OK' : $auditResult));
}
?>