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

$deliveryNoteId = (int)($_GET['delivery_note_id'] ?? 0);

$stmt = $pdo->prepare("SELECT d.*, c.customer_name, c.email, q.id as quotation_id, q.quotation_no,
                        q.subtotal, q.cgst_amount, q.sgst_amount, q.discount_amount, q.grand_total
                        FROM delivery_notes d
                        JOIN sale_vendors c ON c.id=d.customer_id
                        JOIN quotations q ON q.id=d.quotation_id
                        WHERE d.id=?");
$stmt->execute([$deliveryNoteId]);
$d = $stmt->fetch();

if (!$d) {
    setFlash('danger', 'Delivery note not found.');
    header('Location: ../delivery/delivery_notes.php'); exit;
}
if ($d['status'] !== 'delivered') {
    setFlash('danger', 'Delivery must be marked as delivered before generating the tax invoice.');
    header('Location: ../delivery/delivery_view.php?id=' . $deliveryNoteId); exit;
}

// Already invoiced?
$check = $pdo->prepare("SELECT id FROM invoices WHERE delivery_note_id=?");
$check->execute([$deliveryNoteId]);
if ($existing = $check->fetch()) {
    header('Location: invoice_view.php?id=' . $existing['id']); exit;
}

// Pull quotation line items (final amounts - discount already baked in)
$stmt = $pdo->prepare("SELECT qi.*, i.item_name, i.item_code, i.unit, i.hsn_code
                        FROM quotation_items qi JOIN items i ON i.id=qi.item_id WHERE qi.quotation_id=?");
$stmt->execute([$d['quotation_id']]);
$lineItems = $stmt->fetchAll();

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

    try {
        $pdo->beginTransaction();

        $invoiceNo = generateDocNumber('invoices', 'invoice_no', getSetting('invoice_prefix','INV'));
        $invoiceDate = $_POST['invoice_date'];

        // Recompute subtotal/cgst/sgst on the FINAL (post-discount) amounts so invoice tax matches grand_total
        $subtotal = 0; $cgstTotal = 0; $sgstTotal = 0;
        foreach ($lineItems as $li) {
            // Back-calculate base amount from final amount, since GST was originally on pre-discount subtotal
            // Simplify: split final_amount proportionally using original cgst/sgst percent on the discounted base
            $originalBase = $li['line_subtotal'];
            $originalTaxTotal = $li['line_cgst'] + $li['line_sgst'];
            $originalTotal = $li['line_total_before_discount'];
            $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 0;

            $finalBase = round($originalBase * $ratio, 2);
            $finalCgst = round($li['line_cgst'] * $ratio, 2);
            $finalSgst = round($li['line_sgst'] * $ratio, 2);

            $subtotal += $finalBase;
            $cgstTotal += $finalCgst;
            $sgstTotal += $finalSgst;
        }
        $grandTotal = $d['grand_total'];

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

        foreach ($lineItems as $li) {
            $originalTotal = $li['line_total_before_discount'];
            $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 0;
            $finalBase = round($li['line_subtotal'] * $ratio, 2);
            $finalCgst = round($li['line_cgst'] * $ratio, 2);
            $finalSgst = round($li['line_sgst'] * $ratio, 2);
            $lineTotal = $finalBase + $finalCgst + $finalSgst;
            $unitPrice = $li['qty'] > 0 ? $finalBase / $li['qty'] : 0;

            $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 (?,?,?,?,?,?,?,?,?,?,?)")
                ->execute([$invoiceId, $li['item_id'], $li['item_name'], $li['qty'], $unitPrice,
                           $li['cgst_percent'], $li['sgst_percent'], $finalBase, $finalCgst, $finalSgst, $lineTotal]);
        }

        $pdo->commit();
        setFlash('success', "Tax Invoice $invoiceNo generated successfully.");
        header("Location: invoice_view.php?id=$invoiceId");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error: ' . $e->getMessage());
        header("Location: invoice_create.php?delivery_note_id=$deliveryNoteId"); exit;
    }
}

$csrf = generateCSRFToken();

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

<div class="page-header">
    <div>
        <div class="eyebrow">Invoice</div>
        <h2 class="mb-0">Generate Tax Invoice</h2>
    </div>
    <a href="../delivery/delivery_view.php?id=<?= $deliveryNoteId ?>" class="btn"><?= icon('arrow-left') ?> Back</a>
</div>

<div class="card" style="max-width:800px; margin:0 auto;">
    <div class="card-title">From Delivery Note: <span class="mono"><?= sanitize($d['delivery_no']) ?></span></div>
    <div class="form-grid" style="margin-bottom:16px;">
        <div>
            <div class="text-sm text-muted">Customer</div>
            <strong><?= sanitize($d['customer_name']) ?></strong>
        </div>
        <div>
            <div class="text-sm text-muted">Reference Quotation</div>
            <div class="mono"><?= sanitize($d['quotation_no']) ?></div>
        </div>
        <div>
            <div class="text-sm text-muted">Total Amount</div>
            <strong class="mono" style="font-size:18px;"><?= formatMoney($d['grand_total']) ?></strong>
        </div>
    </div>

    <div class="table-wrap">
        <table>
            <thead><tr><th>Item</th><th class="text-right">Qty</th><th class="text-right">Amount</th></tr></thead>
            <tbody>
            <?php foreach ($lineItems as $li): ?>
            <tr>
                <td><?= sanitize($li['item_name']) ?></td>
                <td class="num"><?= $li['qty'] ?></td>
                <td class="num"><?= formatMoney($li['line_final_amount']) ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <form method="POST" class="mt-16">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <input type="hidden" name="action" value="create">
        <div class="form-grid">
            <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>
        <div class="flex-end gap-8 mt-16">
            <button type="submit" class="btn btn-primary"><?= icon('receipt') ?> Generate Tax Invoice</button>
        </div>
    </form>
</div>

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