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

$id = (int)($_GET['id'] ?? 0);
$action = $_GET['action'] ?? '';

// ── Helper: load quotation with customer ──────────────────────
function loadQuotation($pdo, $id) {
    $stmt = $pdo->prepare("SELECT q.*, c.customer_name, c.email, c.phone, c.billing_address, c.shipping_address, c.gst_number as customer_gst, c.city, c.state, c.pincode
                            FROM quotations q JOIN sale_vendors c ON c.id=q.customer_id WHERE q.id=?");
    $stmt->execute([$id]);
    return $stmt->fetch();
}

$q = loadQuotation($pdo, $id);
if (!$q) { setFlash('danger','Quotation not found.'); header('Location: quotations.php'); exit; }

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

    // Find the root quotation_id (original)
    $rootId = $q['parent_quotation_id'] ?: $q['id'];

    // Find max revision for this root
    $maxRev = $pdo->prepare("SELECT MAX(revision_no) FROM quotations WHERE id=? OR parent_quotation_id=?");
    $maxRev->execute([$rootId, $rootId]);
    $nextRev = ((int)$maxRev->fetchColumn()) + 1;

    $customerId      = $q['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'] ?? [];

    try {
        $pdo->beginTransaction();

        // Same quotation_no as original but append -R1, -R2 etc
        $baseNo = preg_replace('/-R\d+$/', '', $q['parent_quotation_id']
            ? (loadQuotation($pdo, $rootId)['quotation_no'] ?? $q['quotation_no'])
            : $q['quotation_no']);
        $newQNo = $baseNo . '-R' . $nextRev;

        $subtotal = 0; $cgstTotal = 0; $sgstTotal = 0; $lineData = [];
        foreach ($itemIds as $idx => $itemId) {
            $itemId = (int)$itemId;
            $qty = (int)($qtys[$idx] ?? 0);
            $price = (float)($prices[$idx] ?? 0);
            $cgstPct = (float)($cgsts[$idx] ?? 9);
            $sgstPct = (float)($sgsts[$idx] ?? 9);
            if ($itemId <= 0 || $qty <= 0) continue;
            $lineSubtotal = $qty * $price;
            $lineCgst = round($lineSubtotal * $cgstPct / 100, 2);
            $lineSgst = round($lineSubtotal * $sgstPct / 100, 2);
            $lineTotalBefore = $lineSubtotal + $lineCgst + $lineSgst;
            $subtotal += $lineSubtotal; $cgstTotal += $lineCgst; $sgstTotal += $lineSgst;
            $lineData[] = compact('itemId','qty','price','cgstPct','sgstPct','lineSubtotal','lineCgst','lineSgst','lineTotalBefore');
        }
        if (empty($lineData)) { $pdo->rollBack(); setFlash('danger','No valid items.'); header("Location: quotation_view.php?id=$id"); exit; }

        $totalBefore   = $subtotal + $cgstTotal + $sgstTotal;
        $discountAmt   = round($totalBefore * $discountPercent / 100, 2);
        $grandTotal    = $totalBefore - $discountAmt;

        foreach ($lineData as &$line) {
            $prop = $totalBefore > 0 ? $line['lineTotalBefore'] / $totalBefore : 0;
            $line['lineDiscountAmt']   = round($discountAmt * $prop, 2);
            $line['lineFinalAmount']   = $line['lineTotalBefore'] - $line['lineDiscountAmt'];
        } unset($line);

        $pdo->prepare("INSERT INTO quotations (quotation_no, parent_quotation_id, revision_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 (?,?,?,?,?,?,?,?,?,?,?,?,?,'draft',?,?)")
            ->execute([$newQNo, $rootId, $nextRev, $customerId, $quotationDate, $validUntil,
                       $subtotal, $cgstTotal, $sgstTotal, $totalBefore,
                       $discountPercent, $discountAmt, $grandTotal, $notes, currentUserId()]);
        $newId = $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([$newId,$line['itemId'],$line['qty'],$line['price'],$line['cgstPct'],$line['sgstPct'],$line['lineSubtotal'],$line['lineCgst'],$line['lineSgst'],$line['lineTotalBefore'],$line['lineDiscountAmt'],$line['lineFinalAmount']]);
        }

        $pdo->commit();
        setFlash('success', "Revised Quotation $newQNo (Rev $nextRev) created.");
        header("Location: quotation_view.php?id=$newId"); exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger','Error: '.$e->getMessage());
        header("Location: quotation_view.php?id=$id"); exit;
    }
}

