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

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

    $customerId = (int)$_POST['customer_id'];
    $quotationDate = $_POST['quotation_date'];
    $validUntil = $_POST['valid_until'];
    $discountPercent = (float)($_POST['discount_percent'] ?? 0);
    $notes = trim($_POST['notes']);

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

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

    try {
        $pdo->beginTransaction();

        $quotationNo = generateDocNumber('quotations', 'quotation_no', getSetting('quotation_prefix','QTN'));

        // STEP 1: Calculate totals before discount (with GST 9+9)
        $subtotal = 0; $cgstTotal = 0; $sgstTotal = 0;
        $lineData = [];

        foreach ($itemIds as $idx => $itemId) {
            $itemId = (int)$itemId;
            $qty = (int)$qtys[$idx];
            $price = (float)$prices[$idx];
            $cgstPct = (float)$cgsts[$idx];
            $sgstPct = (float)$sgsts[$idx];
            if ($itemId <= 0 || $qty <= 0) continue;

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

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

            $lineData[] = [
                'item_id' => $itemId, 'qty' => $qty, 'price' => $price,
                'cgst_pct' => $cgstPct, 'sgst_pct' => $sgstPct,
                'line_subtotal' => $lineSubtotal, 'line_cgst' => $lineCgst, 'line_sgst' => $lineSgst,
                'line_total_before_discount' => $lineTotalBeforeDiscount
            ];
        }

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

        $totalBeforeDiscount = $subtotal + $cgstTotal + $sgstTotal;

        // STEP 2: Apply discount % internally -> get grand total (this is what customer sees, NO discount mentioned)
        $discountAmount = round($totalBeforeDiscount * $discountPercent / 100, 2);
        $grandTotal = $totalBeforeDiscount - $discountAmount;

        // STEP 3: Distribute discount proportionally across line items
        // so each line's "final_amount" (shown to customer) reflects the adjusted price
        // without exposing the discount % anywhere on the customer document
        foreach ($lineData as &$line) {
            $proportion = $totalBeforeDiscount > 0 ? $line['line_total_before_discount'] / $totalBeforeDiscount : 0;
            $line['line_discount_amount'] = round($discountAmount * $proportion, 2);
            $line['line_final_amount'] = $line['line_total_before_discount'] - $line['line_discount_amount'];
        }
        unset($line);

        // Insert quotation header
        $stmt = $pdo->prepare("INSERT INTO quotations
            (quotation_no, customer_id, quotation_date, valid_until, subtotal, cgst_amount, sgst_amount,
             total_before_discount, discount_percent, discount_amount, grand_total, status, notes, created_by)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([
            $quotationNo, $customerId, $quotationDate, $validUntil,
            $subtotal, $cgstTotal, $sgstTotal,
            $totalBeforeDiscount, $discountPercent, $discountAmount, $grandTotal,
            'draft', $notes, currentUserId()
        ]);
        $quotationId = $pdo->lastInsertId();

        foreach ($lineData as $line) {
            $pdo->prepare("INSERT INTO quotation_items
                (quotation_id, item_id, qty, unit_price, cgst_percent, sgst_percent,
                 line_subtotal, line_cgst, line_sgst, line_total_before_discount, line_discount_amount, line_final_amount)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
                ->execute([
                    $quotationId, $line['item_id'], $line['qty'], $line['price'],
                    $line['cgst_pct'], $line['sgst_pct'],
                    $line['line_subtotal'], $line['line_cgst'], $line['line_sgst'],
                    $line['line_total_before_discount'], $line['line_discount_amount'], $line['line_final_amount']
                ]);
        }

        $pdo->commit();
        setFlash('success', "Quotation $quotationNo created. Generate the PDF and click 'Send to Customer' to email it.");
        header("Location: quotation_view.php?id=$quotationId");
        exit;

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

// Update status (accept/reject)
if (isset($_GET['action']) && in_array($_GET['action'], ['accept','reject']) && isset($_GET['id'])) {
    $status = $_GET['action'] === 'accept' ? 'accepted' : 'rejected';
    $pdo->prepare("UPDATE quotations SET status=? WHERE id=?")->execute([$status, (int)$_GET['id']]);
    setFlash('success', "Quotation marked as $status.");
    header('Location: quotations.php'); exit;
}

// Send email
if (isset($_GET['action']) && $_GET['action'] === 'send_email' && isset($_GET['id'])) {
    $result = Mailer::sendQuotation((int)$_GET['id']);
    if ($result['success']) {
        setFlash('success', 'Quotation emailed to customer successfully.');
    } else {
        setFlash('danger', 'Email failed: ' . $result['error']);
    }
    header("Location: quotation_view.php?id=" . (int)$_GET['id']); exit;
}

// Delete (only draft)
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $pdo->prepare("SELECT status FROM quotations WHERE id=?");
    $stmt->execute([$id]);
    $q = $stmt->fetch();
    if ($q && $q['status'] === 'draft') {
        $pdo->prepare("DELETE FROM quotations WHERE id=?")->execute([$id]);
        setFlash('success', 'Quotation deleted.');
    } else {
        setFlash('danger', 'Only draft quotations can be deleted.');
    }
    header('Location: quotations.php'); exit;
}

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

$stmt = $pdo->prepare("SELECT q.*, c.customer_name, c.email FROM quotations q
                        JOIN sale_vendors c ON c.id=q.customer_id ORDER BY q.id DESC LIMIT 100");
$stmt->execute();
$quotations = $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 = 'Quotations';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Sales Flow</div>
        <h2 class="mb-0">Quotations</h2>
    </div>
    <button class="btn btn-primary" onclick="document.getElementById('quoteModal').classList.add('show')"><?= icon('plus') ?> New Quotation</button>
</div>

<div class="card">
    <?php if ($quotations): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Quotation #</th><th>Customer</th><th>Date</th><th>Valid Until</th>
                    <th class="text-right">Amount</th><th>Status</th><th>Email</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($quotations as $q): ?>
            <tr>
                <td><a href="quotation_view.php?id=<?= $q['id'] ?>" class="mono"><?= sanitize($q['quotation_no']) ?></a></td>
                <td><?= sanitize($q['customer_name']) ?></td>
                <td><?= formatDate($q['quotation_date']) ?></td>
                <td><?= formatDate($q['valid_until']) ?></td>
                <td class="num"><strong><?= formatMoney($q['grand_total']) ?></strong></td>
                <td><span class="badge badge-<?= $q['status']=='accepted'?'success':($q['status']=='rejected'?'danger':($q['status']=='sent'?'info':'muted')) ?>"><?= $q['status'] ?></span></td>
                <td><?php if ($q['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>
                    <div class="flex gap-8">
                        <a href="quotation_view.php?id=<?= $q['id'] ?>" class="btn btn-icon btn-sm" title="View"><?= icon('eye') ?></a>
                        <?php if ($q['status']=='draft'): ?>
                        <a href="?action=delete&id=<?= $q['id'] ?>" class="btn btn-icon btn-sm" title="Delete" onclick="return confirm('Delete this draft quotation?')"><?= icon('trash') ?></a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('file-description') ?>No quotations yet. Click "New Quotation" to create one.</div>
    <?php endif; ?>
</div>

<!-- New Quotation Modal -->
<div class="modal-backdrop" id="quoteModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <h2>New Quotation</h2>
            <button class="btn btn-icon" onclick="document.getElementById('quoteModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST" id="quoteForm">
            <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>Quotation Date <span class="req">*</span></label>
                    <input type="date" name="quotation_date" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="form-group">
                    <label>Valid Until</label>
                    <input type="date" name="valid_until" value="<?= date('Y-m-d', strtotime('+15 days')) ?>">
                </div>
            </div>

            <fieldset>
                <legend>Step 1: Select Items (GST 9% + 9% applied automatically)</legend>
                <div class="table-wrap">
                    <table id="lineItemsTable">
                        <thead>
                            <tr><th style="min-width:180px">Item</th><th style="width:100px">Qty</th><th style="width:130px">Unit Price</th>
                                <th style="width:90px">CGST%</th><th style="width:90px">SGST%</th>
                                <th style="width:130px" 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 Item</button>
            </fieldset>

            <fieldset>
                <legend>Step 2: Apply Discount (Internal Only)</legend>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Discount % (will NOT be shown to customer)</label>
                        <input type="number" step="0.01" name="discount_percent" id="discountPercent" value="0" min="0" max="100" oninput="recalcTotals()">
                        <div class="text-sm text-faint">Customer quotation will show only the final adjusted amount as item price - discount % is never displayed.</div>
                    </div>
                </div>

                <div class="divider"></div>
                <div style="background:var(--color-surface-2); border-radius:var(--radius-md); padding:14px;">
                    <div class="flex-between mt-8" style="margin-bottom:4px;">
                        <span class="text-sm text-muted">Subtotal (before GST)</span>
                        <strong class="mono" id="sumSubtotal">₹0.00</strong>
                    </div>
                    <div class="flex-between" style="margin-bottom:4px;">
                        <span class="text-sm text-muted">CGST (9%)</span>
                        <strong class="mono" id="sumCgst">₹0.00</strong>
                    </div>
                    <div class="flex-between" style="margin-bottom:4px;">
                        <span class="text-sm text-muted">SGST (9%)</span>
                        <strong class="mono" id="sumSgst">₹0.00</strong>
                    </div>
                    <div class="flex-between" style="margin-bottom:4px;">
                        <span class="text-sm text-muted">Total before discount</span>
                        <strong class="mono" id="sumBeforeDiscount">₹0.00</strong>
                    </div>
                    <div class="flex-between" style="margin-bottom:4px; color:var(--color-accent-dk);">
                        <span class="text-sm">Discount amount (internal)</span>
                        <strong class="mono" id="sumDiscount">₹0.00</strong>
                    </div>
                    <div class="divider"></div>
                    <div class="flex-between">
                        <span style="font-weight:700;">Customer Quotation Total</span>
                        <strong class="mono" id="sumGrandTotal" style="font-size:18px; color:var(--color-primary);">₹0.00</strong>
                    </div>
                </div>
            </fieldset>

            <div class="form-group full">
                <label>Notes / Terms</label>
                <textarea name="notes" rows="2" placeholder="e.g. Delivery within 5-7 working days. Prices inclusive of GST."></textarea>
            </div>

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

<script>
const ITEMS = <?= json_encode($items) ?>;
const CGST_DEFAULT = <?= $cgstDefault ?>;
const SGST_DEFAULT = <?= $sgstDefault ?>;

function addLine() {
    const tbody = document.getElementById('lineItemsBody');
    const row = document.createElement('tr');
    row.innerHTML = `
        <td>
            <select name="item_id[]" class="item-select" onchange="onItemChange(this)" required>
                <option value="">-- Select Item --</option>
                ${ITEMS.map(i => `<option value="${i.id}" data-price="${i.sale_price}">${i.item_name} (${i.item_code})</option>`).join('')}
            </select>
        </td>
        <td><input type="number" name="qty[]" value="1" min="1" class="qty-input" oninput="recalcLine(this)" style="width:100%;min-width:80px;"></td>
        <td><input type="number" name="unit_price[]" step="0.01" value="0" class="price-input" oninput="recalcLine(this)" style="width:100%;min-width:110px;"></td>
        <td><input type="number" name="cgst[]" step="0.01" value="${CGST_DEFAULT}" class="cgst-input" oninput="recalcLine(this)" style="width:100%;min-width:70px;"></td>
        <td><input type="number" name="sgst[]" step="0.01" value="${SGST_DEFAULT}" class="sgst-input" oninput="recalcLine(this)" style="width:100%;min-width:70px;"></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 onItemChange(sel) {
    const opt = sel.options[sel.selectedIndex];
    const row = sel.closest('tr');
    row.querySelector('.price-input').value = opt.dataset.price || 0;
    recalcLine(sel);
}

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, cgstTotal = 0, sgstTotal = 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;
        cgstTotal += s * cgst/100;
        sgstTotal += s * sgst/100;
    });
    const beforeDiscount = subtotal + cgstTotal + sgstTotal;
    const discountPct = parseFloat(document.getElementById('discountPercent').value) || 0;
    const discountAmt = beforeDiscount * discountPct / 100;
    const grandTotal = beforeDiscount - discountAmt;

    document.getElementById('sumSubtotal').textContent = '₹' + subtotal.toFixed(2);
    document.getElementById('sumCgst').textContent = '₹' + cgstTotal.toFixed(2);
    document.getElementById('sumSgst').textContent = '₹' + sgstTotal.toFixed(2);
    document.getElementById('sumBeforeDiscount').textContent = '₹' + beforeDiscount.toFixed(2);
    document.getElementById('sumDiscount').textContent = '₹' + discountAmt.toFixed(2);
    document.getElementById('sumGrandTotal').textContent = '₹' + grandTotal.toFixed(2);
}

addLine();
</script>

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