<?php
$page_title = 'إنشاء فاتورة جديدة';
require_once 'includes/header.php';

$products = getProducts();
$customers = getCustomers();

// إنشاء رقم فاتورة جديد
$new_invoice_number = generateInvoiceNumber();
?>

<!-- Create Invoice Section -->
<div class="content-section" id="create-invoice">
    <div class="section-header">
        <h3>إنشاء فاتورة جديدة</h3>
    </div>

    <form id="invoiceForm" action="save_invoice.php" method="POST">
        <div class="invoice-form">
            <div>
                <div class="form-group">
                    <label for="customer_name">اسم العميل</label>
                    <input type="text" id="customer_name" name="customer_name" class="form-control">
                </div>
                <div class="form-group">
                    <label for="customer_phone">رقم الهاتف</label>
                    <input type="tel" id="customer_phone" name="customer_phone" class="form-control">
                </div>
                <div class="form-group">
                    <label for="invoice_date">تاريخ الفاتورة</label>
                    <input type="date" id="invoice_date" name="invoice_date" class="form-control" required
                        value="<?= date('Y-m-d') ?>">
                </div>
                <div class="form-group">
                    <label for="invoice_number">رقم الفاتورة</label>
                    <input type="text" id="invoice_number" name="invoice_number" class="form-control" required
                        value="<?= $new_invoice_number ?>" readonly>
                </div>
            </div>
            <div>
                <div class="form-group">
                    <label for="item_name">اسم المنتج<label>
                    <input type="text" id="item_name" class="form-control">
                </div>

                <div class="form-group">
                    <label for="item_price">السعر</label>
                    <input type="number" id="item_price" class="form-control" min="0" step="0.01">
                </div>
                <div class="form-group">
                    <label for="item_quantity">الكمية</label>
                    <input type="number" id="item_quantity" class="form-control" min="1" value="1">
                </div>
                <div class="form-group">
                    <label for="warranty_period">مدة الضمان</label>
                    <select id="warranty_period" class="form-control">
                        <option value="0">بدون ضمان</option>
                        <option value="15">15 يوم</option>
                        <option value="30">1 شهر</option>
                        <option value="60">2 شهر</option>
                        <option value="90">3 شهور</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="warranty_end">تاريخ نهاية الضمان (اختياري)</label>
                    <input type="date" id="warranty_end" class="form-control">
                </div>
            </div>
        </div>
        <button type="button" class="btn btn-primary" id="addItem">إضافة صنف</button>


        <div class="items-table-container">
            <table class="items-table">
                <thead>
                    <tr>
                        <th>الصنف</th>
                        <th>الكمية</th>
                        <th>السعر</th>
                        <th>مدة الضمان</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody id="itemsTableBody">
                    <!-- Items will be added here dynamically -->
                </tbody>
            </table>
        </div>

        <div class="form-group" style="margin-top: 20px;">
            <label for="notes">ملاحظات</label>
            <textarea id="notes" name="notes" class="form-control" rows="3"></textarea>
        </div>

        <!-- Hidden field to store items data -->
        <input type="hidden" id="items_data" name="items_data">

        <div style="margin-top: 20px; text-align: left;">
            <button type="submit" class="btn btn-success" id="saveInvoice">حفظ الفاتورة</button>
            <button type="reset" class="btn btn-danger">إلغاء</button>
        </div>
    </form>
</div>

<script src="assets/js/script.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const invoiceNumberInput = document.getElementById('invoice_number');
        invoiceNumberInput.value = '<?= $new_invoice_number ?>';

        const items = [];

        document.getElementById('addItem').addEventListener('click', function () {
            let itemName = document.getElementById('item_name').value.trim();
            const itemPrice = parseFloat(document.getElementById('item_price').value);
            const itemQuantity = parseInt(document.getElementById('item_quantity').value);
            let warrantyPeriod = document.getElementById('warranty_period').value;
            let warrantyEnd = document.getElementById('warranty_end').value;

            // حساب تاريخ نهاية الضمان إذا لم يتم إدخاله يدوياً
            if (!warrantyEnd && warrantyPeriod > 0) {
                let today = new Date();
                today.setDate(today.getDate() + parseInt(warrantyPeriod));
                warrantyEnd = today.toISOString().split('T')[0];
            }

            const item = {
                product_id: null,
                name: itemName,
                price: itemPrice,
                quantity: itemQuantity,
                total: itemPrice * itemQuantity,
                warranty_period: warrantyPeriod,
                warranty_end: warrantyEnd
            };

            items.push(item);
            updateItemsTable();

            document.getElementById('item_name').value = '';
            document.getElementById('item_price').value = '';
            document.getElementById('item_quantity').value = '1';
        });

        function updateItemsTable() {
            const tableBody = document.getElementById('itemsTableBody');
            tableBody.innerHTML = '';

            items.forEach((item, index) => {
                const row = document.createElement('tr');

                row.innerHTML = `
                    <td>${item.name}</td>
                    <td>${item.quantity}</td>
                    <td>${item.price.toFixed(2)} ج.م</td>
                    <td>${item.warranty_end ? item.warranty_end : 'بدون ضمان'}</td>
                    <td>
                        <button type="button" class="btn btn-danger" onclick="removeItem(${index})">
                            <i class="fas fa-trash"></i> حذف
                        </button>
                    </td>
                `;

                tableBody.appendChild(row);
            });

            document.getElementById('items_data').value = JSON.stringify(items);
        }

        window.removeItem = function (index) {
            items.splice(index, 1);
            updateItemsTable();
        };

        document.getElementById('previewInvoice').addEventListener('click', function () {
            const customerName = document.getElementById('customer_name').value.trim();
            const customerPhone = document.getElementById('customer_phone').value.trim();
            const invoiceDate = document.getElementById('invoice_date').value;
            const invoiceNumber = document.getElementById('invoice_number').value;

            if (!customerName || !invoiceDate || items.length === 0) {
                alert('الرجاء إدخال جميع البيانات المطلوبة');
                return;
            }

            const dateObj = new Date(invoiceDate);
            const formattedDate = dateObj.toLocaleDateString('ar-SA');

            let itemsHtml = '';
            let totalAmount = 0;

            items.forEach(item => {
                itemsHtml += `
                    <tr>
                        <td>${item.total.toFixed(2)} ج.م</td>
                        <td>${item.price.toFixed(2)} ج.م</td>
                        <td>${item.quantity}</td>
                        <td>${item.name}</td>
                    </tr>
                `;
                totalAmount += item.total;
            });


        });

        // إضافة مستمع للضغط على Enter في حقول الصنف
        ['item_name', 'item_price', 'item_quantity'].forEach(function(id) {
            document.getElementById(id).addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    document.getElementById('addItem').click();
                }
            });
        });

    });
</script>


<?php
require_once 'includes/footer.php';