// ── Status actions ────────────────────────────────────────────
if ($action === 'send_email') {
    if (empty($q['email'])) {
        setFlash('danger','No email on file. Share via WhatsApp and check Sent to Customer below.');
    } else {
        $result = Mailer::sendQuotation($id);
        setFlash($result['success']?'success':'danger', $result['success']?'Quotation emailed to '.$q['email']:'Email failed: '.$result['error']);
    }
    header("Location: quotation_view.php?id=$id"); exit;
}
if ($action === 'accept') {
    $pdo->prepare("UPDATE quotations SET status='accepted' WHERE id=?")->execute([$id]);
    setFlash('success','Quotation marked as Accepted.');
    header("Location: quotation_view.php?id=$id"); exit;
}
if ($action === 'reject') {
    $pdo->prepare("UPDATE quotations SET status='rejected' WHERE id=?")->execute([$id]);
    setFlash('success','Quotation marked as Rejected.');
    header("Location: quotation_view.php?id=$id"); exit;
}

// ── Sent to customer toggle ───────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'mark_sent_to_customer') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) { setFlash('danger','Invalid token.'); header("Location: quotation_view.php?id=$id"); exit; }
    $pdo->prepare("UPDATE quotations SET sent_to_customer=1, sent_to_customer_at=NOW(), status=IF(status='draft','sent',status) WHERE id=?")->execute([$id]);
    setFlash('success','Marked as sent. You can now create the Delivery Note.');
    header("Location: quotation_view.php?id=$id"); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'unmark_sent_to_customer') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) { setFlash('danger','Invalid token.'); header("Location: quotation_view.php?id=$id"); exit; }
    $pdo->prepare("UPDATE quotations SET sent_to_customer=0, sent_to_customer_at=NULL WHERE id=?")->execute([$id]);
    setFlash('success','Unmarked.'); header("Location: quotation_view.php?id=$id"); exit;
}

// ── Re-fetch ──────────────────────────────────────────────────
$q = loadQuotation($pdo, $id);

$stmt = $pdo->prepare("SELECT qi.*, i.item_name, i.item_code, i.hsn_code, i.unit FROM quotation_items qi JOIN items i ON i.id=qi.item_id WHERE qi.quotation_id=?");
$stmt->execute([$id]);
$lineItems = $stmt->fetchAll();

$qSubtotalFinal = 0; $qCgstFinal = 0; $qSgstFinal = 0;
foreach ($lineItems as $li) {
    $originalTotal = $li['line_total_before_discount'] ?: 0;
    $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
    $qSubtotalFinal += round($li['line_subtotal'] * $ratio, 2);
    $qCgstFinal     += round($li['line_cgst'] * $ratio, 2);
    $qSgstFinal     += round($li['line_sgst'] * $ratio, 2);
}

// ── Delivery Note for THIS quotation ────────────────────────
$stmt = $pdo->prepare("SELECT * FROM delivery_notes WHERE quotation_id=?");
$stmt->execute([$id]); $deliveryNote = $stmt->fetch();

// ── Invoice for this quotation ────────────────────────────────
$invoice = null;
if ($deliveryNote) {
    $stmt = $pdo->prepare("SELECT * FROM invoices WHERE delivery_note_id=?");
    $stmt->execute([$deliveryNote['id']]); $invoice = $stmt->fetch();
}

// ── All revisions for this quotation family ──────────────────
$rootId = $q['parent_quotation_id'] ?: $q['id'];
$stmt = $pdo->prepare("SELECT q.*, c.customer_name FROM quotations q JOIN sale_vendors c ON c.id=q.customer_id WHERE q.id=? OR q.parent_quotation_id=? ORDER BY q.revision_no ASC");
$stmt->execute([$rootId, $rootId]);
$allRevisions = $stmt->fetchAll();

// ── Items list for revision modal ────────────────────────────
$allItems = $pdo->query("SELECT * FROM items WHERE status=1 ORDER BY item_name")->fetchAll();

$companyName    = getSetting('company_name','Your Company');
$companyAddress = getSetting('company_address','');
$companyGst     = getSetting('company_gst','');
$companyPhone   = getSetting('company_phone','');
$companyEmail   = getSetting('company_email','');
$cgstDefault    = (float)getSetting('cgst_percent', 9);
$sgstDefault    = (float)getSetting('sgst_percent', 9);
$csrf = generateCSRFToken();

