<?php
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/Mailer.php';
requireLogin();

// Handle create
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.');
        header('Location: manual_billing.php'); exit;
    }

    $customerId = (int)$_POST['customer_id'];
    $invoiceDate = $_POST['invoice_date'];
    $notes = trim($_POST['notes']);

    $descriptions = $_POST['description'] ?? [];
    $qtys = $_POST['qty'] ?? [];
    $prices = $_POST['unit_price'] ?? [];
    $cgsts = $_POST['cgst'] ?? [];
    $sgsts = $_POST['sgst'] ?? [];

    if (empty($descriptions) || $customerId <= 0) {
        setFlash('danger', 'Please select a customer and add at least one line item.');
        header('Location: manual_billing.php'); exit;
    }

    try {
        $pdo->beginTransaction();

        $invoiceNo = generateDocNumber('invoices', 'invoice_no', getSetting('invoice_prefix','INV'));

        $subtotal = 0; $cgstTotal = 0; $sgstTotal = 0;
        $lineData = [];

        foreach ($descriptions as $idx => $desc) {
            $desc = trim($desc);
            $qty = (float)$qtys[$idx];
            $price = (float)$prices[$idx];
            $cgstPct = (float)$cgsts[$idx];
            $sgstPct = (float)$sgsts[$idx];
            if ($desc === '' || $qty <= 0) continue;

            $lineSubtotal = $qty * $price;
            $lineCgst = round($lineSubtotal * $cgstPct / 100, 2);
            $lineSgst = round($lineSubtotal * $sgstPct / 100, 2);
            $lineTotal = $lineSubtotal + $lineCgst + $lineSgst;

            $subtotal += $lineSubtotal;
            $cgstTotal += $lineCgst;
            $sgstTotal += $lineSgst;

            $lineData[] = compact('desc','qty','price','cgstPct','sgstPct','lineSubtotal','lineCgst','lineSgst','lineTotal');
        }

        if (empty($lineData)) {
            $pdo->rollBack();
            setFlash('danger', 'No valid line items added.');
            header('Location: manual_billing.php'); exit;
        }

        $grandTotal = $subtotal + $cgstTotal + $sgstTotal;

        $stmt = $pdo->prepare("INSERT INTO invoices
            (invoice_no, invoice_type, customer_id, invoice_date, subtotal, cgst_amount, sgst_amount, discount_amount, grand_total, payment_status, notes, created_by)
            VALUES (?,?,?,?,?,?,?,0,?,?,?,?)");
        $stmt->execute([$invoiceNo, 'manual', $customerId, $invoiceDate, $subtotal, $cgstTotal, $sgstTotal, $grandTotal, 'pending', $notes, currentUserId()]);
        $invoiceId = $pdo->lastInsertId();

        foreach ($lineData as $l) {
            $pdo->prepare("INSERT INTO invoice_items
                (invoice_id, item_id, description, qty, unit_price, cgst_percent, sgst_percent, line_subtotal, line_cgst, line_sgst, line_total)
                VALUES (?,NULL,?,?,?,?,?,?,?,?,?)")
                ->execute([$invoiceId, $l['desc'], $l['qty'], $l['price'], $l['cgstPct'], $l['sgstPct'], $l['lineSubtotal'], $l['lineCgst'], $l['lineSgst'], $l['lineTotal']]);
        }

        $pdo->commit();
        setFlash('success', "Manual invoice $invoiceNo created successfully.");
        header("Location: ../invoice/invoice_view.php?id=$invoiceId");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error: ' . $e->getMessage());
        header('Location: manual_billing.php'); exit;
    }
}

$customers = $pdo->query("SELECT * FROM sale_vendors WHERE status=1 ORDER BY customer_name")->fetchAll();

$stmt = $pdo->query("SELECT i.*, c.customer_name FROM invoices i
                      JOIN sale_vendors c ON c.id=i.customer_id
                      WHERE i.invoice_type='manual' ORDER BY i.id DESC");
$manualBills = $stmt->fetchAll();

$cgstDefault = (float)getSetting('cgst_percent', 9);
$sgstDefault = (float)getSetting('sgst_percent', 9);
$csrf = generateCSRFToken();

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Manual Billing';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Billing</div>
        <h2 class="mb-0">Manual Billing (Service)</h2>
    </div>
    <button class="btn btn-primary" onclick="document.getElementById('billModal').classList.add('show')"><?= icon('plus') ?> New Manual Bill</button>
</div>

<div class="card">
    <div class="card-title">Manual / Service Invoices</div>
    <?php if ($manualBills): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Invoice #</th><th>Customer</th><th>Date</th>
                    <th class="text-right">Total</th><th class="text-right">Paid</th><th>Status</th><th>Email</th><th></th></tr>
            </thead>
            <tbody>
            <?php foreach ($manualBills as $b): ?>
            <tr>
                <td class="mono"><?= sanitize($b['invoice_no']) ?></td>
                <td><?= sanitize($b['customer_name']) ?></td>
                <td><?= formatDate($b['invoice_date']) ?></td>
                <td class="num"><strong><?= formatMoney($b['grand_total']) ?></strong></td>
                <td class="num"><?= formatMoney($b['paid_amount']) ?></td>
                <td><span class="badge badge-<?= $b['payment_status']=='paid'?'success':($b['payment_status']=='partial'?'warning':'danger') ?>"><?= $b['payment_status'] ?></span></td>
                <td><?php if ($b['email_sent']): ?><span class="badge badge-success"><?= icon('mail-forward') ?> Sent</span><?php else: ?><span class="badge badge-muted">Not sent</span><?php endif; ?></td>
                <td><a href="../invoice/invoice_view.php?id=<?= $b['id'] ?>" class="btn btn-icon btn-sm"><?= icon('eye') ?></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('tools') ?>No manual bills yet. Use this for services not tied to stock items.</div>
    <?php endif; ?>
</div>

<!-- New Manual Bill Modal -->
<div class="modal-backdrop" id="billModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <h2>New Manual Bill (Service)</h2>
            <button class="btn btn-icon" onclick="document.getElementById('billModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="create">

            <div class="form-grid">
                <div class="form-group">
                    <label>Customer <span class="req">*</span></label>
                    <select name="customer_id" required>
                        <option value="">-- Select Customer --</option>
                        <?php foreach ($customers as $c): ?>
                        <option value="<?= $c['id'] ?>"><?= sanitize($c['customer_name']) ?> (<?= sanitize($c['customer_code']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Invoice Date <span class="req">*</span></label>
                    <input type="date" name="invoice_date" value="<?= date('Y-m-d') ?>" required>
                </div>
            </div>

            <fieldset>
                <legend>Service / Item Lines</legend>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr><th style="min-width:220px">Description</th><th style="width:80px">Qty</th><th style="width:110px">Rate</th>
                                <th style="width:70px">CGST%</th><th style="width:70px">SGST%</th>
                                <th style="width:120px" class="text-right">Line Total</th><th style="width:40px"></th></tr>
                        </thead>
                        <tbody id="lineItemsBody"></tbody>
                    </table>
                </div>
                <button type="button" class="btn btn-sm mt-8" onclick="addLine()"><?= icon('plus') ?> Add Line</button>

                <div class="divider"></div>
                <div class="flex-end" style="gap:32px;">
                    <div class="text-sm">Subtotal: <strong class="mono" id="sumSubtotal">₹0.00</strong></div>
                    <div class="text-sm">GST: <strong class="mono" id="sumGst">₹0.00</strong></div>
                    <div>Grand Total: <strong class="mono" id="sumTotal" style="font-size:16px;">₹0.00</strong></div>
                </div>
            </fieldset>

            <div class="form-group full">
                <label>Notes</label>
                <textarea name="notes" rows="2" placeholder="Service description, warranty terms, etc."></textarea>
            </div>

            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="document.getElementById('billModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Create Bill</button>
            </div>
        </form>
    </div>
</div>

<script>
const CGST_DEFAULT = <?= $cgstDefault ?>;
const SGST_DEFAULT = <?= $sgstDefault ?>;

function addLine() {
    const tbody = document.getElementById('lineItemsBody');
    const row = document.createElement('tr');
    row.innerHTML = `
        <td><input type="text" name="description[]" placeholder="e.g. Laptop service & repair" required></td>
        <td><input type="number" name="qty[]" value="1" min="0.01" step="0.01" class="qty-input" oninput="recalcLine(this)"></td>
        <td><input type="number" name="unit_price[]" step="0.01" value="0" class="price-input" oninput="recalcLine(this)"></td>
        <td><input type="number" name="cgst[]" step="0.01" value="${CGST_DEFAULT}" class="cgst-input" oninput="recalcLine(this)"></td>
        <td><input type="number" name="sgst[]" step="0.01" value="${SGST_DEFAULT}" class="sgst-input" oninput="recalcLine(this)"></td>
        <td class="num line-total mono">₹0.00</td>
        <td><button type="button" class="btn btn-icon btn-sm" onclick="removeLine(this)"><?= icon('trash') ?></button></td>
    `;
    tbody.appendChild(row);
}
function removeLine(btn) { btn.closest('tr').remove(); recalcTotals(); }
function recalcLine(el) {
    const row = el.closest('tr');
    const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
    const price = parseFloat(row.querySelector('.price-input').value) || 0;
    const cgst = parseFloat(row.querySelector('.cgst-input').value) || 0;
    const sgst = parseFloat(row.querySelector('.sgst-input').value) || 0;
    const subtotal = qty * price;
    const total = subtotal + (subtotal*cgst/100) + (subtotal*sgst/100);
    row.querySelector('.line-total').textContent = '₹' + total.toFixed(2);
    recalcTotals();
}
function recalcTotals() {
    let subtotal=0, gst=0;
    document.querySelectorAll('#lineItemsBody tr').forEach(row => {
        const qty = parseFloat(row.querySelector('.qty-input')?.value) || 0;
        const price = parseFloat(row.querySelector('.price-input')?.value) || 0;
        const cgst = parseFloat(row.querySelector('.cgst-input')?.value) || 0;
        const sgst = parseFloat(row.querySelector('.sgst-input')?.value) || 0;
        const s = qty*price;
        subtotal += s;
        gst += s*cgst/100 + s*sgst/100;
    });
    document.getElementById('sumSubtotal').textContent = '₹' + subtotal.toFixed(2);
    document.getElementById('sumGst').textContent = '₹' + gst.toFixed(2);
    document.getElementById('sumTotal').textContent = '₹' + (subtotal+gst).toFixed(2);
}
addLine();
</script>

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