<?= $this->extend('admin/layout/main') ?>
<?= $this->section('content') ?>
<h3 class="mb-3"><?= $invoice ? lang('App.edit') : lang('App.add_new') ?> - <?= lang('App.invoices') ?></h3>

<div class="row">
<div class="col-md-7">
<div class="card p-4">
<form method="post" action="<?= $invoice ? '/admin/invoices/' . $invoice['id'] : '/admin/invoices' ?>">
    <?= csrf_field() ?>
    <div class="mb-3">
        <label class="form-label"><?= lang('App.client') ?></label>
        <select name="client_id" class="form-select" required>
            <?php foreach ($clients as $c): ?>
                <option value="<?= $c['id'] ?>" <?= ($invoice['client_id'] ?? null) == $c['id'] ? 'selected' : '' ?>><?= esc($c['name']) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="mb-3">
        <label class="form-label"><?= lang('App.invoice_number') ?></label>
        <input type="text" name="invoice_number" class="form-control" value="<?= esc($invoice['invoice_number'] ?? $suggestedNumber ?? '') ?>" required>
    </div>
    <div class="row">
        <div class="col-6 mb-3">
            <label class="form-label"><?= lang('App.amount') ?></label>
            <input type="number" step="0.01" name="amount" class="form-control" value="<?= esc($invoice['amount'] ?? '') ?>" required>
        </div>
        <div class="col-6 mb-3">
            <label class="form-label"><?= lang('App.currency') ?></label>
            <select name="currency" class="form-select">
                <?php foreach ($currencies as $curr): $cur = $curr['code']; ?>
                    <option <?= ($invoice['currency'] ?? $currencies[0]['code']) === $cur ? 'selected' : '' ?>><?= $cur ?><?= !empty($curr['name']) ? ' - ' . esc($curr['name']) : '' ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <div class="mb-3">
        <label class="form-label">سعر الصرف وقت الإصدار</label>
        <input type="number" step="0.000001" name="exchange_rate_at_creation" class="form-control" value="<?= esc($invoice['exchange_rate_at_creation'] ?? 1) ?>">
    </div>
    <div class="row">
        <div class="col-6 mb-3">
            <label class="form-label"><?= lang('App.issue_date') ?></label>
            <input type="date" name="issue_date" class="form-control" value="<?= esc($invoice['issue_date'] ?? date('Y-m-d')) ?>" required>
        </div>
        <div class="col-6 mb-3">
            <label class="form-label"><?= lang('App.due_date') ?></label>
            <input type="date" name="due_date" class="form-control" value="<?= esc($invoice['due_date'] ?? '') ?>" required>
        </div>
    </div>
    <div class="mb-3">
        <label class="form-label"><?= lang('App.status') ?></label>
        <select name="status" class="form-select">
            <?php foreach (['draft' => lang('App.draft'), 'sent' => lang('App.sent'), 'paid' => lang('App.paid'), 'overdue' => lang('App.overdue'), 'cancelled' => lang('App.cancelled')] as $val => $label): ?>
                <option value="<?= $val ?>" <?= ($invoice['status'] ?? 'draft') === $val ? 'selected' : '' ?>><?= $label ?></option>
            <?php endforeach; ?>
        </select>
    </div>

    <label class="form-label"><?= lang('App.items') ?></label>
    <p class="text-muted small mb-2">اختر منتج من الكتالوج (يعبّي الوصف والسعر تلقائياً) أو اكتب بند حر يدوياً، وتقدر تضيف أكتر من بند.</p>
    <div id="items-wrap">
        <?php $rows = $items ?? []; if (empty($rows)) $rows = [['description' => '', 'amount' => '', 'product_id' => '']]; ?>
        <?php foreach ($rows as $item): ?>
            <div class="row mb-2 g-2">
                <div class="col-3">
                    <select name="item_product_id[]" class="form-select form-select-sm product-select" onchange="fillFromProduct(this)">
                        <option value="">— منتج —</option>
                        <?php foreach ($products as $p): ?>
                            <option value="<?= $p['id'] ?>" data-name="<?= esc($p['name']) ?>" data-price="<?= $p['price'] ?>"
                                <?= ($item['product_id'] ?? '') == $p['id'] ? 'selected' : '' ?>>
                                <?= esc($p['name']) ?> (<?= number_format($p['price'], 2) ?> <?= esc($p['currency']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-6"><input type="text" name="item_description[]" class="form-control form-control-sm" placeholder="الوصف" value="<?= esc($item['description'] ?? '') ?>"></div>
                <div class="col-3"><input type="number" step="0.01" name="item_amount[]" class="form-control form-control-sm" placeholder="<?= lang('App.amount') ?>" value="<?= esc($item['amount'] ?? '') ?>"></div>
            </div>
        <?php endforeach; ?>
    </div>
    <button type="button" class="btn btn-sm btn-outline-secondary mb-3" onclick="addItemRow()">+ إضافة بند</button>

    <div class="mb-3">
        <label class="form-label">ملاحظات</label>
        <textarea name="notes" class="form-control"><?= esc($invoice['notes'] ?? '') ?></textarea>
    </div>
    <button class="btn btn-dark"><?= lang('App.save') ?></button>
    <a href="/admin/invoices" class="btn btn-light"><?= lang('App.cancel') ?></a>
</form>
</div>
</div>

<?php if ($invoice): ?>
<div class="col-md-5">
    <div class="card p-4 mb-3">
        <h6><?= lang('App.add_payment') ?></h6>
        <form method="post" action="/admin/invoices/<?= $invoice['id'] ?>/payments">
            <?= csrf_field() ?>
            <div class="row g-2">
                <div class="col-6"><input type="number" step="0.01" name="amount" class="form-control" placeholder="<?= lang('App.amount') ?>" required></div>
                <div class="col-6"><input type="text" name="currency" class="form-control" placeholder="USD" value="<?= esc($invoice['currency']) ?>"></div>
                <div class="col-6">
                    <select name="payment_method" class="form-select">
                        <option value="cash">نقدي</option>
                        <option value="check">شيك</option>
                        <option value="bank_transfer">تحويل بنكي</option>
                        <option value="other">أخرى</option>
                    </select>
                </div>
                <div class="col-6">
                    <select name="status" class="form-select">
                        <option value="completed">مكتمل (تم التحصيل)</option>
                        <option value="pending">قيد التحصيل (شيك لم يُصرف بعد)</option>
                    </select>
                </div>
                <div class="col-6"><input type="date" name="paid_at" class="form-control" value="<?= date('Y-m-d') ?>"></div>
                <div class="col-6"><input type="text" name="reference" class="form-control" placeholder="رقم الشيك/مرجع"></div>
            </div>
            <button class="btn btn-sm btn-dark mt-2 w-100"><?= lang('App.add_payment') ?></button>
        </form>
    </div>
    <div class="card p-4">
        <h6><?= lang('App.payments') ?></h6>
        <?php
        $methodLabels = ['cash' => 'نقدي', 'check' => 'شيك', 'bank_transfer' => 'تحويل بنكي', 'other' => 'أخرى'];
        ?>
        <?php foreach (($payments ?? []) as $p): ?>
            <div class="d-flex justify-content-between align-items-center border-bottom py-2 small">
                <div>
                    <div><?= esc($p['paid_at']) ?> — <?= $methodLabels[$p['payment_method']] ?? esc($p['payment_method']) ?></div>
                    <?php if (!empty($p['reference'])): ?><div class="text-muted">مرجع: <?= esc($p['reference']) ?></div><?php endif; ?>
                </div>
                <div class="text-end">
                    <div><?= number_format($p['amount'], 2) ?> <?= esc($p['currency']) ?></div>
                    <span class="badge <?= $p['status'] === 'completed' ? 'bg-success' : 'bg-warning text-dark' ?>">
                        <?= $p['status'] === 'completed' ? 'مكتمل' : 'قيد التحصيل' ?>
                    </span>
                </div>
            </div>
        <?php endforeach; ?>
        <?php if (empty($payments)): ?><p class="text-muted small mb-0"><?= lang('App.no_data') ?></p><?php endif; ?>
    </div>
</div>
<?php endif; ?>
</div>

<script>
function addItemRow() {
    const wrap = document.getElementById('items-wrap');
    const row = document.createElement('div');
    row.className = 'row mb-2 g-2';
    const productOptions = `<?php foreach ($products as $p): ?>
        <option value="<?= $p['id'] ?>" data-name="<?= esc($p['name']) ?>" data-price="<?= $p['price'] ?>"><?= esc($p['name']) ?> (<?= number_format($p['price'], 2) ?> <?= esc($p['currency']) ?>)</option>
    <?php endforeach; ?>`;
    row.innerHTML = `<div class="col-3">
            <select name="item_product_id[]" class="form-select form-select-sm product-select" onchange="fillFromProduct(this)">
                <option value="">— منتج —</option>
                ${productOptions}
            </select>
        </div>
        <div class="col-6"><input type="text" name="item_description[]" class="form-control form-control-sm" placeholder="الوصف"></div>
        <div class="col-3"><input type="number" step="0.01" name="item_amount[]" class="form-control form-control-sm" placeholder="المبلغ"></div>`;
    wrap.appendChild(row);
}

function fillFromProduct(select) {
    const row = select.closest('.row');
    const option = select.options[select.selectedIndex];
    if (!option.value) return;
    row.querySelector('input[name="item_description[]"]').value = option.dataset.name;
    row.querySelector('input[name="item_amount[]"]').value = option.dataset.price;
}
</script>
<?= $this->endSection() ?>