$pageTitle = 'Quotation';
require_once __DIR__ . '/../../includes/header.php';
?>

<!-- ══ PAGE HEADER ══════════════════════════════════════════════ -->
<div class="page-header no-print">
    <div>
        <div class="eyebrow">Quotation <?= $q['revision_no'] > 0 ? '<span class="badge badge-info">Rev '.$q['revision_no'].'</span>' : '' ?></div>
        <h2 class="mb-0"><?= sanitize($q['quotation_no']) ?></h2>
    </div>
    <div class="flex gap-8" style="flex-wrap:wrap;">
        <a href="quotations.php" class="btn"><?= icon('arrow-left') ?> Back</a>
        <a href="quotation_pdf.php?id=<?= $id ?>" class="btn" target="_blank"><?= icon('download') ?> Download PDF</a>

        <?php if (in_array($q['status'], ['draft','sent','rejected'])): ?>
        <button class="btn btn-secondary" onclick="document.getElementById('revisionModal').classList.add('show')"><?= icon('copy') ?> Create Revised Quotation</button>
        <?php endif; ?>

        <?php if ($q['email']): ?>
        <a href="?id=<?= $id ?>&action=send_email" class="btn btn-primary" onclick="return confirm('Send this quotation to <?= sanitize($q['email']) ?>?')">
            <?= icon('mail-forward') ?> <?= $q['email_sent'] ? 'Re-send Email' : 'Send Email' ?>
        </a>
        <?php endif; ?>

        <?php if (in_array($q['status'], ['sent','accepted'])): ?>
        <a href="?id=<?= $id ?>&action=accept" class="btn btn-success" onclick="return confirm('Mark as Accepted?')"><?= icon('thumb-up') ?> Accept</a>
        <a href="?id=<?= $id ?>&action=reject" class="btn btn-danger" onclick="return confirm('Mark as Rejected?')"><?= icon('thumb-down') ?> Reject</a>
        <?php endif; ?>

        <?php if ($deliveryNote): ?>
        <a href="../delivery/delivery_view.php?id=<?= $deliveryNote['id'] ?>" class="btn btn-accent"><?= icon('truck') ?> View Delivery Note</a>
        <?php endif; ?>
        <?php if ($invoice): ?>
        <a href="../invoice/invoice_view.php?id=<?= $invoice['id'] ?>" class="btn btn-accent"><?= icon('receipt') ?> View Invoice</a>
        <?php endif; ?>
    </div>
</div>

<?php if ($q['email_sent']): ?>
<div class="alert alert-info no-print"><?= icon('mail-forward') ?> Emailed to <?= sanitize($q['email']) ?> on <?= formatDateTime($q['email_sent_at']) ?></div>
<?php endif; ?>

<!-- ══ REVISION TABS ═══════════════════════════════════════════ -->
<?php if (count($allRevisions) > 1): ?>
<div class="card no-print" style="max-width:850px;margin:0 auto 12px;padding:12px 16px;">
    <div class="text-sm text-muted" style="margin-bottom:8px;font-weight:600;"><?= icon('versions') ?> Quotation Revisions</div>
    <div class="flex gap-8" style="flex-wrap:wrap;">
    <?php foreach ($allRevisions as $rev): ?>
        <a href="quotation_view.php?id=<?= $rev['id'] ?>"
           class="btn btn-sm <?= $rev['id'] == $id ? 'btn-primary' : 'btn-secondary' ?>"
           title="<?= sanitize($rev['quotation_no']) ?> — <?= formatMoney($rev['grand_total']) ?>">
            <?= $rev['revision_no'] == 0 ? 'Original' : 'Rev '.$rev['revision_no'] ?>
            <span class="badge badge-<?= $rev['status']=='accepted'?'success':($rev['status']=='rejected'?'danger':'muted') ?>" style="margin-left:4px;"><?= $rev['status'] ?></span>
        </a>
    <?php endforeach; ?>
    </div>
    <?php
    // Show delivery+invoice links for the accepted revision
    foreach ($allRevisions as $rev) {
        if ($rev['status'] === 'accepted') {
            $dn = $pdo->prepare("SELECT * FROM delivery_notes WHERE quotation_id=?");
            $dn->execute([$rev['id']]); $dn = $dn->fetch();
            if ($dn) {
                echo '<div class="divider" style="margin:10px 0;"></div>';
                echo '<div class="flex gap-8 align-center">';
                echo '<span class="text-sm text-muted">Accepted revision ('.sanitize($rev['quotation_no']).'):</span>';
                echo '<a href="../delivery/delivery_view.php?id='.$dn['id'].'" class="btn btn-sm btn-accent">'.icon('truck').' '.$dn['delivery_no'].'</a>';
                $inv2 = $pdo->prepare("SELECT * FROM invoices WHERE delivery_note_id=?");
                $inv2->execute([$dn['id']]); $inv2 = $inv2->fetch();
                if ($inv2) echo '<a href="../invoice/invoice_view.php?id='.$inv2['id'].'" class="btn btn-sm btn-accent">'.icon('receipt').' '.$inv2['invoice_no'].'</a>';
                echo '</div>';
            }
        }
    }
    ?>
