<?php
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'db_connect.php';

// جلب بيانات المستخدم الحالي
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? '';
if (empty($user_name)) {
    try {
        $stmt = $conn->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->execute([':user_id' => $user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($user) && isset($user['username'])) {
            $user_name = $user['username'];
            $_SESSION['user_name'] = $user_name;
        }
    } catch (PDOException $e) {
        error_log("Error fetching user name: " . $e->getMessage());
        $user_name = 'مستخدم غير محدد';
    }
}

// جلب بيانات الفاتورة المراد تعديلها
$invoice = null;
$invoice_items = [];
$success_message = '';
$error_message = '';
$return_url = $_GET['return_url'] ?? 'sales_invoices.php'; // رابط العودة

// التحقق من وجود id في POST أو GET
if (isset($_POST['id']) && is_numeric($_POST['id'])) {
    $invoice_id = $_POST['id'];
} elseif (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $invoice_id = $_GET['id'];
} else {
    echo "Invalid invoice id: " . ($_GET['id'] ?? 'not set') . "<br>";
    $error_message = "معرف الفاتورة غير صالح.";
}

if (isset($invoice_id)) {
    try {
        $stmt = $conn->prepare("SELECT si.*, c.name AS client_name 
                                FROM sales_invoices si 
                                LEFT JOIN clients c ON si.client_id = c.id 
                                WHERE si.id = :id");
        $stmt->execute([':id' => $invoice_id]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($invoice) {
            $stmt = $conn->prepare("SELECT sii.*, i.name AS item_name 
                                    FROM sales_invoice_items sii 
                                    LEFT JOIN items i ON sii.item_id = i.id 
                                    WHERE sii.invoice_id = :invoice_id");
            $stmt->execute([':invoice_id' => $invoice_id]);
            $invoice_items = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } else {
            echo "No invoice found for id: $invoice_id<br>";
            $error_message = "لم يتم العثور على الفاتورة.";
        }
    } catch (PDOException $e) {
        echo "Error fetching invoice details: " . $e->getMessage() . "<br>";
        $error_message = "فشل جلب بيانات الفاتورة: " . $e->getMessage();
    }
}

// جلب العملاء
$clients = [];
try {
    $clients = $conn->query("SELECT id, name FROM clients ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching clients: " . $e->getMessage());
    $clients = [];
}

// جلب الأصناف
$items = [];
try {
    $items = $conn->query("SELECT id, name, barcode, retail_price, wholesale_price, quantity FROM items")->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
    error_log("Error fetching items: " . $e->getMessage());
    $items = [];
}

// إنشاء خيارات القائمة المنسدلة للأصناف
$itemOptions = '';
if (!empty($items) && is_array($items)) {
    foreach ($items as $item) {
        $itemOptions .= '<option value="' . $item['id'] . '" data-barcode="' . ($item['barcode'] ?? '') . '" data-retail-price="' . ($item['retail_price'] ?? 0) . '" data-wholesale-price="' . ($item['wholesale_price'] ?? 0) . '" data-quantity="' . ($item['quantity'] ?? 0) . '">' . htmlspecialchars($item['name'] ?? '') . '</option>';
    }
} else {
    $itemOptions = '<option value="">لا توجد أصناف متاحة</option>';
}

// معالجة حفظ التعديلات
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    error_log("POST request received: " . print_r($_POST, true));
    if (!isset($_POST['save_changes'])) {
        error_log("save_changes not set in POST data. Full POST data: " . print_r($_POST, true));
        $error_message = "لم يتم إرسال طلب الحفظ بشكل صحيح.";
    } else {
        error_log("save_changes is set");

        $store_id = $_POST['store_id'] ?? $invoice['store_id'];
        $treasury_id = $_POST['treasury_id'] ?? $invoice['treasury_id'];
        $client_id = $_POST['client_id'] ?? $invoice['client_id'];
        $payment_type = $_POST['payment_type'] ?? $invoice['payment_type'];
        $discount_value = floatval($_POST['discount_value'] ?? $invoice['discount']);
        $discount_type = $_POST['discount_type'] ?? ($invoice['discount'] > 0 && $invoice['discount'] < 100 ? 'percentage' : 'fixed');
        $paid_amount = floatval($_POST['paid_amount'] ?? $invoice['paid_amount']);
        $items_data = isset($_POST['items_data']) ? json_decode($_POST['items_data'], true) : [];

        error_log("Received POST data: store_id=$store_id, treasury_id=$treasury_id, client_id=$client_id, payment_type=$payment_type, discount_value=$discount_value, paid_amount=$paid_amount, items_data=" . print_r($items_data, true));

        if (empty($items_data) || !is_array($items_data)) {
            $error_message = "لا يمكن حفظ فاتورة بدون أصناف!";
            error_log("Error: No items provided in items_data");
        } else {
            try {
                $conn->beginTransaction();

                // حساب الإجمالي الجديد
                $total = 0;
                foreach ($items_data as $item) {
                    $quantity = intval($item['quantity'] ?? 0);
                    $price = floatval($item['price'] ?? 0);
                    $total += $quantity * $price;
                    error_log("Item processed: id=" . ($item['id'] ?? 'N/A') . ", quantity=$quantity, price=$price, subtotal=" . ($quantity * $price));
                }

                if ($discount_type === 'percentage') {
                    $discount = ($total * $discount_value) / 100;
                } else {
                    $discount = $discount_value;
                }
                $final_total = $total - $discount;
                $remaining_amount = $payment_type === 'credit' ? max(0, $final_total - $paid_amount) : 0;

                error_log("Calculated totals: total=$total, discount=$discount, final_total=$final_total, remaining_amount=$remaining_amount");

                // إعادة الكميات القديمة
                $stmt = $conn->prepare("SELECT item_id, quantity FROM sales_invoice_items WHERE invoice_id = :invoice_id");
                $stmt->execute([':invoice_id' => $invoice_id]);
                $old_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
                foreach ($old_items as $old_item) {
                    $stmt = $conn->prepare("UPDATE items SET quantity = quantity + :quantity WHERE id = :item_id");
                    $stmt->execute([':quantity' => $old_item['quantity'], ':item_id' => $old_item['item_id']]);
                    error_log("Restored quantity for item_id=" . $old_item['item_id'] . ", quantity=" . $old_item['quantity']);
                }

                // حذف الأصناف القديمة
                $stmt = $conn->prepare("DELETE FROM sales_invoice_items WHERE invoice_id = :invoice_id");
                $stmt->execute([':invoice_id' => $invoice_id]);
                error_log("Deleted old items for invoice_id=$invoice_id");

                // إدراج الأصناف الجديدة
                foreach ($items_data as $item) {
                    $item_id = $item['id'] ?? 0;
                    $quantity = intval($item['quantity'] ?? 0);
                    $price = floatval($item['price'] ?? 0);

                    if ($item_id > 0 && $quantity > 0) {
                        $stmt = $conn->prepare("SELECT quantity FROM items WHERE id = :item_id");
                        $stmt->execute([':item_id' => $item_id]);
                        $available_quantity = $stmt->fetchColumn() ?: 0;
                        error_log("Checking available quantity for item_id=$item_id: available=$available_quantity, requested=$quantity");
                        if ($available_quantity < $quantity) {
                            throw new Exception("الكمية غير كافية للصنف: " . ($item['name'] ?? $item_id));
                        }

                        $stmt = $conn->prepare("INSERT INTO sales_invoice_items (invoice_id, item_id, quantity, price) VALUES (:invoice_id, :item_id, :quantity, :price)");
                        $stmt->execute([':invoice_id' => $invoice_id, ':item_id' => $item_id, ':quantity' => $quantity, ':price' => $price]);
                        error_log("Inserted item: invoice_id=$invoice_id, item_id=$item_id, quantity=$quantity, price=$price");

                        $stmt = $conn->prepare("UPDATE items SET quantity = quantity - :sold_quantity WHERE id = :item_id");
                        $stmt->execute([':sold_quantity' => $quantity, ':item_id' => $item_id]);
                        error_log("Updated item quantity: item_id=$item_id, sold_quantity=$quantity");
                    }
                }

                // تحديث بيانات الفاتورة
                $stmt = $conn->prepare("UPDATE sales_invoices 
                                        SET store_id = :store_id, treasury_id = :treasury_id, client_id = :client_id, 
                                            payment_type = :payment_type, total = :total, discount = :discount, 
                                            final_total = :final_total, paid_amount = :paid_amount, 
                                            remaining_amount = :remaining_amount, date = NOW() 
                                        WHERE id = :id");
                $stmt->execute([
                    ':store_id' => $store_id,
                    ':treasury_id' => $treasury_id,
                    ':client_id' => $client_id,
                    ':payment_type' => $payment_type,
                    ':total' => $total,
                    ':discount' => $discount,
                    ':final_total' => $final_total,
                    ':paid_amount' => $paid_amount,
                    ':remaining_amount' => $remaining_amount,
                    ':id' => $invoice_id
                ]);
                error_log("Updated invoice $invoice_id: total=$total, final_total=$final_total");

                // تحديث الخزنة
                if ($invoice['payment_type'] === 'cash' && $payment_type === 'credit') {
                    $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance - :final_total WHERE id = :treasury_id");
                    $stmt->execute([':final_total' => $invoice['final_total'], ':treasury_id' => $treasury_id]);
                } elseif ($invoice['payment_type'] === 'credit' && $payment_type === 'cash') {
                    $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance + :final_total WHERE id = :treasury_id");
                    $stmt->execute([':final_total' => $final_total, ':treasury_id' => $treasury_id]);
                } elseif ($payment_type === 'cash' && $final_total != $invoice['final_total']) {
                    $diff = $final_total - $invoice['final_total'];
                    $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance + :diff WHERE id = :treasury_id");
                    $stmt->execute([':diff' => $diff, ':treasury_id' => $treasury_id]);
                }

                // تحديث ديون العميل
                if ($payment_type === 'credit' && $remaining_amount != $invoice['remaining_amount']) {
                    $debt_diff = $remaining_amount - $invoice['remaining_amount'];
                    $stmt = $conn->prepare("UPDATE clients SET previous_debt = previous_debt + :debt_diff WHERE id = :client_id");
                    $stmt->execute([':debt_diff' => $debt_diff, ':client_id' => $client_id]);
                }

                $conn->commit();
                error_log("Invoice $invoice_id committed successfully");
                $success_message = "تم تعديل الفاتورة بنجاح!";

                if (!headers_sent()) {
                    header("Location: " . $return_url . "?success=1");
                    exit();
                } else {
                    error_log("Headers already sent, cannot redirect");
                    echo "<script>window.location.href='" . $return_url . "?success=1';</script>";
                    exit();
                }
            } catch (Exception $e) {
                $conn->rollBack();
                error_log("Error updating invoice $invoice_id: " . $e->getMessage());
                $error_message = "فشل تعديل الفاتورة: " . $e->getMessage();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - تعديل فاتورة بيع</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2ECC71, #3498DB, #E74C3C);
            overflow-x: hidden;
            animation: gradientShift 10s ease infinite;
            background-size: 400% 400%;
        }

        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .container-fluid {
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            padding: 20px;
            margin-bottom: 20px;
            animation: fadeIn 1s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        h2 {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 0 5px rgba(46, 204, 113, 0.5);
        }

        .form-label {
            color: #3498DB;
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }

        .form-label i {
            margin-left: 8px;
            color: #2ECC71;
        }

        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #2ECC71;
            padding: 6px 10px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
            box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.1);
            font-size: 0.9rem;
        }

        .form-control:focus, .form-select:focus {
            border-color: #3498DB;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.1);
            background: #fff;
        }

        .btn {
            border-radius: 10px;
            padding: 6px 15px;
            font-weight: bold;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
            font-size: 0.9rem;
        }

        .btn-save {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }

        .btn-save:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.5);
        }

        .btn-cancel {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }

        .btn-cancel:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
        }

        .btn-add {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }

        .btn-add:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .btn-delete {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }

        .btn-delete:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
        }

        .success-message {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .error-message {
            color: #E74C3C;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .table {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .table thead {
            background: #2ECC71;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        .total-box {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            color: #fff;
            padding: 15px 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
            text-align: center;
            font-weight: bold;
            font-size: 1.5rem;
            position: fixed;
            bottom: 60px;
            right: 20px;
            z-index: 1000;
        }

        .remaining-box {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            color: #fff;
            padding: 10px 20px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
            text-align: center;
            font-weight: bold;
            font-size: 1.2rem;
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <?php if ($invoice && empty($error_message)): ?>
                <h2><i class="fas fa-edit me-2"></i> تعديل فاتورة بيع #<?php echo htmlspecialchars($invoice['invoice_number'] ?? 'غير محدد'); ?></h2>
                <?php if ($success_message): ?>
                    <div class="success-message"><?php echo $success_message; ?></div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="error-message"><?php echo $error_message; ?></div>
                <?php endif; ?>

                <form method="POST" id="editInvoiceForm" action="">
                    <!-- إضافة حقل مخفي لتخزين id -->
                    <input type="hidden" name="id" value="<?php echo htmlspecialchars($invoice_id); ?>">

                    <div class="invoice-details row g-3">
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-store"></i> المخزن</label>
                            <select class="form-select" name="store_id" required>
                                <?php
                                $stores = $conn->query("SELECT id, name FROM stores")->fetchAll(PDO::FETCH_ASSOC);
                                foreach ($stores as $store): ?>
                                    <option value="<?php echo $store['id']; ?>" <?php echo $invoice['store_id'] == $store['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($store['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-vault"></i> الخزنة</label>
                            <select class="form-select" name="treasury_id" required>
                                <?php
                                $treasuries = $conn->query("SELECT id, name FROM treasuries")->fetchAll(PDO::FETCH_ASSOC);
                                foreach ($treasuries as $treasury): ?>
                                    <option value="<?php echo $treasury['id']; ?>" <?php echo $invoice['treasury_id'] == $treasury['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($treasury['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-user"></i> العميل</label>
                            <select class="form-select" name="client_id" required>
                                <?php foreach ($clients as $client): ?>
                                    <option value="<?php echo $client['id']; ?>" <?php echo $invoice['client_id'] == $client['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($client['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-money-bill"></i> نوع الدفع</label>
                            <select class="form-select" name="payment_type" id="paymentType" onchange="togglePaidAmount()" required>
                                <option value="cash" <?php echo $invoice['payment_type'] == 'cash' ? 'selected' : ''; ?>>نقدي</option>
                                <option value="credit" <?php echo $invoice['payment_type'] == 'credit' ? 'selected' : ''; ?>>آجل</option>
                            </select>
                        </div>
                        <div class="col-md-2" id="paidAmountField" style="display: <?php echo $invoice['payment_type'] == 'credit' ? 'block' : 'none'; ?>;">
                            <label class="form-label"><i class="fas fa-money-check"></i> المبلغ المدفوع</label>
                            <input type="number" step="0.01" class="form-control" name="paid_amount" id="paidAmount" value="<?php echo $invoice['paid_amount']; ?>" oninput="updateTotal()">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-minus-circle"></i> الخصم</label>
                            <input type="number" step="0.01" class="form-control" name="discount_value" id="discountValue" value="<?php echo $invoice['discount']; ?>" oninput="updateTotal()">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-percentage"></i> نوع الخصم</label>
                            <select class="form-select" name="discount_type" id="discountType" onchange="updateTotal()">
                                <option value="fixed" <?php echo $invoice['discount'] >= 100 || $invoice['discount'] == 0 ? 'selected' : ''; ?>>جنيه</option>
                                <option value="percentage" <?php echo $invoice['discount'] > 0 && $invoice['discount'] < 100 ? 'selected' : ''; ?>>%</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-add" onclick="addItemRow()"><i class="fas fa-plus"></i> إضافة صنف</button>
                        </div>
                    </div>

                    <div class="table-responsive" style="max-height: 40vh; overflow-y: auto; margin-top: 20px;">
                        <table class="table table-striped" id="itemsTable">
                            <thead>
                                <tr>
                                    <th>الإجراء</th>
                                    <th>اسم الصنف</th>
                                    <th>الكمية</th>
                                    <th>السعر</th>
                                    <th>الإجمالي</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($invoice_items)): ?>
                                    <tr>
                                        <td colspan="5" style="text-align: center; color: #E74C3C;">لا يوجد أصناف لهذه الفاتورة.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($invoice_items as $index => $item): ?>
                                        <tr>
                                            <td>
                                                <button class="btn btn-delete" onclick="deleteItem(<?php echo $index; ?>)"><i class="fas fa-trash"></i> حذف</button>
                                            </td>
                                            <td>
                                                <select class="form-select item-select" data-index="<?php echo $index; ?>" onchange="updateItem(<?php echo $index; ?>)">
                                                    <option value="">اختر الصنف</option>
                                                    <?php echo $itemOptions; ?>
                                                </select>
                                            </td>
                                            <td><input type="number" class="form-control quantity" data-index="<?php echo $index; ?>" value="<?php echo htmlspecialchars($item['quantity'] ?? 1); ?>" min="1" oninput="updateQuantity(<?php echo $index; ?>, this.value)"></td>
                                            <td><input type="number" class="form-control price" data-index="<?php echo $index; ?>" value="<?php echo htmlspecialchars($item['price'] ?? 0); ?>" step="0.01" oninput="updateTotal()"></td>
                                            <td class="total-cell" data-index="<?php echo $index; ?>"><?php echo number_format(($item['quantity'] ?? 0) * ($item['price'] ?? 0), 2); ?></td>
                                        </tr>
                                        <script>
                                            document.querySelector('.item-select[data-index="<?php echo $index; ?>"]').value = '<?php echo htmlspecialchars($item['item_id'] ?? ''); ?>';
                                        </script>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- حقل مخفي لتخزين بيانات الأصناف -->
                    <input type="hidden" name="items_data" id="itemsData">

                    <!-- أزرار الحفظ والإلغاء -->
                    <div style="display: flex; justify-content: center; margin-top: 20px;">
                        <button type="button" class="btn btn-cancel" onclick="window.location.href='<?php echo $return_url; ?>'"><i class="fas fa-times"></i> إلغاء</button>
                        <button type="submit" name="save_changes" class="btn btn-save"><i class="fas fa-save"></i> حفظ التعديلات</button>
                    </div>

                    <div class="total-box">
                        الإجمالي: <span id="totalAmount"><?php echo number_format($invoice['final_total'], 2); ?></span> ج.م
                    </div>
                    <div class="remaining-box" id="remainingBox" style="display: <?php echo $invoice['payment_type'] == 'credit' ? 'block' : 'none'; ?>;">
                        المتبقي: <span id="remainingAmount"><?php echo number_format($invoice['remaining_amount'], 2); ?></span> ج.م
                    </div>
                </form>
            <?php else: ?>
                <h2><i class="fas fa-edit me-2"></i> تعديل فاتورة بيع</h2>
                <p style="text-align: center; color: #E74C3C;">لم يتم العثور على الفاتورة.</p>
                <a href="<?php echo htmlspecialchars($return_url); ?>" class="btn btn-cancel"><i class="fas fa-arrow-right"></i> العودة</a>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // تحديد مصفوفة items بشكل آمن
    let items = <?php
        $items_array = array_map(function($item) {
            return [
                'id' => $item['item_id'] ?? '',
                'name' => $item['item_name'] ?? '',
                'quantity' => $item['quantity'] ?? 1,
                'price' => $item['price'] ?? 0,
                'total' => ($item['quantity'] ?? 0) * ($item['price'] ?? 0)
            ];
        }, $invoice_items ?? []);
        echo json_encode($items_array, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
    ?> || [];

    function updateItem(index) {
        const select = document.querySelector(`.item-select[data-index="${index}"]`);
        if (!select) return;
        const itemId = select.value;
        const option = select.options[select.selectedIndex];
        if (!option) return;
        const price = parseFloat(option.getAttribute('data-retail-price')) || 0;
        items[index] = {
            id: itemId,
            name: option.text,
            quantity: items[index]?.quantity || 1,
            price: price,
            total: (items[index]?.quantity || 1) * price
        };
        updateTotal();
        saveItemsToForm();
    }

    function updateQuantity(index, quantity) {
        if (isNaN(quantity) || quantity < 1) quantity = 1;
        const select = document.querySelector(`.item-select[data-index="${index}"]`);
        if (!select) return;
        const availableQuantity = parseInt(select.options[select.selectedIndex].getAttribute('data-quantity')) || 0;
        quantity = parseInt(quantity);
        if (quantity > availableQuantity) {
            alert('الكمية المطلوبة غير متاحة لهذا الصنف. الكمية المتاحة: ' + availableQuantity);
            quantity = availableQuantity;
            const quantityInput = document.querySelector(`.quantity[data-index="${index}"]`);
            if (quantityInput) quantityInput.value = quantity;
        }
        items[index].quantity = quantity;
        items[index].total = items[index].quantity * items[index].price;
        updateTotal(); // تحديث الإجمالي فورًا
        saveItemsToForm();
    }

    function deleteItem(index) {
        if (confirm('هل أنت متأكد من حذف هذا الصنف؟')) {
            items.splice(index, 1);
            updateTable();
            saveItemsToForm();
        }
    }

    function addItemRow() {
        const index = items.length;
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><button class="btn btn-delete" onclick="deleteItem(${index})"><i class="fas fa-trash"></i> حذف</button></td>
            <td>
                <select class="form-select item-select" data-index="${index}" onchange="updateItem(${index})">
                    <option value="">اختر الصنف</option>
                    <?php echo $itemOptions; ?>
                </select>
            </td>
            <td><input type="number" class="form-control quantity" data-index="${index}" value="1" min="1" oninput="updateQuantity(${index}, this.value)"></td>
            <td><input type="number" class="form-control price" data-index="${index}" value="0" step="0.01" oninput="updateTotal()"></td>
            <td class="total-cell" data-index="${index}">0.00</td>
        `;
        const tbody = document.querySelector('#itemsTable tbody');
        if (tbody) tbody.appendChild(row);
        items.push({ id: '', name: '', quantity: 1, price: 0, total: 0 });
        saveItemsToForm();
    }

    function updateTable() {
        const tbody = document.querySelector('#itemsTable tbody');
        if (!tbody) return;
        tbody.innerHTML = '';
        if (items.length === 0) {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="5" style="text-align: center; color: #E74C3C;">لا يوجد أصناف لهذه الفاتورة.</td>';
            tbody.appendChild(row);
            return;
        }
        items.forEach((item, index) => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><button class="btn btn-delete" onclick="deleteItem(${index})"><i class="fas fa-trash"></i> حذف</button></td>
                <td>
                    <select class="form-select item-select" data-index="${index}" onchange="updateItem(${index})">
                        <option value="">اختر الصنف</option>
                        <?php echo $itemOptions; ?>
                    </select>
                </td>
                <td><input type="number" class="form-control quantity" data-index="${index}" value="${item.quantity || 1}" min="1" oninput="updateQuantity(${index}, this.value)"></td>
                <td><input type="number" class="form-control price" data-index="${index}" value="${item.price || 0}" step="0.01" oninput="updateTotal()"></td>
                <td class="total-cell" data-index="${index}">${Number(item.total || 0).toFixed(2)}</td>
            `;
            tbody.appendChild(row);
            const select = document.querySelector(`.item-select[data-index="${index}"]`);
            if (select) select.value = item.id || '';
        });
    }

    function updateTotal() {
        let total = 0;
        items.forEach((item, index) => {
            const quantityInput = document.querySelector(`.quantity[data-index="${index}"]`);
            const priceInput = document.querySelector(`.price[data-index="${index}"]`);
            const quantity = quantityInput ? parseInt(quantityInput.value) || 1 : (item.quantity || 1);
            const price = priceInput ? parseFloat(priceInput.value) || 0 : (item.price || 0);
            items[index].quantity = quantity;
            items[index].price = price;
            items[index].total = quantity * price;
            const totalCell = document.querySelector(`.total-cell[data-index="${index}"]`);
            if (totalCell) totalCell.innerText = Number(items[index].total).toFixed(2);
            total += items[index].total;
        });

        const discountValue = parseFloat(document.getElementById('discountValue')?.value) || 0;
        const discountType = document.getElementById('discountType')?.value || 'fixed';
        let finalTotal = total;
        if (discountType === 'percentage') {
            finalTotal -= (total * discountValue) / 100;
        } else {
            finalTotal -= discountValue;
        }
        finalTotal = Math.max(0, finalTotal);

        const paymentType = document.getElementById('paymentType')?.value || 'cash';
        let paidAmount = parseFloat(document.getElementById('paidAmount')?.value) || 0;
        if (paymentType === 'cash') {
            paidAmount = finalTotal;
        }
        const remainingAmount = paymentType === 'credit' ? Math.max(0, finalTotal - paidAmount) : 0;

        const totalAmount = document.getElementById('totalAmount');
        if (totalAmount) totalAmount.innerText = finalTotal.toFixed(2);
        const remainingBox = document.getElementById('remainingBox');
        const remainingAmountSpan = document.getElementById('remainingAmount');
        if (remainingBox && remainingAmountSpan) {
            if (paymentType === 'credit') {
                remainingBox.style.display = 'block';
                remainingAmountSpan.innerText = remainingAmount.toFixed(2);
            } else {
                remainingBox.style.display = 'none';
            }
        }

        saveItemsToForm();
    }

    function togglePaidAmount() {
        const paymentType = document.getElementById('paymentType')?.value || 'cash';
        const paidAmountField = document.getElementById('paidAmountField');
        if (paidAmountField) {
            if (paymentType === 'credit') {
                paidAmountField.style.display = 'block';
            } else {
                paidAmountField.style.display = 'none';
                const remainingBox = document.getElementById('remainingBox');
                if (remainingBox) remainingBox.style.display = 'none';
            }
        }
        updateTotal();
    }

    function saveItemsToForm() {
        const itemsData = document.getElementById('itemsData');
        if (itemsData) {
            itemsData.value = JSON.stringify(items);
            console.log("Items saved to form:", items);
        } else {
            console.log("itemsData field not found, form may not be rendered.");
        }
    }

    // تحديث الجدول عند التحميل
    document.addEventListener('DOMContentLoaded', () => {
        updateTable();
        updateTotal();
        const form = document.getElementById('editInvoiceForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                saveItemsToForm();
                const formData = new FormData(this);
                console.log("Form data before submission:", Object.fromEntries(formData.entries()));
            });

            // مستمع للضغط على Enter لتأكيد الحفظ أو الحذف بناءً على العنصر النشط
            form.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' || e.keyCode === 13) {
                    const activeElement = document.activeElement;
                    if (activeElement.classList.contains('btn-delete')) {
                        // إذا كان العنصر النشط زر الحذف
                        e.preventDefault();
                        const index = activeElement.closest('tr').querySelector('.item-select').getAttribute('data-index');
                        deleteItem(index);
                    } else if (activeElement.classList.contains('quantity') || activeElement.classList.contains('price')) {
                        // إذا كان العنصر النشط حقل الكمية أو السعر
                        e.preventDefault();
                        if (confirm('هل أنت متأكد من الحفظ؟')) {
                            saveItemsToForm();
                            // محاكاة النقر على زر "حفظ التعديلات" بدلاً من this.submit()
                            const saveButton = document.querySelector('button[name="save_changes"]');
                            if (saveButton) {
                                saveButton.click();
                            } else {
                                console.error("Save button not found!");
                            }
                        }
                    }
                }
            });
        }
    });
</script>
</body>
</html>