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

$products = getProducts();
$customers = getCustomers();
$new_invoice_number = generateInvoiceNumber();
?>

<style>
    body {
        font-family: 'Almarai', sans-serif;
        background-color: #f8f9fa;
        color: #333;
    }

    .content-section {
        background: #fff;
        padding: 25px;
        border-radius: 15px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        animation: fadeIn 0.6s ease-in-out;
    }

    .section-header h3 {
        margin-bottom: 15px;
        font-weight: 700;
        color: #0d6efd;
    }

    .invoice-form {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 20px;
        margin-bottom: 20px;
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-group label {
        font-weight: 600;
        margin-bottom: 6px;
        display: block;
    }

    .form-control, select, textarea {
        width: 100%;
        padding: 10px 12px;
        border-radius: 10px;
        border: 1px solid #ccc;
        transition: all 0.2s;
    }

    .form-control:focus, select:focus, textarea:focus {
        border-color: #0d6efd;
        box-shadow: 0 0 0 0.2rem rgba(13,110,253,.15);
        outline: none;
    }

    .btn {
        padding: 10px 18px;
        border-radius: 10px;
        border: none;
        font-weight: 600;
        transition: all 0.3s;
        cursor: pointer;
    }

    .btn-primary { background: #0d6efd; color: #fff; }
    .btn-success { background: #198754; color: #fff; }
    .btn-danger { background: #dc3545; color: #fff; }

    .btn:hover { opacity: 0.9; transform: translateY(-1px); }

    .items-table-container {
        margin-top: 20px;
        overflow-x: auto;
    }

    .items-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
        border-radius: 10px;
        overflow: hidden;
    }

    .items-table th, .items-table td {
        padding: 12px 15px;
        border-bottom: 1px solid #eee;
        text-align: center;
    }

    .items-table thead {
        background: #0d6efd;
        color: #fff;
    }

    .items-table tbody tr:nth-child(even) {
        background: #f9fbfd;
    }

    .items-table tbody tr:hover {
        background: #eef4ff;
        transition: 0.2s;
    }

    #totalAmount {
        font-weight: bold;
        font-size: 1.1em;
        color: #198754;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px);}
        to { opacity: 1; transform: translateY(0);}
    }
</style>

<div class="content-section" id="create-invoice">
    <div class="section-header">
        <h3><i class="fas fa-file-invoice"></i> إنشاء فاتورة جديدة</h3>
    </div>

    <form id="invoiceForm" action="save_invoice.php" method="POST" onsubmit="return validateInvoiceForm()">
        <input type="hidden" name="invoice_number" value="<?= $new_invoice_number ?>">

        <div class="invoice-form">
            <!-- بيانات العميل -->
            <div>
                <div class="form-group">
                    <label for="customer_name">اسم العميل <span class="required">*</span></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">تاريخ الفاتورة <span class="required">*</span></label>
                    <input type="date" id="invoice_date" name="invoice_date" class="form-control" value="<?= date('Y-m-d') ?>">
                </div>
                <div class="form-group">
                    <label>رقم الفاتورة</label>
                    <input type="text" class="form-control" value="<?= $new_invoice_number ?>" readonly>
                </div>
            </div>

            <!-- بيانات المنتج -->
            <div>
                <div class="form-group">
                    <label for="item_name">اسم المنتج <span class="required">*</span></label>
                    <input type="text" id="item_name" class="form-control">
                </div>
                <div class="form-group">
                    <label for="item_price">السعر <span class="required">*</span></label>
                    <input type="number" id="item_price" class="form-control" min="0" step="0.01">
                </div>
                <div class="form-group">
                    <label for="item_quantity">الكمية <span class="required">*</span></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"><i class="fas fa-plus"></i> إضافة صنف</button>

        <!-- جدول الأصناف -->
        <div class="items-table-container">
            <table class="items-table">
                <thead>
                    <tr>
                        <th>الصنف</th>
                        <th>الكمية</th>
                        <th>السعر</th>
                        <th>الإجمالي</th>
                        <th>مدة الضمان</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody id="itemsTableBody"></tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" style="text-align: left;"><strong>المجموع الكلي:</strong></td>
                        <td id="totalAmount">0.00 ج.م</td>
                        <td colspan="2"></td>
                    </tr>
                </tfoot>
            </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"><i class="fas fa-save"></i> حفظ الفاتورة</button>
            <button type="reset" class="btn btn-danger" onclick="clearForm()"><i class="fas fa-times"></i> إلغاء</button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let invoiceItems = [];

    document.getElementById('addItem').addEventListener('click', function() {
        addItemToInvoice();
    });

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

        if (!itemName || isNaN(itemPrice) || isNaN(itemQuantity)) {
            alert('الرجاء إدخال جميع بيانات الصنف المطلوبة');
            return;
        }

        const total = itemPrice * itemQuantity;

        const newItem = {
            name: itemName,
            price: itemPrice,
            quantity: itemQuantity,
            warranty_period: warrantyPeriod,
            warranty_end: warrantyEnd,
            total: total
        };

        invoiceItems.push(newItem);

        updateItemsTable();
        updateItemsDataField();
        resetItemFields();
    }

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

        let grandTotal = 0;

        invoiceItems.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.total.toFixed(2)} ج.م</td>
                <td>${item.warranty_period > 0 ? item.warranty_period + ' يوم' : 'بدون ضمان'}</td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(${index})">
                        <i class="fas fa-trash"></i> حذف
                    </button>
                </td>
            `;
            tableBody.appendChild(row);

            grandTotal += item.total;
        });

        document.getElementById('totalAmount').textContent = grandTotal.toFixed(2) + ' ج.م';
    }

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

    function updateItemsDataField() {
        document.getElementById('items_data').value = JSON.stringify(invoiceItems);
    }

    function resetItemFields() {
        document.getElementById('item_name').value = '';
        document.getElementById('item_price').value = '';
        document.getElementById('item_quantity').value = '1';
        document.getElementById('warranty_period').value = '0';
        document.getElementById('warranty_end').value = '';
    }

    window.validateInvoiceForm = function() {
        if (invoiceItems.length === 0) {
            alert('الرجاء إضافة أصناف على الأقل إلى الفاتورة');
            return false;
        }

        if (!document.getElementById('customer_name').value.trim()) {
            alert('الرجاء إدخال اسم العميل');
            return false;
        }

        if (!document.getElementById('invoice_date').value) {
            alert('الرجاء إدخال تاريخ الفاتورة');
            return false;
        }

        return true;
    };

    window.clearForm = function() {
        if (confirm('هل أنت متأكد من إلغاء الفاتورة؟ سيتم حذف جميع الأصناف المضافة.')) {
            invoiceItems = [];
            updateItemsTable();
            updateItemsDataField();
            document.getElementById('invoiceForm').reset();
        }
    };

    document.getElementById('warranty_period').addEventListener('change', function() {
        const warrantyPeriod = parseInt(this.value);
        if (warrantyPeriod > 0) {
            const invoiceDate = document.getElementById('invoice_date').value;
            if (invoiceDate) {
                const endDate = new Date(invoiceDate);
                endDate.setDate(endDate.getDate() + warrantyPeriod);
                document.getElementById('warranty_end').value = endDate.toISOString().split('T')[0];
            }
        } else {
            document.getElementById('warranty_end').value = '';
        }
    });
});
</script>