</div>
<?php endif; ?>

<!-- ══ SENT TO CUSTOMER PANEL ══════════════════════════════════ -->
<div class="card no-print" style="max-width:850px;margin:0 auto 16px;border-color:<?= $q['sent_to_customer']?'var(--color-success)':'var(--color-border)' ?>;">
    <div class="flex-between" style="flex-wrap:wrap;gap:12px;">
        <form method="POST" id="sentToCustomerForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="<?= $q['sent_to_customer']?'unmark_sent_to_customer':'mark_sent_to_customer' ?>">
            <label class="flex gap-8" style="align-items:center;cursor:pointer;margin:0;">
                <input type="checkbox" <?= $q['sent_to_customer']?'checked':'' ?> onchange="document.getElementById('sentToCustomerForm').submit()" style="width:20px;height:20px;">
                <span style="font-weight:600;">Sent to Customer</span>
            </label>
        </form>
        <?php if ($q['sent_to_customer']): ?>
        <div class="text-sm text-muted">Confirmed on <?= formatDateTime($q['sent_to_customer_at']) ?></div>
        <?php endif; ?>
    </div>

    <?php if ($q['sent_to_customer'] && !$deliveryNote && $q['status']==='accepted'): ?>
    <div class="divider"></div>
    <div class="flex-between">
        <div class="text-sm text-muted">Customer accepted. Create Delivery Note to proceed.</div>
        <a href="../delivery/delivery_create.php?quotation_id=<?= $id ?>" class="btn btn-accent"><?= icon('truck') ?> Create Delivery Note</a>
    </div>
    <?php elseif ($q['sent_to_customer'] && $q['status'] !== 'accepted'): ?>
    <div class="divider"></div>
    <div class="text-sm text-faint">Waiting for customer acceptance. Use Accept/Reject buttons above.</div>
    <?php elseif (!$q['sent_to_customer']): ?>
    <div class="divider"></div>
    <div class="text-sm text-faint">Check this once the customer has received the quotation (email or WhatsApp).</div>
    <?php endif; ?>
</div>

