<?php
include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$record_id = (int) ($_GET['record_id'] ?? 0);
$inv_res   = $db->query("invoices", "SELECT * FROM invoices WHERE record_id = $record_id");
$invoice   = $inv_res->fetch_assoc();

if (!$invoice) {
    echo "<script>alert('Invoice not found'); window.location.href='invoices.php';</script>";
    exit;
}

$items_res = $db->query("invoice_items",
    "SELECT * FROM invoice_items WHERE invoice_no = '{$invoice['invoice_no']}'"
);
$items = [];
while ($item = $items_res->fetch_assoc()) {
    $items[] = $item;
}
if (empty($items)) {
    $items[] = ['description' => '', 'quantity' => 1, 'unit_price' => 0, 'total' => 0];
}

/* Fetch stock items for datalist */
$stock_res   = $db->query("stock", "SELECT item_name, item_price FROM stock ORDER BY item_name ASC");
$stock_items = [];
$datalist_options = "";
while ($stock = $stock_res->fetch_assoc()) {
    $name  = htmlspecialchars($stock['item_name'], ENT_QUOTES);
    $price = (float) ($stock['item_price'] ?? 0);
    $stock_items[]     = ['name' => $name, 'price' => $price];
    $datalist_options .= "<option value='{$name}'>";
}
?>

<!-- Stock item datalist -->
<datalist id="stock_items_list">
    <?= $datalist_options ?>
</datalist>

