<?= $this->extend('layout/main') ?>
<?= $this->section('content') ?>

<h5 class="mb-4"><?= $mode === 'edit' ? 'Modifier la Facture' : 'Nouvelle Facture' ?></h5>

<form method="POST" action="<?= $mode === 'edit' ? '/invoices/edit/' . $invoice['id'] : '/invoices/create' ?>">
    <?= csrf_field() ?>

    <div class="row g-4">
        <!-- Header Info -->
        <div class="col-lg-8">
            <div class="table-card">
                <h6 class="mb-3">Informations generales</h6>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">Client</label>
                        <select name="invoice[client_id]" class="form-select" required>
                            <option value="">Selectionner un client</option>
                            <?php foreach ($clients as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= ($invoice['client_id'] ?? '') == $c['id'] ? 'selected' : '' ?>>
                                    <?= $c['code'] ?> - <?= $c['company_name'] ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Type</label>
                        <select name="invoice[invoice_type]" class="form-select">
                            <option value="facture" <?= ($invoice['invoice_type'] ?? '') === 'facture' ? 'selected' : '' ?>>Facture</option>
                            <option value="devis" <?= ($invoice['invoice_type'] ?? '') === 'devis' ? 'selected' : '' ?>>Devis</option>
                            <option value="avoir" <?= ($invoice['invoice_type'] ?? '') === 'avoir' ? 'selected' : '' ?>>Avoir</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Date</label>
                        <input type="date" name="invoice[date]" class="form-control" value="<?= $invoice['date'] ?? date('Y-m-d') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Echeance</label>
                        <input type="date" name="invoice[due_date]" class="form-control" value="<?= $invoice['due_date'] ?? date('Y-m-d', strtotime('+30 days')) ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Ref. Client</label>
                        <input type="text" name="invoice[reference_client]" class="form-control" value="<?= $invoice['reference_client'] ?? '' ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Code en douane</label>
                        <input type="text" name="invoice[customs_code]" class="form-control" value="<?= $invoice['customs_code'] ?? '' ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Reper. N</label>
                        <input type="text" name="invoice[reper_number]" class="form-control" value="<?= $invoice['reper_number'] ?? '' ?>">
                    </div>
                    <div class="col-md-8">
                        <label class="form-label">Designation generale</label>
                        <input type="text" name="invoice[designation_global]" class="form-control" value="<?= $invoice['designation_global'] ?? '' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Poids Brut</label>
                        <input type="number" step="0.01" name="invoice[gross_weight]" class="form-control" value="<?= $invoice['gross_weight'] ?? '' ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Unite</label>
                        <select name="invoice[weight_unit]" class="form-select">
                            <option value="KGS" <?= ($invoice['weight_unit'] ?? '') === 'KGS' ? 'selected' : '' ?>>KGS</option>
                            <option value="TON" <?= ($invoice['weight_unit'] ?? '') === 'TON' ? 'selected' : '' ?>>TON</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Nbre. Colis</label>
                        <input type="number" name="invoice[package_count]" class="form-control" value="<?= $invoice['package_count'] ?? '' ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Valeur devise</label>
                        <input type="number" step="0.01" name="invoice[currency_value]" class="form-control" value="<?= $invoice['currency_value'] ?? '' ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Devise</label>
                        <select name="invoice[currency_unit]" class="form-select">
                            <option value="EUR" <?= ($invoice['currency_unit'] ?? '') === 'EUR' ? 'selected' : '' ?>>EUR</option>
                            <option value="USD" <?= ($invoice['currency_unit'] ?? '') === 'USD' ? 'selected' : '' ?>>USD</option>
                            <option value="TND" <?= ($invoice['currency_unit'] ?? '') === 'TND' ? 'selected' : '' ?>>TND</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Expediteur</label>
                        <input type="text" name="invoice[shipper]" class="form-control" value="<?= $invoice['shipper'] ?? '' ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">N Declaration</label>
                        <input type="text" name="invoice[declaration_number]" class="form-control" value="<?= $invoice['declaration_number'] ?? '' ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Regime</label>
                        <input type="text" name="invoice[regime]" class="form-control" value="<?= $invoice['regime'] ?? '' ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">N Quittance</label>
                        <input type="text" name="invoice[quittance_number]" class="form-control" value="<?= $invoice['quittance_number'] ?? '' ?>">
                    </div>
                </div>
            </div>
        </div>

        <!-- Totals Panel -->
        <div class="col-lg-4">
            <div class="table-card sticky-top" style="top: 20px;">
                <h6 class="mb-3">Totaux</h6>
                <div class="mb-3">
                    <label class="form-label">Taux TVA</label>
                    <div class="input-group">
                        <input type="number" step="0.01" name="invoice[vat_rate]" id="vatRate" class="form-control" value="<?= $invoice['vat_rate'] ?? 0.19 ?>">
                        <span class="input-group-text">%</span>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Remise (%)</label>
                    <input type="number" step="0.01" name="invoice[discount_percent]" id="discountPercent" class="form-control" value="<?= $invoice['discount_percent'] ?? 0 ?>">
                </div>
                <div class="mb-3">
                    <label class="form-label">Avance</label>
                    <input type="number" step="0.01" name="invoice[advance_amount]" id="advanceAmount" class="form-control" value="<?= $invoice['advance_amount'] ?? 0 ?>">
                </div>
                <div class="mb-3">
                    <label class="form-label">Droit de timbres</label>
                    <input type="number" step="0.01" name="invoice[stamp_duty]" id="stampDuty" class="form-control" value="<?= $invoice['stamp_duty'] ?? 1 ?>">
                </div>
                <hr>
                <div class="d-flex justify-content-between mb-2">
                    <span>Debours:</span>
                    <span id="displayDebours" class="fw-bold">0,00 TND</span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>Taxables:</span>
                    <span id="displayTaxables" class="fw-bold">0,00 TND</span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>TVA:</span>
                    <span id="displayTVA" class="fw-bold">0,00 TND</span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>Timbres:</span>
                    <span id="displayTimbres" class="fw-bold">0,00 TND</span>
                </div>
                <hr>
                <div class="d-flex justify-content-between mb-2 fs-5">
                    <span class="fw-bold">Total TTC:</span>
                    <span id="displayTotal" class="fw-bold text-primary">0,00 TND</span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>Avance:</span>
                    <span id="displayAvance" class="fw-bold">0,00 TND</span>
                </div>
                <div class="d-flex justify-content-between fs-5">
                    <span class="fw-bold">Net a payer:</span>
                    <span id="displayNet" class="fw-bold text-success">0,00 TND</span>
                </div>
                <div class="mt-3 p-2 bg-light rounded">
                    <small class="text-muted fst-italic" id="amountInWords">Zero dinars</small>
                </div>
                <button type="button" class="btn btn-outline-primary w-100 mt-3" onclick="recalculate()">
                    <i class="bi bi-calculator"></i> Recalculer
                </button>
            </div>
        </div>
    </div>

    <!-- Invoice Lines -->
    <div class="table-card mt-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="m-0">Lignes de facture (Frais / Debours)</h6>
            <button type="button" class="btn btn-sm btn-success" onclick="addLine()">
                <i class="bi bi-plus-lg"></i> Ajouter une ligne
            </button>
        </div>
        <table class="table table-bordered" id="linesTable">
            <thead class="table-dark">
                <tr>
                    <th style="width:5%">N</th>
                    <th style="width:45%">Designation</th>
                    <th style="width:10%">Qte</th>
                    <th style="width:10%">Unite</th>
                    <th style="width:15%">Prix unitaire</th>
                    <th style="width:15%">Montant</th>
                    <th style="width:5%"></th>
                </tr>
            </thead>
            <tbody id="linesBody">
                <?php 
                $lineCount = count($lines);
                if ($lineCount === 0): 
                ?>
                    <tr class="line-row" data-index="0">
                        <td class="line-num">1</td>
                        <td><input type="text" name="lines[0][designation]" class="form-control form-control-sm" placeholder="Designation du frais..."></td>
                        <td><input type="number" step="0.01" name="lines[0][quantity]" class="form-control form-control-sm qty-input" value="1" onchange="recalculate()"></td>
                        <td><input type="text" name="lines[0][unit]" class="form-control form-control-sm" value="U"></td>
                        <td><input type="number" step="0.01" name="lines[0][unit_price]" class="form-control form-control-sm price-input" value="0" onchange="recalculate()"></td>
                        <td><input type="number" step="0.01" name="lines[0][amount]" class="form-control form-control-sm amount-input" value="0" readonly></td>
                        <td><button type="button" class="btn btn-sm btn-danger" onclick="removeLine(this)"><i class="bi bi-trash"></i></button></td>
                    </tr>
                <?php else: 
                    foreach ($lines as $idx => $line): 
                ?>
                    <tr class="line-row" data-index="<?= $idx ?>">
                        <td class="line-num"><?= $idx + 1 ?></td>
                        <td><input type="text" name="lines[<?= $idx ?>][designation]" class="form-control form-control-sm" value="<?= $line['designation'] ?? '' ?>"></td>
                        <td><input type="number" step="0.01" name="lines[<?= $idx ?>][quantity]" class="form-control form-control-sm qty-input" value="<?= $line['quantity'] ?? 1 ?>" onchange="recalculate()"></td>
                        <td><input type="text" name="lines[<?= $idx ?>][unit]" class="form-control form-control-sm" value="<?= $line['unit'] ?? 'U' ?>"></td>
                        <td><input type="number" step="0.01" name="lines[<?= $idx ?>][unit_price]" class="form-control form-control-sm price-input" value="<?= $line['unit_price'] ?? 0 ?>" onchange="recalculate()"></td>
                        <td><input type="number" step="0.01" name="lines[<?= $idx ?>][amount]" class="form-control form-control-sm amount-input" value="<?= $line['amount'] ?? 0 ?>" readonly></td>
                        <td><button type="button" class="btn btn-sm btn-danger" onclick="removeLine(this)"><i class="bi bi-trash"></i></button></td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <div class="d-flex justify-content-between mt-4">
        <a href="/invoices" class="btn btn-outline-secondary">Annuler</a>
        <button type="submit" class="btn btn-primary btn-lg">
            <i class="bi bi-check-lg"></i> <?= $mode === 'edit' ? 'Mettre a jour' : 'Creer la facture' ?>
        </button>
    </div>
</form>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
let lineIndex = <?= count($lines) > 0 ? count($lines) : 1 ?>;

function addLine() {
    const tbody = document.getElementById('linesBody');
    const tr = document.createElement('tr');
    tr.className = 'line-row';
    tr.setAttribute('data-index', lineIndex);
    tr.innerHTML = `
        <td class="line-num">${lineIndex + 1}</td>
        <td><input type="text" name="lines[${lineIndex}][designation]" class="form-control form-control-sm" placeholder="Designation du frais..."></td>
        <td><input type="number" step="0.01" name="lines[${lineIndex}][quantity]" class="form-control form-control-sm qty-input" value="1" onchange="recalculate()"></td>
        <td><input type="text" name="lines[${lineIndex}][unit]" class="form-control form-control-sm" value="U"></td>
        <td><input type="number" step="0.01" name="lines[${lineIndex}][unit_price]" class="form-control form-control-sm price-input" value="0" onchange="recalculate()"></td>
        <td><input type="number" step="0.01" name="lines[${lineIndex}][amount]" class="form-control form-control-sm amount-input" value="0" readonly></td>
        <td><button type="button" class="btn btn-sm btn-danger" onclick="removeLine(this)"><i class="bi bi-trash"></i></button></td>
    `;
    tbody.appendChild(tr);
    lineIndex++;
    renumberLines();
}

function removeLine(btn) {
    const rows = document.querySelectorAll('.line-row');
    if (rows.length <= 1) {
        Swal.fire('Attention', 'Au moins une ligne est requise', 'warning');
        return;
    }
    btn.closest('tr').remove();
    renumberLines();
    recalculate();
}

function renumberLines() {
    document.querySelectorAll('.line-row').forEach((row, idx) => {
        row.querySelector('.line-num').textContent = idx + 1;
    });
}

function recalculate() {
    const rows = document.querySelectorAll('.line-row');
    const lines = [];

    rows.forEach(row => {
        const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
        const price = parseFloat(row.querySelector('.price-input').value) || 0;
        const amount = qty * price;
        row.querySelector('.amount-input').value = amount.toFixed(2);

        lines.push({
            quantity: qty,
            unit_price: price,
            amount: amount,
            is_taxable: 0
        });
    });

    const vatRate = parseFloat(document.getElementById('vatRate').value) || 0.19;
    const discount = parseFloat(document.getElementById('discountPercent').value) || 0;
    const advance = parseFloat(document.getElementById('advanceAmount').value) || 0;
    const stampDuty = parseFloat(document.getElementById('stampDuty').value) || 1;

    // Send to server for accurate calculation
    fetch('/invoices/ajax-calculate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: new URLSearchParams({
            'lines': JSON.stringify(lines),
            'vat_rate': vatRate,
            'discount_percent': discount,
            'advance_amount': advance,
            'stamp_duty': stampDuty,
            '<?= csrf_token() ?>': '<?= csrf_hash() ?>'
        })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('displayDebours').textContent = formatNumber(data.totals.disbursements) + ' TND';
            document.getElementById('displayTaxables').textContent = formatNumber(data.totals.vat_base) + ' TND';
            document.getElementById('displayTVA').textContent = formatNumber(data.totals.vat_amount) + ' TND';
            document.getElementById('displayTimbres').textContent = formatNumber(data.totals.stamp_duty) + ' TND';
            document.getElementById('displayTotal').textContent = formatNumber(data.totals.total_ttc) + ' TND';
            document.getElementById('displayAvance').textContent = formatNumber(data.totals.advance_amount) + ' TND';
            document.getElementById('displayNet').textContent = formatNumber(data.totals.net_payable) + ' TND';
            document.getElementById('amountInWords').textContent = data.totals.amount_in_words;
        }
    });
}

function formatNumber(num) {
    return parseFloat(num).toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

// Initial calculation
recalculate();
</script>
<?= $this->endSection() ?>