<!-- ══ QUOTATION DOCUMENT (Customer View) ══════════════════════ -->
<div class="card" id="printArea" style="max-width:850px;margin:0 auto;">
    <div class="flex-between" style="align-items:flex-start;margin-bottom:24px;">
        <div>
            <h1 style="margin-bottom:4px;"><?= sanitize($companyName) ?></h1>
            <div class="text-sm text-muted"><?= nl2br(sanitize($companyAddress)) ?></div>
            <?php if ($companyGst): ?><div class="text-sm text-muted">GSTIN: <?= sanitize($companyGst) ?></div><?php endif; ?>
            <?php if ($companyPhone): ?><div class="text-sm text-muted">Phone: <?= sanitize($companyPhone) ?> | Email: <?= sanitize($companyEmail) ?></div><?php endif; ?>
        </div>
        <div class="text-right">
            <h2 style="margin-bottom:4px;">QUOTATION<?= $q['revision_no']>0?' (Rev '.$q['revision_no'].')':'' ?></h2>
            <div class="mono"><?= sanitize($q['quotation_no']) ?></div>
            <div class="text-sm text-muted">Date: <?= formatDate($q['quotation_date']) ?></div>
            <div class="text-sm text-muted">Valid Until: <?= formatDate($q['valid_until']) ?></div>
        </div>
    </div>

    <div class="divider"></div>

    <div class="form-grid" style="margin-bottom:16px;">
        <div>
            <div class="text-sm text-muted" style="font-weight:700;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;">To</div>
            <div style="font-weight:600;"><?= sanitize($q['customer_name']) ?></div>
            <div class="text-sm"><?= nl2br(sanitize($q['shipping_address'] ?: $q['billing_address'])) ?></div>
            <div class="text-sm"><?= sanitize($q['city']) ?><?= $q['city']&&$q['state']?', ':'' ?><?= sanitize($q['state']) ?> <?= sanitize($q['pincode']) ?></div>
            <?php if ($q['customer_gst']): ?><div class="text-sm">GSTIN: <?= sanitize($q['customer_gst']) ?></div><?php endif; ?>
            <div class="text-sm">Phone: <?= sanitize($q['phone']) ?></div>
        </div>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th style="width:36px">#</th>
                    <th>Item Description</th>
                    <th>HSN</th>
                    <th class="text-right">Qty</th>
                    <th class="text-right">Unit</th>
                    <th class="text-right">Rate</th>
                    <th class="text-right">CGST</th>
                    <th class="text-right">SGST</th>
                    <th class="text-right">Amount</th>
                </tr>
            </thead>
            <tbody>
            <?php $sno=1; foreach ($lineItems as $li):
                $originalTotal = $li['line_total_before_discount'] ?: 0;
                $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
                $finalBase = round($li['line_subtotal'] * $ratio, 2);
                $finalCgst = round($li['line_cgst'] * $ratio, 2);
                $finalSgst = round($li['line_sgst'] * $ratio, 2);
                $effectiveRate = $li['qty'] > 0 ? $finalBase / $li['qty'] : 0;
            ?>
                <tr>
                    <td><?= $sno++ ?></td>
                    <td><?= sanitize($li['item_name']) ?></td>
                    <td class="mono"><?= sanitize($li['hsn_code']) ?: '-' ?></td>
                    <td class="num"><?= $li['qty'] ?></td>
                    <td class="num"><?= sanitize($li['unit']) ?></td>
                    <td class="num mono"><?= formatMoney($effectiveRate) ?></td>
                    <td class="num mono"><?= formatMoney($finalCgst) ?> <span class="text-faint">(<?= number_format($li['cgst_percent'],1) ?>%)</span></td>
                    <td class="num mono"><?= formatMoney($finalSgst) ?> <span class="text-faint">(<?= number_format($li['sgst_percent'],1) ?>%)</span></td>
                    <td class="num mono"><strong><?= formatMoney($li['line_final_amount']) ?></strong></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <div class="flex-end mt-16">
        <div style="width:280px;">
            <div class="flex-between" style="padding:4px 0;"><span class="text-sm text-muted">Subtotal</span><strong class="mono"><?= formatMoney($qSubtotalFinal) ?></strong></div>
            <div class="flex-between" style="padding:4px 0;"><span class="text-sm text-muted">CGST</span><strong class="mono"><?= formatMoney($qCgstFinal) ?></strong></div>
            <div class="flex-between" style="padding:4px 0;"><span class="text-sm text-muted">SGST</span><strong class="mono"><?= formatMoney($qSgstFinal) ?></strong></div>
            <div class="divider" style="margin:8px 0;"></div>
            <div class="flex-between" style="padding:4px 0;">
                <span style="font-weight:700;font-size:15px;">Grand Total</span>
                <strong class="mono" style="font-size:18px;color:var(--color-primary);"><?= formatMoney($q['grand_total']) ?></strong>
            </div>
        </div>
    </div>

    <?php if ($q['notes']): ?>
    <div class="divider"></div>
    <div><strong class="text-sm">Terms & Notes:</strong><div class="text-sm text-muted"><?= nl2br(sanitize($q['notes'])) ?></div></div>
    <?php endif; ?>
    <div class="divider"></div>
    <div class="text-sm text-faint">This is a system-generated quotation. Prices are inclusive of applicable taxes.</div>
</div>

<!-- ══ INTERNAL DETAILS ════════════════════════════════════════ -->
<div class="card no-print" style="max-width:850px;margin:20px auto 0;border-color:var(--color-accent);">
    <div class="card-title" style="color:var(--color-accent-dk);"><?= icon('lock') ?> Internal Details (Not shown to customer)</div>
    <div class="form-grid">
        <div><div class="text-sm text-muted">Total before discount</div><div class="mono" style="font-size:16px;"><?= formatMoney($q['total_before_discount']) ?></div></div>
        <div><div class="text-sm text-muted">Discount %</div><div class="mono" style="font-size:16px;"><?= number_format($q['discount_percent'],2) ?>%</div></div>
        <div><div class="text-sm text-muted">Discount amount</div><div class="mono" style="font-size:16px;color:var(--color-accent-dk);">- <?= formatMoney($q['discount_amount']) ?></div></div>
        <div><div class="text-sm text-muted">Final (customer)</div><div class="mono" style="font-size:16px;font-weight:700;"><?= formatMoney($q['grand_total']) ?></div></div>
    </div>