<style>
    :root {
        --blue: #1e3a8a; --light-blue: #eaf0ff;
        --orange: #f97316; --white: #ffffff;
        --border: #d1d5db; --text: #0f172a;
    }

    body { margin: 0; background: #f8fafc; font-family: "Segoe UI", Roboto, Arial, sans-serif; color: var(--text); }
    .form_down { width: 95%; margin: auto; padding-bottom: 3vw; }
    h1 { font-size: 3em; color: var(--blue); margin: 1.5vw 0 0.5vw; }
    h2 { font-size: 1.5em; color: var(--blue); margin: 1.5vw 0 0.5vw; border-left: 4px solid var(--orange); padding-left: 0.5vw; }

    .card { background: var(--white); border-radius: 12px; padding: 1.5vw; margin-bottom: 1.5vw; box-shadow: 0 4px 15px rgba(0,0,0,0.07); }

    .field-row { display: flex; flex-direction: row; align-items: center; gap: 1vw; margin-bottom: 0.8vw; width: 100%; }
    .field-row label { font-size: 1.1em; font-weight: 600; color: var(--blue); width: 20%; }

    .inputs { border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; font-size: 1em; background: var(--white); color: var(--text); width: 40%; }
    .inputs:focus { outline: none; border-color: #2563eb; box-shadow: 0 0 0 2px rgba(37,99,235,0.15); }
    textarea.inputs { resize: vertical; width: 60%; }

    table { width: 100%; border-collapse: collapse; font-size: 1em; }
    th { background: var(--blue); color: var(--white); padding: 0.6vw; text-align: left; }
    td { border: 1px solid var(--border); padding: 0.3vw; }

    .row-input { width: 100%; border: 1px solid var(--border); border-radius: 6px; padding: 8px; font-size: 0.95em; box-sizing: border-box; }
    .row-input:focus { outline: none; border-color: #2563eb; }
    .row-input[readonly] { background: #f1f5f9; color: #64748b; }

    .delete_btn { background: linear-gradient(135deg, #f97316, #fb923c); color: var(--white); border: none; padding: 8px 14px; border-radius: 8px; font-weight: 700; cursor: pointer; width: 100%; }
    .delete_btn:hover { background: linear-gradient(135deg, #224396, #153b96); }

    .submit_btn { background: var(--blue); color: var(--white); border: none; padding: 1vw 2vw; font-size: 1.3em; font-weight: 700; border-radius: 8px; cursor: pointer; margin-top: 1vw; }
    .submit_btn:hover { background: var(--orange); }

    .add_row_btn { background: var(--orange); color: var(--white); border: none; padding: 0.6vw 1.2vw; font-size: 1em; font-weight: 700; border-radius: 8px; cursor: pointer; margin-top: 0.8vw; }
    .add_row_btn:hover { background: #ea580c; }

    .totals-row td { font-weight: 700; background: var(--light-blue); }
    .grand-total-row td { font-weight: 700; font-size: 1.1em; background: var(--blue); color: var(--white); }
</style>

<div class="form_down">
    <h1>EDIT INVOICE — <?= htmlspecialchars($invoice['invoice_no']) ?></h1>

    <form action="update_invoice.ajax.php" method="POST" onsubmit="return validateForm()">
        <input type="hidden" name="record_id"  value="<?= $record_id ?>">
        <input type="hidden" name="invoice_no" value="<?= htmlspecialchars($invoice['invoice_no']) ?>">

        <!-- Invoice Details -->
        <div class="card">
            <h2>INVOICE DETAILS</h2>

            <div class="field-row">
                <label>INVOICE NO :</label>
                <input type="text" class="inputs" value="<?= htmlspecialchars($invoice['invoice_no']) ?>" readonly>
            </div>
            <div class="field-row">
                <label>INVOICE DATE :</label>
                <input type="date" name="invoice_date" class="inputs" value="<?= htmlspecialchars($invoice['invoice_date']) ?>" required>
            </div>
            <div class="field-row">
                <label>DUE DATE :</label>
                <input type="date" name="due_date" class="inputs" value="<?= htmlspecialchars($invoice['due_date']) ?>" required>
            </div>
            <div class="field-row">
                <label>STATUS :</label>
                <select name="status" class="inputs">
                    <option value="UNPAID" <?= $invoice['status'] === 'UNPAID' ? 'selected' : '' ?>>UNPAID</option>
                    <option value="PAID"   <?= $invoice['status'] === 'PAID'   ? 'selected' : '' ?>>PAID</option>
                </select>
            </div>
        </div>

        <!-- Client Details -->
        <div class="card">
            <h2>CLIENT DETAILS</h2>

            <div class="field-row">
                <label>CLIENT NAME :</label>
                <input type="text" name="client_name" class="inputs" value="<?= htmlspecialchars($invoice['client_name']) ?>" required>
            </div>
            <div class="field-row">
                <label>ADDRESS :</label>
                <input type="text" name="client_address" class="inputs" value="<?= htmlspecialchars($invoice['client_address']) ?>">
            </div>
            <div class="field-row">
                <label>EMAIL :</label>
                <input type="email" name="client_email" class="inputs" value="<?= htmlspecialchars($invoice['client_email']) ?>">
            </div>
            <div class="field-row">
                <label>PHONE :</label>
                <input type="text" name="client_phone" class="inputs" value="<?= htmlspecialchars($invoice['client_phone']) ?>">
            </div>
        </div>

        <!-- Line Items -->
        <div class="card">
            <h2>LINE ITEMS</h2>
            <input type="hidden" id="no_rows" name="no_rows" value="<?= count($items) ?>">

            <table id="items_table">
                <thead>
                    <tr>
                        <th style="width:40%">Description</th>
                        <th style="width:12%">Qty</th>
                        <th style="width:15%">Unit Price (R)</th>
                        <th style="width:15%">Total (R)</th>
                        <th style="width:8%"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $idx => $item):
                        $n = $idx + 1;
                    ?>
                    <tr>
                        <td>
                            <input type="text" name="desc_<?= $n ?>" class="row-input"
                                list="stock_items_list"
                                value="<?= htmlspecialchars($item['description']) ?>"
                                placeholder="Type or pick a stock item..."
                                onchange="autofillPrice(<?= $n ?>)"
                                required>
                        </td>
                        <td><input type="number" name="qty_<?= $n ?>"        class="row-input" value="<?= $item['quantity']   ?>" min="0" step="any"  oninput="calcRow(<?= $n ?>)" required></td>
                        <td><input type="number" name="unit_price_<?= $n ?>" class="row-input" value="<?= $item['unit_price'] ?>" min="0" step="0.01" oninput="calcRow(<?= $n ?>)" required></td>
                        <td><input type="number" name="total_<?= $n ?>"      class="row-input" value="<?= $item['total']      ?>" readonly></td>
                        <td><button type="button" class="delete_btn" onclick="deleteRow(this)">X</button></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="totals-row">
                        <td colspan="3" style="text-align:right; padding:0.5vw;">SUBTOTAL :</td>
                        <td><input type="number" id="subtotal" name="subtotal" class="row-input" value="0" readonly></td>
                        <td></td>
                    </tr>
                    <tr class="grand-total-row">
                        <td colspan="3" style="text-align:right; padding:0.5vw;">TOTAL :</td>
                        <td><input type="number" id="grand_total" name="grand_total" class="row-input" value="0" readonly style="background:var(--blue); color:var(--white); font-weight:700;"></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>

            <button type="button" class="add_row_btn" onclick="addRow()">+ ADD ROW</button>
        </div>

        <!-- Notes -->
        <div class="card">
            <h2>NOTES</h2>
            <div class="field-row">
                <label>NOTES :</label>
                <textarea name="notes" class="inputs" rows="4"><?= htmlspecialchars($invoice['notes']) ?></textarea>
            </div>
        </div>

        <button type="submit" class="submit_btn">UPDATE INVOICE</button>
    </form>
</div>

<script>
    let rowIndex = <?= count($items) ?>;

    /* Build price lookup map from PHP stock data */
    const stockPrices = {
        <?php foreach ($stock_items as $s): ?>
        <?= json_encode($s['name']) ?>: <?= $s['price'] ?>,
        <?php endforeach; ?>
    };

    /* On load — calculate totals from existing saved values */
    window.onload = function () { calcTotals(); };

    /* Auto-fill unit price if description matches a stock item */
    function autofillPrice(i) {
        const desc  = document.querySelector(`[name="desc_${i}"]`).value.trim();
        const price = stockPrices[desc];

        if (price !== undefined) {
            document.querySelector(`[name="unit_price_${i}"]`).value = price.toFixed(2);
            calcRow(i);
        }
        /* If no match — do nothing, user keeps their custom price */
    }

    function calcRow(i) {
        const qty        = parseFloat(document.querySelector(`[name="qty_${i}"]`).value)        || 0;
        const unit_price = parseFloat(document.querySelector(`[name="unit_price_${i}"]`).value) || 0;
        document.querySelector(`[name="total_${i}"]`).value = (qty * unit_price).toFixed(2);
        calcTotals();
    }

    function calcTotals() {
        let subtotal = 0;
        document.querySelectorAll("[name^='total_']").forEach(input => {
            subtotal += parseFloat(input.value) || 0;
        });
        document.getElementById("subtotal").value    = subtotal.toFixed(2);