<?php
header("Content-Type: application/json; charset=UTF-8");
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once "db.php";

// ✅ استقبال البيانات بصيغة JSON
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);

// ✅ التحقق من وجود ID للتعديل
$id = isset($data['id']) ? intval($data['id']) : 0;
if ($id <= 0) {
    echo json_encode([
        "status" => "error",
        "message" => "❌ رقم المعاملة غير صالح"
    ]);
    exit;
}

// ✅ التحقق من الحقول المطلوبة
$required = ["payment_method", "deposit_date", "balance_value", "type"];
foreach ($required as $key) {
    if (empty($data[$key])) {
        echo json_encode([
            "status" => "error",
            "message" => "❌ الحقل '$key' مطلوب"
        ]);
        exit;
    }
}

// ✅ تجهيز الاستعلام للتعديل
$sql = "UPDATE `TransactionsMH` SET 
    `method` = ?, 
    `date` = ?, 
    `value` = ?, 
    `type` = ?, 
    `AttachmentPath` = ?, 
    `notes` = ?
WHERE `id` = ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode([
        "status" => "error",
        "message" => "❌ فشل تجهيز الاستعلام"
    ]);
    exit;
}

$method = $data['payment_method'];
$date = $data['deposit_date'];
$value = floatval($data['balance_value']);
$type = $data['type'];
$attachment = $data['AttachmentPath'] ?? '';
$notes = $data['notes'] ?? '';

$stmt->bind_param("ssdsssi", $method, $date, $value, $type, $attachment, $notes, $id);
$success = $stmt->execute();

if ($success) {
    echo json_encode([
        "status" => "success",
        "message" => "✅ تم تعديل المعاملة بنجاح"
    ], JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode([
        "status" => "error",
        "message" => "❌ فشل في تنفيذ التعديل",
        "error" => $stmt->error
    ], JSON_UNESCAPED_UNICODE);
}

$stmt->close();
$conn->close();
?>
