<?php
$isEdit = isset($invoice) && !empty($invoice);
$pageTitle = $isEdit ? 'Edit Invoice' : 'Create Invoice';
ob_start();
?>
<div class="container-fluid py-4">
    <div class="card">
        <div class="card-header">
            <h5><?= $pageTitle ?></h5>
        </div>
        <div class="card-body">
            <form action="<?= APP_URL ?>/finance/invoices<?= $isEdit ? '/' . $invoice['id'] . '/edit' : '/create' ?>" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Project</label>
                        <select name="project_id" class="form-control" required>
                            <option value="">Select Project</option>
                            <?php foreach ($projects ?? [] as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= (int)($invoice['project_id'] ?? $project_id ?? 0) === (int)$p['id'] ? 'selected' : '' ?>><?= htmlspecialchars($p['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Contractor/Supplier</label>
                        <select name="contractor_id" class="form-control">
                            <option value="">Select Contractor</option>
                            <?php foreach ($contractors ?? [] as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= (int)($invoice['contractor_id'] ?? $contractor_id ?? 0) === (int)$c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['company_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>Invoice Date</label>
                        <input type="date" name="date" value="<?= htmlspecialchars($invoice['date'] ?? date('Y-m-d')) ?>" class="form-control" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>Due Date</label>
                        <input type="date" name="due_date" value="<?= htmlspecialchars($invoice['due_date'] ?? '') ?>" class="form-control">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label>PO Reference</label>
                        <input type="text" name="po_reference" value="<?= htmlspecialchars($invoice['po_reference'] ?? '') ?>" class="form-control">
                    </div>
                </div>

                <hr class="my-4">
                <h6>Line Items</h6>
                <div class="table-responsive">
                    <table class="table" id="lineItemsTable">
                        <thead>
                            <tr>
                                <th>Description</th>
                                <th width="100">Qty</th>
                                <th width="150">Unit Price</th>
                                <th width="150">Total</th>
                                <th width="50"></th>
                            </tr>
                        </thead>
                        <tbody id="lineItemsBody">
                            <?php $existingItems = $invoice['items'] ?? [[]]; ?>
                            <?php foreach ($existingItems as $idx => $li): ?>
                            <tr>
                                <td><input type="text" name="items[<?= $idx ?>][description]" value="<?= htmlspecialchars($li['description'] ?? '') ?>" class="form-control" required></td>
                                <td><input type="number" name="items[<?= $idx ?>][qty]" class="form-control qty-input" value="<?= htmlspecialchars($li['qty'] ?? 1) ?>" min="1" required></td>
                                <td><input type="number" name="items[<?= $idx ?>][unit_price]" class="form-control price-input" step="0.01" value="<?= htmlspecialchars($li['unit_price'] ?? '') ?>" required></td>
                                <td><input type="text" class="form-control row-total" readonly value="<?= number_format((float)($li['total'] ?? 0), 2) ?>"></td>
                                <td><button type="button" class="btn btn-danger btn-sm remove-row"><i class="fa fa-trash"></i></button></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <button type="button" class="btn btn-sm btn-secondary" id="addRowBtn">Add Item</button>
                </div>

                <hr class="my-4">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label>Notes</label>
                            <textarea name="notes" class="form-control" rows="4"><?= htmlspecialchars($invoice['notes'] ?? '') ?></textarea>
                        </div>
                        <div class="mb-3">
                            <label>Attachment</label>
                            <input type="file" name="attachment" class="form-control">
                        </div>
                    </div>
                    <div class="col-md-4 offset-md-2">
                        <div class="d-flex justify-content-between mb-2">
                            <span>Subtotal:</span>
                            <span id="subtotalDisplay">$0.00</span>
                        </div>
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span>Tax (%):</span>
                            <input type="number" name="tax_percent" id="taxPercentInput" class="form-control w-50" value="0" min="0" step="0.1">
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>Tax Amount:</span>
                            <span id="taxAmountDisplay">$0.00</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between fw-bold fs-5">
                            <span>Total:</span>
                            <span id="totalDisplay">$0.00</span>
                        </div>
                    </div>
                </div>

                <div class="mt-4">
                    <button type="submit" class="btn btn-primary">Save Invoice</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let rowIndex = <?= count($existingItems) ?>;

    document.getElementById('addRowBtn').addEventListener('click', function() {
        const tbody = document.getElementById('lineItemsBody');
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td><input type="text" name="items[${rowIndex}][description]" class="form-control" required></td>
            <td><input type="number" name="items[${rowIndex}][qty]" class="form-control qty-input" value="1" min="1" required></td>
            <td><input type="number" name="items[${rowIndex}][unit_price]" class="form-control price-input" step="0.01" required></td>
            <td><input type="text" class="form-control row-total" readonly value="0.00"></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-row"><i class="fa fa-trash"></i></button></td>
        `;
        tbody.appendChild(tr);
        rowIndex++;
        calculateTotals();
    });

    document.getElementById('lineItemsBody').addEventListener('click', function(e) {
        if (e.target.closest('.remove-row')) {
            e.target.closest('tr').remove();
            calculateTotals();
        }
    });

    document.getElementById('lineItemsBody').addEventListener('input', function(e) {
        if (e.target.classList.contains('qty-input') || e.target.classList.contains('price-input')) {
            const tr = e.target.closest('tr');
            const qty = parseFloat(tr.querySelector('.qty-input').value) || 0;
            const price = parseFloat(tr.querySelector('.price-input').value) || 0;
            const total = qty * price;
            tr.querySelector('.row-total').value = total.toFixed(2);
            calculateTotals();
        }
    });

    document.getElementById('taxPercentInput').addEventListener('input', calculateTotals);

    function calculateTotals() {
        let subtotal = 0;
        document.querySelectorAll('.row-total').forEach(function(input) {
            subtotal += parseFloat(input.value) || 0;
        });

        const taxPercent = parseFloat(document.getElementById('taxPercentInput').value) || 0;
        const taxAmount = subtotal * (taxPercent / 100);
        const total = subtotal + taxAmount;

        document.getElementById('subtotalDisplay').textContent = '$' + subtotal.toFixed(2);
        document.getElementById('taxAmountDisplay').textContent = '$' + taxAmount.toFixed(2);
        document.getElementById('totalDisplay').textContent = '$' + total.toFixed(2);
    }
});
</script>
<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>
