<?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 = 'مستخدم غير محدد';
    }
}

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

// جلب الموردين
$suppliers = [];
try {
    $suppliers = $conn->query("SELECT id, name, previous_debt FROM suppliers ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
    error_log("Error fetching suppliers: " . $e->getMessage());
    $suppliers = [];
}

// جلب الخزن
$treasuries = [];
try {
    $treasuries = $conn->query("SELECT id, name FROM treasuries")->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
    error_log("Error fetching treasuries: " . $e->getMessage());
    $treasuries = [];
}

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

// إنشاء رقم فاتورة تلقائي
$latestInvoice = $conn->query("SELECT MAX(invoice_number) as max_number FROM purchase_invoices")->fetchColumn() ?: 0;
$invoice_number = $latestInvoice ? (int)$latestInvoice + 1 : 1000;

$success_message = '';
$error_message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    error_log("POST request received: " . print_r($_POST, true));
    if (!isset($_POST['save_purchase'])) {
        error_log("save_purchase not set in POST data. Full POST data: " . print_r($_POST, true));
        $error_message = "لم يتم إرسال طلب الحفظ بشكل صحيح.";
    } else {
        $supplier_id = $_POST['supplier_id'] ?? null;
        $treasury_id = $_POST['treasury_id'] ?? null;
        $payment_type = $_POST['payment_type'] ?? 'cash';
        $items_data = isset($_POST['items_data']) ? json_decode($_POST['items_data'], true) : [];
        $paid_amount = floatval($_POST['paid_amount'] ?? 0);

        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;
                }

                $remaining_amount = $payment_type === 'credit' ? $total - $paid_amount : 0;

                // إدراج الفاتورة
                $stmt = $conn->prepare("INSERT INTO purchase_invoices (invoice_number, date, supplier_id, treasury_id, payment_type, total, paid_amount, remaining_amount) VALUES (:invoice_number, NOW(), :supplier_id, :treasury_id, :payment_type, :total, :paid_amount, :remaining_amount)");
                $stmt->execute([
                    ':invoice_number' => $invoice_number,
                    ':supplier_id' => $supplier_id,
                    ':treasury_id' => $treasury_id,
                    ':payment_type' => $payment_type,
                    ':total' => $total,
                    ':paid_amount' => $paid_amount,
                    ':remaining_amount' => $remaining_amount
                ]);
                $invoice_id = $conn->lastInsertId();
                error_log("Inserted purchase invoice: id=$invoice_id, invoice_number=$invoice_number");

                // إدراج الأصناف
                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("INSERT INTO purchase_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 purchase item: invoice_id=$invoice_id, item_id=$item_id, quantity=$quantity, price=$price");

                        // تحديث جدول الأصناف
                        $stmt = $conn->prepare("UPDATE items SET quantity = quantity + :quantity, retail_price = :price WHERE id = :item_id");
                        $stmt->execute([':quantity' => $quantity, ':price' => $price, ':item_id' => $item_id]);
                        error_log("Updated item: item_id=$item_id, new_quantity=" . ($quantity + $item['quantity'] ?? 0) . ", new_retail_price=$price");
                    }
                }

                // تحديث الدين السابق للمورد إذا كان آجل
                if ($payment_type === 'credit' && $remaining_amount > 0) {
                    $stmt = $conn->prepare("UPDATE suppliers SET previous_debt = previous_debt + :remaining_amount WHERE id = :supplier_id");
                    $stmt->execute([':remaining_amount' => $remaining_amount, ':supplier_id' => $supplier_id]);
                    error_log("Updated supplier debt: supplier_id=$supplier_id, new_debt=" . ($remaining_amount + ($suppliers[array_search($supplier_id, array_column($suppliers, 'id'))]['previous_debt'] ?? 0)));
                }

                // تحديث رصيد الخزنة إذا كان نقدي
                if ($payment_type === 'cash') {
                    // جلب الرصيد الحالي للخزنة قبل التحديث
                    $stmt = $conn->prepare("SELECT current_balance FROM treasuries WHERE id = :treasury_id");
                    $stmt->execute([':treasury_id' => $treasury_id]);
                    $current_balance = $stmt->fetchColumn() ?: 0;
                    $new_balance = $current_balance - $total;

                    $stmt = $conn->prepare("UPDATE treasuries SET current_balance = :new_balance WHERE id = :treasury_id");
                    $stmt->execute([':new_balance' => $new_balance, ':treasury_id' => $treasury_id]);
                    error_log("Updated treasury balance: treasury_id=$treasury_id, old_balance=$current_balance, new_balance=$new_balance");

                    // إضافة سجل في treasury_transactions مع تحديد نوع الفاتورة
                    $stmt = $conn->prepare("INSERT INTO treasury_transactions (treasury_id, transaction_type, amount, date, description, invoice_id, invoice_type) VALUES (:treasury_id, 'withdrawal', :amount, NOW(), :description, :invoice_id, 'purchase')");
                    $stmt->execute([
                        ':treasury_id' => $treasury_id,
                        ':amount' => $total,
                        ':description' => "دفع فاتورة شراء رقم $invoice_number",
                        ':invoice_id' => $invoice_id
                    ]);
                    error_log("Added treasury transaction: treasury_id=$treasury_id, amount=$total, invoice_id=$invoice_id, invoice_type=purchase");
                }

                $conn->commit();
                error_log("Purchase invoice $invoice_id committed successfully");
                $success_message = "تم إنشاء فاتورة الشراء بنجاح!";

                header("Location: purchase_invoices.php?success=1");
                exit();
            } catch (Exception $e) {
                $conn->rollBack();
                error_log("Error creating purchase invoice: " . $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);
        }

        .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">
            <h2><i class="fas fa-plus me-2"></i> إنشاء فاتورة شراء</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="purchaseInvoiceForm" action="">
                <!-- كونتنير بيانات الصنف -->
                <div class="invoice-details row g-3">
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-box"></i> اختيار الصنف</label>
                        <select class="form-select item-select" id="itemSelect" onchange="updateItemDetails()">
                            <option value="">اختر الصنف أو أدخل الباركود</option>
                            <?php echo $itemOptions; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-barcode"></i> الباركود</label>
                        <input type="text" class="form-control" id="barcodeInput" oninput="searchByBarcode()">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-warehouse"></i> الكمية المتاحة</label>
                        <input type="number" class="form-control" id="availableQuantity" readonly>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-money-bill"></i> السعر الجديد</label>
                        <input type="number" step="0.01" class="form-control" id="newPrice" oninput="updateTotal()">
                    </div>
                    <div class="col-md-1">
                        <label class="form-label"><i class="fas fa-sort-numeric-up"></i> الكمية</label>
                        <input type="number" class="form-control" id="quantity" value="1" min="1" oninput="updateTotal()">
                    </div>
                    <div class="col-md-1" style="padding-top: 30px;">
                        <button type="button" class="btn btn-add" onclick="addItemRow()"><i class="fas fa-plus"></i> إضافة</button>
                    </div>
                </div>

                <!-- كونتنير بيانات الفاتورة -->
                <div class="invoice-details row g-3" style="margin-top: 20px;">
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-hashtag"></i> رقم الفاتورة</label>
                        <input type="text" class="form-control" name="invoice_number" value="<?php echo $invoice_number; ?>" readonly>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-calendar"></i> التاريخ</label>
                        <input type="text" class="form-control" value="<?php echo date('Y-m-d H:i:s'); ?>" readonly>
                    </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()">
                            <option value="cash">نقدي</option>
                            <option value="credit">آجل</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-user"></i> المورد</label>
                        <select class="form-select" name="supplier_id" id="supplierSelect" onchange="updateSupplierDetails()">
                            <option value="">اختر المورد</option>
                            <?php foreach ($suppliers as $supplier): ?>
                                <option value="<?php echo $supplier['id']; ?>" data-previous-debt="<?php echo $supplier['previous_debt'] ?? 0; ?>">
                                    <?php echo htmlspecialchars($supplier['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2" id="paidAmountField" style="display: 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="0" oninput="updateTotal()">
                    </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 foreach ($treasuries as $treasury): ?>
                                <option value="<?php echo $treasury['id']; ?>">
                                    <?php echo htmlspecialchars($treasury['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-money-bill-wave"></i> الدين السابق</label>
                        <input type="text" class="form-control" id="previousDebt" readonly>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-money-bill-wave"></i> الدين الجديد</label>
                        <input type="text" class="form-control" id="newDebt" readonly>
                    </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>
                                <th>الإجمالي</th>
                            </tr>
                        </thead>
                        <tbody></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='purchase_invoices.php'"><i class="fas fa-times"></i> إلغاء</button>
                    <button type="submit" name="save_purchase" class="btn btn-save"><i class="fas fa-save"></i> حفظ الفاتورة</button>
                </div>

                <div class="total-box">
                    الإجمالي: <span id="totalAmount">0.00</span> ج.م | عدد الأصناف: <span id="itemCount">0</span>
                </div>
                <div class="remaining-box" id="remainingBox" style="display: none;">
                    المتبقي: <span id="remainingAmount">0.00</span> ج.م
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let items = [];

        function updateItemDetails() {
            const select = document.getElementById('itemSelect');
            const option = select.options[select.selectedIndex];
            if (option.value) {
                document.getElementById('availableQuantity').value = option.getAttribute('data-quantity') || 0;
                document.getElementById('newPrice').value = option.getAttribute('data-retail-price') || 0;
                document.getElementById('quantity').value = 1;
                updateTotal();
            }
        }

        function searchByBarcode() {
            const barcode = document.getElementById('barcodeInput').value;
            if (barcode) {
                const item = <?php echo json_encode($items); ?>.find(i => i.barcode === barcode);
                if (item) {
                    document.getElementById('itemSelect').value = item.id;
                    document.getElementById('availableQuantity').value = item.quantity || 0;
                    document.getElementById('newPrice').value = item.retail_price || 0;
                    document.getElementById('quantity').value = 1;
                    updateTotal();
                }
            }
        }

        function updateSupplierDetails() {
            const select = document.getElementById('supplierSelect');
            const option = select.options[select.selectedIndex];
            const previousDebt = parseFloat(option.getAttribute('data-previous-debt') || 0);
            document.getElementById('previousDebt').value = previousDebt.toFixed(2);
            updateTotal(); // لتحديث الدين الجديد
        }

        function addItemRow() {
            const select = document.getElementById('itemSelect');
            const quantityInput = document.getElementById('quantity');
            const newPriceInput = document.getElementById('newPrice');
            const availableQuantity = document.getElementById('availableQuantity');

            if (!select.value) {
                alert('يرجى اختيار صنف أولاً!');
                return;
            }

            const option = select.options[select.selectedIndex];
            const item = {
                id: select.value,
                name: option.text,
                available_quantity: parseInt(availableQuantity.value) || 0,
                quantity: parseInt(quantityInput.value) || 1,
                price: parseFloat(newPriceInput.value) || 0,
                total: (parseInt(quantityInput.value) || 1) * (parseFloat(newPriceInput.value) || 0)
            };

            items.push(item);
            updateTable(); // تحديث الجدول فورًا
            updateTotal(); // تحديث الإجمالي

            // إعادة تعيين الحقول
            select.value = '';
            availableQuantity.value = '';
            quantityInput.value = 1;
            newPriceInput.value = 0;
        }

        function updateQuantity(index, quantity) {
            if (isNaN(quantity) || quantity < 1) quantity = 1;
            items[index].quantity = parseInt(quantity);
            items[index].total = items[index].quantity * items[index].price;
            document.querySelector(`.total-cell[data-index="${index}"]`).innerText = items[index].total.toFixed(2);
            updateTotal();
        }

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

        function updateTable() {
            const tbody = document.querySelector('#itemsTable tbody');
            tbody.innerHTML = '';
            if (items.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="6" 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>${item.name || 'غير محدد'}</td>
                    <td>${item.available_quantity || 0}</td>
                    <td><input type="number" class="form-control quantity" data-index="${index}" value="${item.quantity}" min="1" oninput="updateQuantity(${index}, this.value)"></td>
                    <td><input type="number" class="form-control price" data-index="${index}" value="${item.price.toFixed(2)}" step="0.01" oninput="updateTotal()"></td>
                    <td class="total-cell" data-index="${index}">${item.total.toFixed(2)}</td>
                `;
                tbody.appendChild(row);
            });
            updateTotal();
        }

        function updateTotal() {
            let total = 0;
            let itemCount = 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;
                const price = priceInput ? parseFloat(priceInput.value) || 0 : item.price;
                items[index].quantity = quantity;
                items[index].price = price;
                items[index].total = quantity * price;
                document.querySelector(`.total-cell[data-index="${index}"]`).innerText = items[index].total.toFixed(2);
                total += items[index].total;
                itemCount++;
            });

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

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

            // تحديث الدين الجديد
            const supplierSelect = document.getElementById('supplierSelect');
            const option = supplierSelect.options[supplierSelect.selectedIndex];
            const previousDebt = parseFloat(option.getAttribute('data-previous-debt') || 0);
            document.getElementById('newDebt').value = (previousDebt + remainingAmount).toFixed(2);

            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);
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            updateTable();
            updateTotal();
            const form = document.getElementById('purchaseInvoiceForm');
            if (form) {
                form.addEventListener('submit', function(e) {
                    saveItemsToForm();
                    const formData = new FormData(this);
                    console.log("Form data before submission:", Object.fromEntries(formData.entries()));
                });
            }
        });
    </script>
</body>
</html>