<?php
session_start();
require_once("../config/config.php");

// Allowed roles
$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$success = "";
$error = "";
$project_id= $_GET['project_id'];

// Generate GRN Code

function generateGRNCode(mysqli $conn): string {
    $sql = "SELECT grn_code FROM goods_received_note ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['grn_code'], 4) + 1;
    }
    return sprintf("GRN-%03d", $next);
}
$generated_code = generateGRNCode($conn);

// Fetch required data
$projects = $conn->query("SELECT id, project_code, project_name FROM project_master WHERE project_status IN ('Active', 'In Progress') AND id = $project_id  ORDER BY project_name ASC");
$items_result = $conn->query("SELECT id, name, uom, model_no FROM inventory_master ORDER BY name ASC");
$vendors_result = $conn->query("SELECT vendor_name FROM vendor_master ORDER BY vendor_name ASC");

// Fetch Issued Delivery Challans
$dcs = $conn->query("
    SELECT dc.id, dc.dc_code, dc.dc_date, dc.receiver_name, p.project_name 
    FROM delivery_challan dc
    LEFT JOIN project_master p ON dc.project_id = p.id
    WHERE dc.status = 'Issued' AND dc.project_id = $project_id
    ORDER BY dc.dc_date DESC
");

// Handle Form Submission - Proper data insertion
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    
    $grn_date   = $_POST['grn_date'] ?? date('Y-m-d');
    $vendor     = trim($_POST['vendor'] ?? '');
    $project_id = !empty($_POST['project_id']) ? (int)$_POST['project_id'] : null;
    $invoice_no = trim($_POST['invoice_no'] ?? '');
    $remarks    = trim($_POST['remarks'] ?? '');

    $serial_nos = $_POST['serial_no'] ?? [];
    $item_ids   = $_POST['item_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $rates      = $_POST['rate'] ?? [];
    $batches    = $_POST['batch'] ?? [];

    if (empty($grn_date)) {
        $error = "GRN Date is required.";
    } elseif (empty($vendor)) {
        $error = "Vendor is required.";
    } elseif (empty($item_ids) || count(array_filter($quantities, fn($q) => (float)$q > 0)) === 0) {
        $error = "Please add at least one item with received quantity > 0.";
    } else {
        try {
            $conn->begin_transaction();

            // Insert GRN Header
            $grn_sql = "INSERT INTO goods_received_note 
                (grn_code,grn_date, vendor, invoice_number, project_id, remarks, status, received_by, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, 'Received', ?, NOW())";

            $grn_stmt = $conn->prepare($grn_sql);
            $grn_stmt->bind_param("sssissi",$generated_code, $grn_date, $vendor, $invoice_no, $project_id, $remarks, $user_id);
            $grn_stmt->execute();
            $grn_id = $conn->insert_id;

            // Insert GRN Items
            $item_sql = "INSERT INTO goods_received_note_items 
                (grn_id, item_id, serial_number, received_qty, rate, batch_no, unit) 
                VALUES (?, ?, ?, ?, ?, ?, ?)";

            $item_stmt = $conn->prepare($item_sql);

            // Project Inventory Update (if project selected)
            $stock_stmt = null;
            if ($project_id > 0) {
                $stock_sql = "INSERT INTO project_inventory (project_id, item_id, current_stock, avg_rate, last_updated)
                    VALUES (?, ?, ?, ?, NOW())
                    ON DUPLICATE KEY UPDATE 
                        current_stock = current_stock + VALUES(current_stock),
                        avg_rate = (current_stock * avg_rate + VALUES(current_stock) * VALUES(avg_rate)) / (current_stock + VALUES(current_stock)),
                        last_updated = NOW()";
                $stock_stmt = $conn->prepare($stock_sql);
            }

            foreach ($item_ids as $idx => $item_id) {

    $qty   = (float)($quantities[$idx] ?? 0);
    $rate  = (float)($rates[$idx] ?? 0);
    $batch = trim($batches[$idx] ?? '');
    $serial_input = trim($serial_nos[$idx] ?? '');
    $serial_list = array_filter(array_map('trim', explode(',', $serial_input)));

// ✅ VALIDATION
if (!empty($serial_list) && count($serial_list) != $qty) {
    throw new Exception("Serial count must match quantity for item ID: " . $item_id);
}
    if ($qty > 0 && $item_id > 0) {

        // Get UOM
        $unit_q = $conn->prepare("SELECT uom FROM inventory_master WHERE id = ?");
        $unit_q->bind_param("i", $item_id);
        $unit_q->execute();
        $unit_result = $unit_q->get_result();
        $unit = ($unit_result && $unit_result->num_rows > 0)
            ? $unit_result->fetch_assoc()['uom']
            : 'NOS';
        $unit_q->close();

        // 👉 Split serials (comma separated)
        $serial_list = array_filter(array_map('trim', explode(',', $serial_input)));

        
        // =========================
        // CASE 1: SERIAL ITEMS
        // =========================
        if (!empty($serial_list)) {
            
            foreach ($serial_list as $serial_no) {
                $qty_single = 1;
                // Insert GRN item (1 qty per serial)
                $item_stmt->bind_param(
                    "iiidids",
                    $grn_id,
                    $item_id,
                    $serial_no,
                    $qty_single,
                    $rate,
                    $batch,
                    $unit
                );
                $item_stmt->execute();

                // Update project stock (+1 each)
                if ($project_id > 0 && $stock_stmt) {
                    $stock_stmt->bind_param("iidd", $project_id, $item_id, $qty_single, $rate);
                    $stock_stmt->execute();
                         // 🔧 FIX: Get the project_inventory_id after update
                    $get_pi_id = $conn->prepare("
                        SELECT id FROM project_inventory 
                        WHERE project_id = ? AND item_id = ?
                        ");
                        $get_pi_id->bind_param("ii", $project_id, $item_id);
                        $get_pi_id->execute();
                        $pi_result = $get_pi_id->get_result();
                        if ($pi_row = $pi_result->fetch_assoc()) {
                        $project_inventory_id = $pi_row['id'];
                        }
                        $get_pi_id->close();
                }

                // 👉 Insert serial tracking
                if ($project_id > 0) {
                    $serial_stmt = $conn->prepare("
                        INSERT INTO project_inventory_serials 
                        (project_inventory_id, project_id, item_id, serial_no, grn_id, status)
                        VALUES (?, ?, ?, ?, ?, 'IN')
                    ");
                    $serial_stmt->bind_param("iiisi",$project_inventory_id, $project_id, $item_id, $serial_no, $grn_id);
                    $serial_stmt->execute();
                }
            }

        } 
        // =========================
        // CASE 2: NON-SERIAL ITEMS
        // =========================
        else {

            // Insert GRN item normally
            $item_stmt->bind_param(
                "iiidids",
                $grn_id,
                $item_id,
                '',
                $qty,
                $rate,
                $batch,
                $unit
            );
            $item_stmt->execute();

            // Update stock normally
            if ($project_id > 0 && $stock_stmt) {
                $stock_stmt->bind_param("iidd", $project_id, $item_id, $qty, $rate);
                $stock_stmt->execute();
            }
        }
    }
}
            // UPDATE DC STATUS (ADD HERE)
// =========================
$selected_dcs = $_POST['selected_dcs'] ?? [];

if (!empty($selected_dcs)) {

    $dc_update_stmt = $conn->prepare("
        UPDATE delivery_challan 
        SET status = 'Delivered' 
        WHERE id = ?
    ");

    foreach ($selected_dcs as $dc_id) {
        $dc_id = (int)$dc_id;
        $dc_update_stmt->bind_param("i", $dc_id);
        $dc_update_stmt->execute();
    }
}


            $conn->commit();
            $success = "Goods Received Note created successfully!<br><strong>" . $generated_code . "</strong>";

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to create GRN: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Goods Received Note</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
    :root {
        --primary: #a855f7;
        --accent: #c084fc;
        --glass: rgba(255, 255, 255, 0.10);
        --glass-border: rgba(255, 255, 255, 0.20);
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', system-ui, sans-serif;
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.78), rgba(0, 0, 0, 0.92)),
            url('../background.jpeg') center/cover fixed;
        color: #f1f5f9;
        padding: 20px 15px;
        min-height: 100vh;
    }

    .container {
        max-width: 1350px;
        margin: auto;
    }

    .glass-container {
        background: var(--glass);
        backdrop-filter: blur(24px);
        border-radius: 32px;
        border: 1px solid var(--glass-border);
        box-shadow: 0 25px 80px rgba(0, 0, 0, 0.65);
        overflow: hidden;
    }

    .header {
        background: linear-gradient(90deg, rgba(168, 85, 247, 0.35), rgba(147, 51, 234, 0.25));
        padding: 50px 40px;
        text-align: center;
        position: relative;
    }

    .header h1 {
        font-size: clamp(28px, 5vw, 42px);
        font-weight: 700;
    }

    .form-area {
        padding: 45px 40px;
    }

    .form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 20px;
        margin-bottom: 25px;
    }

    label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #e0e7ff;
    }

    .required {
        color: #f87171;
    }

    input,
    select,
    textarea {
        width: 100%;
        padding: 14px 18px;
        background: rgba(255, 255, 255, 0.09);
        border: 1px solid rgba(255, 255, 255, 0.25);
        border-radius: 16px;
        color: white;
        font-size: 16px;
    }

    .checkbox-input {
        width: auto;
        margin-right: 8px;
    }

    input:focus,
    select:focus,
    textarea:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 4px rgba(168, 85, 247, 0.25);
    }

    .dc-section {
        background: rgba(255, 255, 255, 0.06);
        border: 1px solid var(--glass-border);
        border-radius: 20px;
        padding: 25px;
        margin: 35px 0;
    }

    .dc-list {
        max-height: 340px;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .dc-item {
        background: rgba(255, 255, 255, 0.08);
        padding: 14px 18px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .items-table {
        width: 100%;
        margin: 35px 0;
        border-collapse: collapse;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 16px;
        overflow: hidden;
    }

    .items-table th {
        background: rgba(168, 85, 247, 0.3);
        padding: 16px 12px;
        text-align: left;
        font-weight: 600;
    }

    .items-table td {
        padding: 14px 12px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }

    .remove-row {
        color: #f87171;
        font-size: 1.6rem;
        cursor: pointer;
    }

    .add-row-btn {
        background: linear-gradient(135deg, #22c55e, #86efac);
        color: #052e16;
        border: none;
        padding: 14px 32px;
        border-radius: 16px;
        font-weight: 700;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }

    .submit-btn {
        width: 100%;
        padding: 18px;
        background: linear-gradient(135deg, var(--primary), var(--accent));
        color: white;
        border: none;
        border-radius: 16px;
        font-size: 1.2rem;
        font-weight: 700;
        cursor: pointer;
        margin-top: 25px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
    }

    .grand-total {
        font-size: 1.8rem;
        font-weight: 700;
        text-align: right;
        margin: 30px 0;
        color: #ddd6fe;
    }

    .message {
        padding: 16px 24px;
        border-radius: 16px;
        margin-bottom: 25px;
        font-weight: 600;
    }

    .success {
        background: rgba(34, 197, 94, 0.25);
        border: 1px solid #4ade80;
        color: #86efac;
    }

    .error {
        background: rgba(239, 68, 68, 0.25);
        border: 1px solid #f87171;
        color: #fca5a5;
    }

    @media (max-width: 768px) {
        .glass-container {
            border-radius: 24px;
        }

        .header,
        .form-area {
            padding: 35px 25px;
        }

        .dc-list {
            max-height: 260px;
        }
    }
    .suggestions {
        position: absolute;
        z-index: 1000;
        background: #1f2937;
        border: 1px solid var(--primary);
        border-radius: 12px;
        max-height: 280px;
        overflow-y: auto;
        width: 100%;
        margin-top: 4px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.6);
    }

    .suggestion-item {
        padding: 12px 16px;
        cursor: pointer;
    }

    .suggestion-item:hover {
        background: rgba(168, 85, 247, 0.3);
    }
    </style>
</head>

<body>

    <?php include '../config/header.php'; ?>

    <div class="container">
        <div class="glass-container">

            <div class="header">
                <a href="grn_list.php"
                    style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                    ← Back to GRN List
                </a>
                <h1><i class="fas fa-truck"></i> Create Goods Received Note</h1>
                <p style="margin-top:12px; opacity:0.9;">Record incoming materials</p>
            </div>

            <div class="form-area">
                <?php if ($success): ?>
                <div class="message success"><?= $success ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                <div class="message error"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>

                <form method="post">

                    <div class="form-grid">
                        <div class="form-group">
                            <label>GRN Code</label>
                            <input type="text" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                        </div>
                        <div class="form-group">
                            <label>GRN Date <span class="required">*</span></label>
                            <input type="date" name="grn_date" value="<?= date('Y-m-d') ?>" required>
                        </div>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label>Vendor / Supplier <span class="required">*</span></label>
                            <select name="vendor" required>
                                <option value="">-- Select Vendor --</option>
                                <?php while ($v = $vendors_result->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($v['vendor_name']) ?>">
                                    <?= htmlspecialchars($v['vendor_name']) ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Receive For Project</label>
                            <select name="project_id">
                                <!-- <option value="">Central Stock</option> -->
                                <?php while ($proj = $projects->fetch_assoc()): ?>
                                <option value="<?= $proj['id'] ?>">
                                    <?= htmlspecialchars($proj['project_code']) ?> -
                                    <?= htmlspecialchars($proj['project_name']) ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Supplier Invoice / DC Number</label>
                        <input type="text" name="invoice_no" placeholder="INV-12345 or DC-98765">
                    </div>

                    <!-- Delivery Challan Section -->
                    <div class="dc-section">
                        <h3 style="margin-bottom:18px;">Load from Delivery Challans</h3>
                        <div class="dc-list">
                            <?php if ($dcs->num_rows > 0): ?>
                            <?php while ($dc = $dcs->fetch_assoc()): ?>
                            <div class="dc-item">
                                <input type="checkbox" name="selected_dcs[]" class="checkbox-input"
                                    value="<?= $dc['id']?>" id="dc_<?= $dc['id'] ?>">
                                <label for="dc_<?= $dc['id'] ?>" style="cursor:pointer; flex:1;">
                                    <strong><?= htmlspecialchars($dc['dc_code'] ?? 'DC-'.$dc['id']) ?></strong>
                                    • <?= date('d M Y', strtotime($dc['dc_date'])) ?>
                                    • <?= htmlspecialchars($dc['receiver_name']) ?>
                                </label>
                            </div>
                            <?php endwhile; ?>
                            <?php else: ?>
                            <p style="opacity:0.7;">No Issued Delivery Challans available.</p>
                            <?php endif; ?>
                        </div>
                        <button type="button" onclick="loadSelectedDCs()" style="margin-top:20px;" class="add-row-btn">
                            <i class="fas fa-download"></i> Load Selected DC Items
                        </button>
                    </div>

                    <h3 style="margin:40px 0 15px; color:#ddd6fe;">Received Items</h3>

                    <table class="items-table" id="itemsTable">
                        <thead>
                            <tr>
                                <th>Model No</th>
                                <th>Serial No</th>
                                <th>Item Name</th>
                                <th>Received Qty <span class="required">*</span></th>
                                <th>Rate (₹)</th>
                                <th>Batch / Lot</th>
                                <th>UOM</th>
                                <th>Amount (₹)</th>
                                <th style="width:60px;"></th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody"></tbody>
                    </table>

                    <button type="button" class="add-row-btn" onclick="addItemRow()">
                        <i class="fas fa-plus"></i> Add Item Manually
                    </button>

                    <div class="grand-total">
                        Grand Total: <span id="grandTotal">₹ 0.00</span>
                    </div>

                    <div class="form-group">
                        <label>Remarks / Notes</label>
                        <textarea name="remarks" rows="3"
                            placeholder="Any observations, condition of goods, shortages, etc."></textarea>
                    </div>

                    <button type="submit" class="submit-btn">
                        <i class="fas fa-truck-loading"></i> Save GRN
                    </button>
                </form>
            </div>
        </div>
    </div>
    <script>
    // Add initial empty row
    document.addEventListener('DOMContentLoaded', () => addItemRow());

    function addItemRow() {
        const tbody = document.getElementById('itemsBody');
        const row = tbody.insertRow();

        row.innerHTML = `
        <td>
            <input type="text" name="model_no[]" placeholder="Type Model No" onkeyup="searchByModel(this)" style="width:100%;">
            <div class="suggestions" style="display:none;"></div>
        </td>
        <td>
            <input type="text" name="serial_no[]" placeholder="Type Serial No" style="width:100%;">
            
            
        </td>
        <td>
            <select name="item_id[]" class="item-select" onchange="updateUnit(this)" required>
                <option value="">Select Item</option>
                <?php 
                $items_result->data_seek(0);
                while ($item = $items_result->fetch_assoc()): ?>
                    <option value="<?= $item['id'] ?>" data-unit="<?= htmlspecialchars($item['uom']) ?>">
                        <?= htmlspecialchars($item['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </td>
        <td><input type="number" name="quantity[]" step="0.001" min="0.001" placeholder="0" required oninput="calculateLineTotal(this)"></td>
        <td><input type="number" name="rate[]" step="0.01" min="0" placeholder="0.00" oninput="calculateLineTotal(this)"></td>
        <td><input type="text" name="batch[]" placeholder="Batch/Lot"></td>
        <td class="unit-cell">—</td>
        <td class="line-total">₹ 0.00</td>
        <td><span class="remove-row" onclick="removeRow(this)"><i class="fas fa-trash"></i></span></td>
    `;
    }

    async function loadSelectedDCs() {
        const checked = document.querySelectorAll('input[name="selected_dcs[]"]:checked');
        const dcIds = Array.from(checked).map(cb => parseInt(cb.value));

        if (dcIds.length === 0) {
            alert("Please select at least one Delivery Challan.");
            return;
        }

        // Clear existing rows
        document.getElementById('itemsBody').innerHTML = '';

        try {
            const response = await fetch('get_dc_items.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    dc_ids: dcIds
                })
            });

            const text = await response.text();
            console.log("=== RAW SERVER RESPONSE ===");
            console.log(text);
            console.log("===========================");

            const data = JSON.parse(text);

            if (data.success && data.items && data.items.length > 0) {
                data.items.forEach(item => {
                    const row = document.getElementById('itemsBody').insertRow();

                    row.innerHTML = `
                    <td style="position:relative;">
                        <input type="text" name="model_no[]" value="${item.model_no || ''}" 
                               onkeyup="searchByModel(this)" style="width:100%;">
                        <div class="suggestions" style="display:none;"></div>
                    </td>
                    <td><input type="text" name="serial_no[]" value="${item.serial_number || ''}" style="width:100%;"></td>
                    <td>
                        <select name="item_id[]" onchange="updateUnit(this)" required>
                            <option value="${item.item_id}" selected data-unit="${item.uom || 'NOS'}">
                                ${item.name || 'Loaded Item'}
                            </option>
                        </select>
                    </td>
                    <td>
                        <input type="number" name="quantity[]" step="0.001" min="0.001" 
                               value="${parseFloat(item.pending_qty || item.dc_quantity || 1)}" 
                               required oninput="calculateLineTotal(this)">
                    </td>
                    <td>
                        <input type="number" name="rate[]" step="0.01" min="0" 
                               value="${parseFloat(item.rate || 0)}" 
                               oninput="calculateLineTotal(this)">
                    </td>
                    <td><input type="text" name="batch[]" placeholder="Batch/Lot"></td>
                    <td class="unit-cell">${item.uom || '—'}</td>
                    <td class="line-total">₹ 0.00</td>
                    <td><span class="remove-row" onclick="removeRow(this)"><i class="fas fa-trash"></i></span></td>
                `;

                    // Force update UOM and line total
                    const selectEl = row.querySelector('select[name="item_id[]"]');
                    if (selectEl) {
                        updateUnit(selectEl); // This will set UOM cell
                    }
                    calculateLineTotal(row.querySelector('input[name="quantity[]"]'));
                });

                updateGrandTotal();
                alert(`✅ Loaded ${data.items.length} item(s) successfully!`);
            } else {
                alert(data.message || "No pending items found in the selected Delivery Challans.");
            }
        } catch (err) {
            console.error("Load Error:", err);
            alert("Failed to load items.\n\nCheck F12 → Console and copy the RAW SERVER RESPONSE");
        }
    }
    // Existing JS functions (searchByModel, selectModelItem, updateUnit, calculateLineTotal, removeRow, updateGrandTotal)
    function searchByModel(input) {
        const model = input.value.trim();
        const row = input.closest('tr');
        const suggestionsDiv = row.querySelector('.suggestions');

        // if (model.length < 2) {
        //     suggestionsDiv.style.display = 'none';
        //     return;
        // }

        fetch(`search_by_model.php?model=${encodeURIComponent(model)}`)
            .then(r => r.json())
            .then(data => {
                suggestionsDiv.innerHTML = '';
                if (data.success && data.items.length > 0) {
                    data.items.forEach(item => {
                        const div = document.createElement('div');
                        div.className = 'suggestion-item';
                        div.innerHTML = `<strong>${item.model_no}</strong> — ${item.name}`;
                        div.onclick = () => {
                            selectModelItem(row, item);
                            suggestionsDiv.style.display = 'none';
                        };
                        suggestionsDiv.appendChild(div);
                    });
                    suggestionsDiv.style.display = 'block';
                } else {
                    suggestionsDiv.style.display = 'none';
                }
            });
    }

    function selectModelItem(row, item) {
        row.querySelector('input[name="model_no[]"]').value = item.model_no || '';
        const select = row.querySelector('select[name="item_id[]"]');
        select.value = item.id;
        select.dispatchEvent(new Event('change'));
        calculateLineTotal(row.querySelector('input[name="quantity[]"]'));
    }

    function updateUnit(select) {
        const row = select.closest('tr');
        const unitCell = row.querySelector('.unit-cell');
        const option = select.options[select.selectedIndex];
        unitCell.textContent = option.dataset.unit || '—';
        calculateLineTotal(select);
    }

    function calculateLineTotal(input) {
        const row = input.closest('tr');
        const qty = parseFloat(row.querySelector('input[name="quantity[]"]').value) || 0;
        const rate = parseFloat(row.querySelector('input[name="rate[]"]').value) || 0;
        row.querySelector('.line-total').textContent = `₹ ${(qty * rate).toFixed(2)}`;
        updateGrandTotal();
    }

    function removeRow(btn) {
        btn.closest('tr').remove();
        updateGrandTotal();
    }

    function updateGrandTotal() {
        let total = 0;
        document.querySelectorAll('.line-total').forEach(cell => {
            total += parseFloat(cell.textContent.replace('₹ ', '')) || 0;
        });
        document.getElementById('grandTotal').textContent = `₹ ${total.toFixed(2)}`;
    }
    </script>

</body>

</html>

<?php $conn->close(); ?>