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

require_once "db.php";

// استقبال البيانات من الـ AJAX
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);

// تحقق من البيانات المطلوبة
if (
    !$data ||
    !isset($data['id']) || !is_numeric($data['id']) ||
    !isset($data['invoice_number']) ||
    !isset($data['item_price']) ||
    !isset($data['date']) ||
    !isset($data['unit']) ||
    !isset($data['quantity']) ||
    !isset($data['total_price']) ||
    !isset($data['supplier']) ||
    !isset($data['payment_method'])
) {
    echo json_encode(["status" => "error", "message" => "❌ بيانات ناقصة أو غير صالحة"]);
    exit;
}

$id             = intval($data['id']);
$invoice_number = trim($data['invoice_number']);
$item_price     = floatval($data['item_price']);
$date           = trim($data['date']);
$unit           = trim($data['unit']);
$quantity       = floatval($data['quantity']);
$total_price    = floatval($data['total_price']);
$supplier       = trim($data['supplier']);
$payment_method = trim($data['payment_method']);
$employee_name  = isset($data['employee_name']) ? trim($data['employee_name']) : null;
$notes          = isset($data['notes']) ? trim($data['notes']) : "";
$attachment     = isset($data['AttachmentPath']) ? trim($data['AttachmentPath']) : "";

// تركيب الملحوظة النهائية
$notes_final = "مصروفات - رقم الفاتورة: " . $invoice_number;
if ($notes) {
    $notes_final .= " - " . $notes;
}

// ✅ استرجاع القيم القديمة قبل التعديل
$sql_old = "SELECT date, payment_method, total_price, invoice_number FROM expensesMH WHERE id = ?";
$stmt_old = $conn->prepare($sql_old);
$stmt_old->bind_param("i", $id);
$stmt_old->execute();
$result_old = $stmt_old->get_result();

if ($result_old->num_rows === 0) {
    echo json_encode(["status" => "error", "message" => "❌ لم يتم العثور على المصروف المطلوب"]);
    exit;
}

$row_old = $result_old->fetch_assoc();
$old_date = $row_old['date'];
$old_payment_method = $row_old['payment_method'];
$old_total_price = floatval($row_old['total_price']);
$old_invoice_number = trim($row_old['invoice_number']);
$stmt_old->close();

// ✅ تحديث المصروف في جدول expensesMH
$sql = "UPDATE expensesMH 
        SET 
            invoice_number = ?, 
            item_price = ?, 
            date = ?, 
            unit = ?, 
            quantity = ?, 
            total_price = ?, 
            supplier = ?, 
            payment_method = ?, 
            notes = ?, 
            AttachmentPath = ?, 
            EmpID = (SELECT id FROM USEUSERSMH WHERE username = ? LIMIT 1)
        WHERE id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param(
    "sdssddsssssi", 
    $invoice_number, 
    $item_price, 
    $date, 
    $unit, 
    $quantity, 
    $total_price, 
    $supplier, 
    $payment_method, 
    $notes, 
    $attachment,
    $employee_name, 
    $id
);

if ($stmt->execute()) {
    $stmt->close();

    // ✅ تعديل العملية المالية في TransactionsMH باستخدام كل القيم القديمة
    $sql2 = "UPDATE TransactionsMH 
             SET 
                RefranNUM = ?, 
                AttachmentPath = ?, 
                notes = ?
             WHERE 
                method = ? AND 
                date = ? AND 
                value = ? AND 
                RefranNUM = ? AND 
                type = 'مخرج'";

    $stmt2 = $conn->prepare($sql2);
    $stmt2->bind_param(
        "ssssssd", 
        $invoice_number, 
        $attachment, 
        $notes_final, 
        $old_payment_method, 
        $old_date, 
        $old_total_price, 
        $old_invoice_number
    );

    if ($stmt2->execute()) {
        echo json_encode(["status" => "success", "message" => "✅ تم تعديل المصروف وتحديث العملية المالية بنجاح"]);
    } else {
        echo json_encode(["status" => "error", "message" => "❌ تم تعديل المصروف، لكن فشل تعديل العملية المالية", "error" => $stmt2->error]);
    }

    $stmt2->close();
} else {
    echo json_encode(["status" => "error", "message" => "❌ فشل تعديل المصروف: " . $stmt->error]);
    $stmt->close();
}

$conn->close();
?>