<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';

// التحقق من أن الرابط يحتوي على رقم الفاتورة
if (!isset($_GET['num'])) {
    redirect('review_invoices.php');
}

$invoice_number = trim($_GET['num']);

// جلب بيانات الفاتورة برقمها
$invoice = $db->fetchOne("SELECT * FROM invoices WHERE invoice_number = ?", [$invoice_number]);
if (!$invoice) {
    $_SESSION['error'] = 'الفاتورة غير موجودة';
    redirect('review_invoices.php');
}

// جلب العناصر المرتبطة بالفاتورة
$invoice['items'] = $db->fetchAll("SELECT * FROM invoice_items WHERE invoice_id = ?", [$invoice['id']]);

$page_title = 'تعديل الفاتورة #' . $invoice['invoice_number'];
require_once 'includes/header.php';

// جلب بيانات العميل
$customer_name  = $invoice['customer_name'] ?? '';
$customer_phone = $invoice['customer_phone'] ?? '';
$invoice_date   = $invoice['date'] ?? date('Y-m-d');
$notes          = $invoice['notes'] ?? '';
$items          = $invoice['items'] ?? [];
?>

<div class="content-section" id="edit-invoice">
    <div class="section-header">
        <h3>تعديل الفاتورة</h3>
    </div>
    <form id="editInvoiceForm" action="update_invoice.php" method="POST">
        <!-- نرسل رقم الفاتورة بدل الـ ID -->
        <input type="hidden" name="invoice_number" value="<?= htmlspecialchars($invoice['invoice_number']) ?>">
        
        <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" value="<?= htmlspecialchars($customer_name) ?>">
                </div>
                <div class="form-group">
                    <label for="customer_phone">رقم الهاتف</label>
                    <input type="tel" id="customer_phone" name="customer_phone" class="form-control" value="<?= htmlspecialchars($customer_phone) ?>">
                </div>
                <div class="form-group">
                    <label for="invoice_date">تاريخ الفاتورة</label>
                    <input type="date" id="invoice_date" name="invoice_date" class="form-control" required value="<?= htmlspecialchars($invoice_date) ?>">
                </div>
            </div>
        </div>
        
        <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">
                    <?php foreach ($items as $index => $item): ?>
                        <tr>
                            <td><input type="text" name="items[<?= $index ?>][name]" value="<?= htmlspecialchars($item['product_name']) ?>" class="form-control"></td>
                            <td><input type="number" name="items[<?= $index ?>][price]" value="<?= htmlspecialchars($item['price']) ?>" class="form-control" min="0" step="0.01"></td>
                            <td><input type="number" name="items[<?= $index ?>][quantity]" value="<?= htmlspecialchars($item['quantity']) ?>" class="form-control" min="1"></td>
                            <td><input type="date" name="items[<?= $index ?>][warranty_end]" value="<?= htmlspecialchars($item['warranty_end'] ?? '') ?>" class="form-control"></td>
                            <td><button type="button" class="btn btn-danger" onclick="this.closest('tr').remove()">حذف</button></td>
                        </tr>
                    <?php endforeach; ?>
                </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"><?= htmlspecialchars($notes) ?></textarea>
        </div>
        
        <div style="margin-top: 20px; text-align: left;">
            <button type="submit" class="btn btn-primary">حفظ التعديلات</button>
            <button type="button" class="btn btn-primary" onclick="addRow()">إضافة منتج</button>
            <a href="view_invoice.php?num=<?= urlencode($invoice['invoice_number']) ?>" class="btn btn-secondary">إلغاء</a>
        </div>
    </form>
</div>

<script>
function addRow() {
    const tableBody = document.getElementById('itemsTableBody');
    const rowCount = tableBody.rows.length;
    const row = document.createElement('tr');
    row.innerHTML = `
        <td><input type="text" name="items[${rowCount}][name]" class="form-control"></td>
        <td><input type="number" name="items[${rowCount}][price]" class="form-control" min="0" step="0.01"></td>
        <td><input type="number" name="items[${rowCount}][quantity]" class="form-control" min="1" value="1"></td>
        <td><input type="date" name="items[${rowCount}][warranty_end]" class="form-control"></td>
        <td><button type="button" class="btn btn-danger" onclick="this.closest('tr').remove()">حذف</button></td>
    `;
    tableBody.appendChild(row);
}
</script>

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