</div>

<!-- ══ REVISED QUOTATION MODAL ═════════════════════════════════ -->
<div class="modal-backdrop" id="revisionModal">
    <div class="modal modal-lg">
        <div class="modal-header">
            <h2><?= icon('copy') ?> Create Revised Quotation</h2>
            <button class="btn btn-icon" onclick="document.getElementById('revisionModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <div class="alert alert-info" style="margin:12px 16px 0;">
            <?= icon('info-circle') ?> This creates a new revision of <strong><?= sanitize($q['quotation_no']) ?></strong>. You can change items, qty, rate, or add/remove lines.
        </div>
        <form method="POST" id="revisionForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="create_revision">

            <div class="form-grid" style="padding:16px;">
                <div class="form-group">
                    <label>Quotation Date</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 style="margin:0 16px;">
                <legend>Items (pre-filled from current quotation — edit as needed)</legend>
                <div class="table-wrap">
                    <table id="revLineTable">
                        <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="revLineBody">
                        <?php foreach ($lineItems as $li):
                            $originalTotal = $li['line_total_before_discount'] ?: 0;
                            $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
                            $finalBase = round($li['line_subtotal'] * $ratio, 2);
                            $effectiveRate = $li['qty'] > 0 ? $finalBase / $li['qty'] : $li['unit_price'];
                        ?>
                        <tr>
                            <td>
                                <select name="item_id[]" class="rev-item-select" onchange="revOnItemChange(this)" required>
                                    <option value="">-- Select --</option>
                                    <?php foreach ($allItems as $ai): ?>
                                    <option value="<?= $ai['id'] ?>" data-price="<?= $ai['sale_price'] ?>" <?= $ai['id']==$li['item_id']?'selected':'' ?>><?= sanitize($ai['item_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td><input type="number" name="qty[]" value="<?= $li['qty'] ?>" min="1" class="rev-qty" oninput="revRecalcLine(this)" style="width:100%;min-width:80px;"></td>
                            <td><input type="number" name="unit_price[]" step="0.01" value="<?= number_format($effectiveRate,2,'.','') ?>" class="rev-price" oninput="revRecalcLine(this)" style="width:100%;min-width:110px;"></td>
                            <td><input type="number" name="cgst[]" step="0.01" value="<?= $li['cgst_percent'] ?>" class="rev-cgst" oninput="revRecalcLine(this)" style="width:100%;min-width:70px;"></td>
                            <td><input type="number" name="sgst[]" step="0.01" value="<?= $li['sgst_percent'] ?>" class="rev-sgst" oninput="revRecalcLine(this)" style="width:100%;min-width:70px;"></td>
                            <td class="num rev-line-total mono">₹0.00</td>
                            <td><button type="button" class="btn btn-icon btn-sm" onclick="revRemoveLine(this)"><?= icon('trash') ?></button></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <button type="button" class="btn btn-sm mt-8" onclick="revAddLine()"><?= icon('plus') ?> Add Item</button>
            </fieldset>

            <div class="form-grid" style="padding:16px;">
                <div class="form-group">
                    <label>Discount % (internal)</label>
                    <input type="number" step="0.01" name="discount_percent" id="revDiscountPct" value="<?= $q['discount_percent'] ?>" min="0" max="100" oninput="revRecalcTotals()">
                </div>
                <div style="background:var(--color-surface-2);border-radius:var(--radius-md);padding:12px;">
                    <div class="flex-between" style="margin-bottom:4px;"><span class="text-sm text-muted">Before Discount</span><strong class="mono" id="revSumBefore">₹0.00</strong></div>
                    <div class="flex-between" style="margin-bottom:4px;color:var(--color-accent-dk);"><span class="text-sm">Discount</span><strong class="mono" id="revSumDiscount">₹0.00</strong></div>
                    <div class="divider" style="margin:6px 0;"></div>
                    <div class="flex-between"><span style="font-weight:700;">Grand Total</span><strong class="mono" id="revGrandTotal" style="font-size:16px;color:var(--color-primary);">₹0.00</strong></div>
                </div>
            </div>

            <div class="form-group" style="padding:0 16px;">
                <label>Notes</label>
                <textarea name="notes" rows="2"><?= sanitize($q['notes']) ?></textarea>
            </div>

            <div class="flex-end gap-8" style="padding:16px;">
                <button type="button" class="btn" onclick="document.getElementById('revisionModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('copy') ?> Save Revised Quotation</button>
            </div>
        </form>
    </div>
</div>

<script>
const REV_ITEMS = <?= json_encode($allItems) ?>;
const REV_CGST_DEFAULT = <?= $cgstDefault ?>;
const REV_SGST_DEFAULT = <?= $sgstDefault ?>;

function revAddLine() {
    const tbody = document.getElementById('revLineBody');
    const row = document.createElement('tr');
    row.innerHTML = `
        <td><select name="item_id[]" class="rev-item-select" onchange="revOnItemChange(this)" required>
            <option value="">-- Select --</option>
            ${REV_ITEMS.map(i=>`<option value="${i.id}" data-price="${i.sale_price}">${i.item_name}</option>`).join('')}
        </select></td>
        <td><input type="number" name="qty[]" value="1" min="1" class="rev-qty" oninput="revRecalcLine(this)" style="width:100%;min-width:80px;"></td>
        <td><input type="number" name="unit_price[]" step="0.01" value="0" class="rev-price" oninput="revRecalcLine(this)" style="width:100%;min-width:110px;"></td>
        <td><input type="number" name="cgst[]" step="0.01" value="${REV_CGST_DEFAULT}" class="rev-cgst" oninput="revRecalcLine(this)" style="width:100%;min-width:70px;"></td>
        <td><input type="number" name="sgst[]" step="0.01" value="${REV_SGST_DEFAULT}" class="rev-sgst" oninput="revRecalcLine(this)" style="width:100%;min-width:70px;"></td>
        <td class="num rev-line-total mono">₹0.00</td>
        <td><button type="button" class="btn btn-icon btn-sm" onclick="revRemoveLine(this)"><?= icon('trash') ?></button></td>`;
    tbody.appendChild(row);
}
function revOnItemChange(sel) {
    const opt = sel.options[sel.selectedIndex];
    const row = sel.closest('tr');
    row.querySelector('.rev-price').value = parseFloat(opt.dataset.price||0).toFixed(2);
    revRecalcLine(sel);
}
function revRemoveLine(btn) { btn.closest('tr').remove(); revRecalcTotals(); }
function revRecalcLine(el) {
    const row = el.closest('tr');
    const qty = parseFloat(row.querySelector('.rev-qty').value)||0;
    const price = parseFloat(row.querySelector('.rev-price').value)||0;
    const cgst = parseFloat(row.querySelector('.rev-cgst').value)||0;
    const sgst = parseFloat(row.querySelector('.rev-sgst').value)||0;
    const s = qty*price;
    row.querySelector('.rev-line-total').textContent = '₹'+(s+s*cgst/100+s*sgst/100).toFixed(2);
    revRecalcTotals();
}
function revRecalcTotals() {
    let sub=0,cg=0,sg=0;
    document.querySelectorAll('#revLineBody tr').forEach(r=>{
        const qty=parseFloat(r.querySelector('.rev-qty')?.value)||0;
        const price=parseFloat(r.querySelector('.rev-price')?.value)||0;
        const cgst=parseFloat(r.querySelector('.rev-cgst')?.value)||0;
        const sgst=parseFloat(r.querySelector('.rev-sgst')?.value)||0;
        sub+=qty*price; cg+=qty*price*cgst/100; sg+=qty*price*sgst/100;
    });
    const before=sub+cg+sg;
    const disc=before*(parseFloat(document.getElementById('revDiscountPct').value)||0)/100;
    document.getElementById('revSumBefore').textContent='₹'+before.toFixed(2);
    document.getElementById('revSumDiscount').textContent='₹'+disc.toFixed(2);
    document.getElementById('revGrandTotal').textContent='₹'+(before-disc).toFixed(2);
}
// Init totals on load
document.querySelectorAll('#revLineBody tr').forEach(r=>{ const inp=r.querySelector('.rev-qty'); if(inp) revRecalcLine(inp); });
</script>

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