<!-- edit_bbu.php -->
<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

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

$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 = "";
$bbu_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($bbu_id == 0) {
    header("Location: bbu_list.php");
    exit();
}

// Fetch BBU data
$bbu_query = $conn->prepare("
    SELECT b.*, p.project_code, p.project_name 
    FROM bbu_master b
    LEFT JOIN project_master p ON b.project_id = p.id
    WHERE b.id = ?
");
$bbu_query->bind_param("i", $bbu_id);
$bbu_query->execute();
$bbu_data = $bbu_query->get_result()->fetch_assoc();

if (!$bbu_data) {
    header("Location: bbu_list.php");
    exit();
}

// Check if BBU can be edited (only Draft status)
if ($bbu_data['status'] !== 'Draft') {
    $_SESSION['error'] = "Only Draft BBU entries can be edited.";
    header("Location: bbu_list.php");
    exit();
}

// Fetch BBU items
$items_query = $conn->prepare("
    SELECT * FROM bbu_items 
    WHERE bbu_id = ? 
    ORDER BY sr_no
");
$items_query->bind_param("i", $bbu_id);
$items_query->execute();
$bbu_items = $items_query->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch BBU payments
$payment_query = $conn->prepare("
    SELECT * FROM bbu_payments 
    WHERE bbu_id = ? 
    ORDER BY sr_no
");
$payment_query->bind_param("i", $bbu_id);
$payment_query->execute();
$payment_items = $payment_query->get_result()->fetch_all(MYSQLI_ASSOC);

// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    try {
        $conn->begin_transaction();

        // First, restore original stock before updating
        $restore_query = $conn->prepare("
            SELECT bi.*, im.id as item_id 
            FROM bbu_items bi
            JOIN inventory_master im ON bi.model_no = im.model_no
            WHERE bi.bbu_id = ?
        ");
        $restore_query->bind_param("i", $bbu_id);
        $restore_query->execute();
        $original_items = $restore_query->get_result()->fetch_all(MYSQLI_ASSOC);

        // Restore original stock quantities
        foreach ($original_items as $orig_item) {
            $project_id = (int)$_POST['project_id'];
            $item_id = $orig_item['item_id'];
            $orig_qty = (float)$orig_item['quantity'];
            $orig_serial = $orig_item['serial_no'];
            
            // Restore stock in project_inventory
            $restore_stock = $conn->prepare("
                UPDATE project_inventory 
                SET current_stock = current_stock + ?,
                    last_updated = NOW()
                WHERE project_id = ? AND item_id = ?
            ");
            $restore_stock->bind_param("dii", $orig_qty, $project_id, $item_id);
            $restore_stock->execute();
            
            // Restore serial status if it was a serial item
            if (!empty($orig_serial)) {
                $restore_serial = $conn->prepare("
                    UPDATE project_inventory_serials 
                    SET status = 'IN', 
                        issued_date = NULL,
                        bbu_id = NULL,
                        updated_at = NOW()
                    WHERE serial_no = ? AND project_id = ? AND item_id = ?
                ");
                $restore_serial->bind_param("sii", $orig_serial, $project_id, $item_id);
                $restore_serial->execute();
            }
        }

        // Delete old items
        $conn->query("DELETE FROM bbu_items WHERE bbu_id = $bbu_id");

        // Update BBU master
        $project_id = (int)$_POST['project_id'];
        $boq_code = trim($_POST['boq_code'] ?? '');
        $boq_id = isset($_POST['boq_id']) ? (int)$_POST['boq_id'] : 0;  
        $system_description = trim($_POST['system_description']);
        $uom_id = (int)$_POST['uom_id'];
        $quantity = (float)$_POST['quantity'];
        $rate_type = $_POST['rate_type'];
        $boq_remarks = trim($_POST['boq_remarks'] ?? '');

        // Rate fields
        $sitc_rate = !empty($_POST['sitc_rate']) ? (float)$_POST['sitc_rate'] : null;
        $sitc_amount = !empty($_POST['sitc_amount']) ? (float)$_POST['sitc_amount'] : null;
        $supply_rate = !empty($_POST['supply_rate']) ? (float)$_POST['supply_rate'] : null;
        $supply_amount = !empty($_POST['supply_amount']) ? (float)$_POST['supply_amount'] : null;
        $itc_rate = !empty($_POST['itc_rate']) ? (float)$_POST['itc_rate'] : null;
        $itc_amount = !empty($_POST['itc_amount']) ? (float)$_POST['itc_amount'] : null;

        $update_bbu = $conn->prepare("
            UPDATE bbu_master SET 
                project_id = ?, 
                boq_id = ?,
                boq_code = ?, 
                system_description = ?, 
                uom_id = ?, 
                quantity = ?, 
                rate_type = ?, 
                sitc_rate = ?, 
                sitc_amount = ?, 
                supply_rate = ?, 
                supply_amount = ?, 
                itc_rate = ?, 
                itc_amount = ?, 
                boq_remarks = ?, 
                updated_by = ?, 
                updated_at = NOW()
            WHERE id = ?
        ");
        
        $update_bbu->bind_param("iisssisssddddssi", 
            $project_id, $boq_id, $boq_code, $system_description, $uom_id,
            $quantity, $rate_type, $sitc_rate, $sitc_amount,
            $supply_rate, $supply_amount, $itc_rate, $itc_amount,
            $boq_remarks, $user_id, $bbu_id
        );
        
        if (!$update_bbu->execute()) {
            throw new Exception("Failed to update BBU: " . $update_bbu->error);
        }

        // Insert updated BBU Items and Update Stock
        if (isset($_POST['bbu_items']) && is_array($_POST['bbu_items'])) {
            $item_stmt = $conn->prepare("
                INSERT INTO bbu_items (
                    bbu_id, sr_no, ra_no, model_no, serial_no, 
                    quantity, rate, amount, remarks
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            foreach ($_POST['bbu_items'] as $item) {
                $sr_no = (int)$item['sr_no'];
                $ra_no = trim($item['ra_no']);
                $model_no = trim($item['model_no'] ?? '');
                $serial_no = trim($item['serial_no'] ?? '');
                $quantity_item = (float)$item['quantity'];
                $rate = (float)$item['rate'];
                $amount = (float)$item['amount'];
                $remarks = trim($item['remarks'] ?? '');
                
                // Insert BBU item
                $item_stmt->bind_param("iisssddds", 
                    $bbu_id, $sr_no, $ra_no, $model_no, $serial_no, 
                    $quantity_item, $rate, $amount, $remarks
                );
                
                if (!$item_stmt->execute()) {
                    throw new Exception("Failed to insert BBU item: " . $item_stmt->error);
                }

                // =========================
                // STOCK VALIDATION & DEDUCTION
                // =========================
                
                // Get item_id from inventory_master
                $get_item = $conn->prepare("
                    SELECT id FROM inventory_master WHERE model_no = ?
                ");
                $get_item->bind_param("s", $model_no);
                $get_item->execute();
                $item_result = $get_item->get_result();
                
                if ($item_result->num_rows === 0) {
                    throw new Exception("Item not found for model: $model_no");
                }
                
                $item_row = $item_result->fetch_assoc();
                $item_id = $item_row['id'];
                $get_item->close();
                
                // Check current stock
                $check_stock = $conn->prepare("
                    SELECT id, current_stock, avg_rate 
                    FROM project_inventory 
                    WHERE project_id = ? AND item_id = ?
                ");
                $check_stock->bind_param("ii", $project_id, $item_id);
                $check_stock->execute();
                $stock_result = $check_stock->get_result();
                
                if ($stock_result->num_rows === 0) {
                    throw new Exception("No stock record found for model: $model_no in this project");
                }
                
                $stock_row = $stock_result->fetch_assoc();
                $current_stock = (float)$stock_row['current_stock'];
                $project_inventory_id = $stock_row['id'];
                $check_stock->close();
                
                // Validate sufficient stock
                if ($current_stock < $quantity_item) {
                    throw new Exception("Insufficient stock for model: $model_no. Available: $current_stock, Required: $quantity_item");
                }
                
                // Update stock in project_inventory
                $new_stock = $current_stock - $quantity_item;
                $update_stock = $conn->prepare("
                    UPDATE project_inventory 
                    SET current_stock = ?, 
                        last_updated = NOW()
                    WHERE id = ?
                ");
                $update_stock->bind_param("di", $new_stock, $project_inventory_id);
                
                if (!$update_stock->execute()) {
                    throw new Exception("Failed to update stock for model: $model_no");
                }
                $update_stock->close();
                
                // =========================
                // HANDLE SERIAL NUMBERS
                // =========================
                if (!empty($serial_no)) {
                    // Split serial numbers if multiple
                    $serial_list = array_map('trim', explode(',', $serial_no));
                    
                    foreach ($serial_list as $single_serial) {
                        if (empty($single_serial)) continue;
                        
                        // Check if serial exists and is IN status
                        $check_serial = $conn->prepare("
                            SELECT id, status 
                            FROM project_inventory_serials 
                            WHERE serial_no = ? AND project_id = ? AND item_id = ?
                        ");
                        $check_serial->bind_param("sii", $single_serial, $project_id, $item_id);
                        $check_serial->execute();
                        $serial_result = $check_serial->get_result();
                        
                        if ($serial_result->num_rows === 0) {
                            throw new Exception("Serial number not found: $single_serial");
                        }
                        
                        $serial_row = $serial_result->fetch_assoc();
                        $serial_id = $serial_row['id'];
                        $serial_status = $serial_row['status'];
                        $check_serial->close();
                        
                        if ($serial_status !== 'IN') {
                            throw new Exception("Serial number $single_serial is not available (Status: $serial_status)");
                        }
                        
                        // Update serial status to OUT
                        $update_serial = $conn->prepare("
                            UPDATE project_inventory_serials 
                            SET status = 'OUT', 
                                issued_date = NOW(),
                                bbu_id = ?,
                                updated_at = NOW()
                            WHERE id = ?
                        ");
                        $update_serial->bind_param("ii", $bbu_id, $serial_id);
                        
                        if (!$update_serial->execute()) {
                            throw new Exception("Failed to update serial status for: $single_serial");
                        }
                        $update_serial->close();
                    }
                }
            }
            $item_stmt->close();
        }
        // =========================
// SAVE PAYMENT ITEMS
// =========================

// First delete old payments
$conn->query("DELETE FROM bbu_payments WHERE bbu_id = $bbu_id");

if (isset($_POST['payment_items']) && is_array($_POST['payment_items'])) {

    $payment_stmt = $conn->prepare("
        INSERT INTO bbu_payments 
        (bbu_id, sr_no, payment_date, description, amount, remarks, status)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");

    foreach ($_POST['payment_items'] as $p) {
        $sr_no = (int)$p['sr_no'];
        $payment_date = !empty($p['payment_date']) ? $p['payment_date'] : null;
        $description = trim($p['description'] ?? '');
        $amount = (float)($p['amount'] ?? 0);
        $remarks = trim($p['remarks'] ?? '');
        $status = $p['status'] ?? 'Pending';

        $payment_stmt->bind_param(
            "iissdss",
            $bbu_id,
            $sr_no,
            $payment_date,
            $description,
            $amount,
            $remarks,
            $status
        );

        if (!$payment_stmt->execute()) {
            throw new Exception("Payment insert failed: " . $payment_stmt->error);
        }
    }

    $payment_stmt->close();
}
        $conn->commit();
        
        $_SESSION['success'] = "BBU updated successfully and stock adjusted!";
        header("Location: bbu_list.php");
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error = "Error: " . $e->getMessage();
        error_log("BBU Update Error: " . $e->getMessage());
    }
}

// Fetch Projects & UOMs
$projects = $conn->query("
    SELECT id, project_code, project_name 
    FROM project_master 
    WHERE project_status IN ('Active', 'In Progress') 
    ORDER BY project_name ASC
");

$uoms_result = $conn->query("SELECT id, uom_name FROM uom_tbl ORDER BY uom_name ASC");
$uoms = $uoms_result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Edit BBU | Progress Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,600;14..32,700&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            color: #f1f5f9;
            min-height: 100vh;
            padding: 20px;
        }
        .container { max-width: 1400px; margin: 0 auto; }
        .glass-card {
            background: rgba(255, 255, 255, 0.08);
            backdrop-filter: blur(12px);
            border-radius: 32px;
            border: 1px solid rgba(255, 255, 255, 0.15);
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, rgba(139, 92, 246, 0.3), rgba(59, 130, 246, 0.2));
            padding: 40px 35px;
            position: relative;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        .header h1 {
            font-size: clamp(24px, 5vw, 36px);
            font-weight: 700;
            background: linear-gradient(135deg, #fff, #c4b5fd);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        .back-link {
            position: absolute;
            left: 35px;
            top: 40px;
            color: #a78bfa;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        .back-link:hover { color: #c4b5fd; transform: translateX(-5px); }
        .content { padding: 40px; }
        .alert {
            padding: 16px 20px;
            border-radius: 16px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 500;
            animation: slideIn 0.3s ease;
        }
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .alert-success { background: rgba(34, 197, 94, 0.2); border: 1px solid #4ade80; color: #86efac; }
        .alert-error { background: rgba(239, 68, 68, 0.2); border: 1px solid #f87171; color: #fca5a5; }
        .alert-warning {
            background: rgba(245, 158, 11, 0.2);
            border: 1px solid #f59e0b;
            color: #fbbf24;
        }
        .form-section {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 24px;
            padding: 30px;
            margin-bottom: 30px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            transition: all 0.3s;
        }
        .form-section:hover { border-color: rgba(139, 92, 246, 0.5); }
        .section-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            color: #c4b5fd;
        }
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 25px;
        }
        .form-group { margin-bottom: 0; }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #e0e7ff;
            font-size: 0.9rem;
        }
        .required { color: #f87171; margin-left: 4px; }
        input, select, textarea {
            width: 100%;
            padding: 14px 18px;
            background: rgba(255, 255, 255, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 16px;
            color: #fff;
            font-size: 0.95rem;
            transition: all 0.3s;
            font-family: inherit;
        }
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #8b5cf6;
            background: rgba(255, 255, 255, 0.12);
            box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.2);
        }
        textarea { resize: vertical; min-height: 100px; }
        .items-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }
        .btn-add {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 40px;
            cursor: pointer;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        .btn-add:hover { transform: translateY(-2px); box-shadow: 0 10px 25px rgba(16, 185, 129, 0.3); }
        .bbu-item {
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 20px;
            position: relative;
            transition: all 0.3s;
        }
        .bbu-item:hover { background: rgba(255, 255, 255, 0.06); border-color: rgba(139, 92, 246, 0.4); }
        .btn-remove {
            position: absolute;
            top: 20px;
            right: 20px;
            background: rgba(239, 68, 68, 0.2);
            color: #f87171;
            border: 1px solid #f87171;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
        }
        .btn-remove:hover { background: #ef4444; color: white; transform: scale(1.1); }
        .item-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 18px;
        }
        .btn-submit {
            width: 100%;
            background: linear-gradient(135deg, #8b5cf6, #6d28d9);
            color: white;
            border: none;
            padding: 18px;
            border-radius: 40px;
            font-size: 1.1rem;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            transition: all 0.3s;
            margin-top: 20px;
        }
        .btn-submit:hover { transform: translateY(-3px); box-shadow: 0 20px 40px rgba(139, 92, 246, 0.4); }
        .suggestions-box {
            position: absolute;
            z-index: 1000;
            background: #1e1b4b;
            border: 1px solid #8b5cf6;
            border-radius: 12px;
            max-height: 250px;
            overflow-y: auto;
            width: calc(100% - 36px);
            margin-top: 5px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
        }
        .suggestion-item {
            padding: 12px 16px;
            cursor: pointer;
            transition: background 0.2s;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        .suggestion-item:hover { background: rgba(139, 92, 246, 0.3); }
        .suggestion-item strong { color: #c4b5fd; }
        .suggestion-desc { font-size: 0.8rem; color: #9ca3af; margin-top: 4px; }
        .info-badge {
            display: inline-block;
            background: rgba(139, 92, 246, 0.3);
            padding: 6px 12px;
            border-radius: 12px;
            font-size: 0.85rem;
            margin-bottom: 20px;
        }
        @media (max-width: 768px) {
            body { padding: 10px; }
            .content { padding: 20px; }
            .form-section { padding: 20px; }
            .header { padding: 30px 20px; }
            .back-link { position: static; display: inline-flex; margin-bottom: 15px; }
            .item-grid { grid-template-columns: 1fr; }
        }
        input[readonly] { background: rgba(255, 255, 255, 0.05); cursor: not-allowed; }
        .stock-warning {
            background: rgba(245, 158, 11, 0.2);
            border: 1px solid #f59e0b;
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 0.75rem;
            margin-top: 5px;
        }
        select[name*="[status]"] {
    font-weight: 600;
    
}
option{
    color:black;
}
    </style>
</head>
<body>

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

<div class="container">
    <div class="glass-card">
        <div class="header">
            <a href="bbu_list.php" class="back-link">
                <i class="fas fa-arrow-left"></i> Back to BBU List
            </a>
            <h1 style="margin-top: 10px;">
                <i class="fas fa-edit"></i> 
                Edit BBU Entry
            </h1>
            <p style="margin-top: 10px; opacity: 0.7;">Edit material issue details and update inventory</p>
        </div>

        <div class="content">
            <div class="alert alert-warning">
                <i class="fas fa-info-circle"></i>
                <strong>BBU Number: <?= htmlspecialchars($bbu_data['bbu_no']) ?></strong> | 
                Status: <?= htmlspecialchars($bbu_data['status']) ?> | 
                Created: <?= date('d-m-Y', strtotime($bbu_data['created_at'])) ?>
            </div>

            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form method="post" id="bbuForm" onsubmit="return validateForm()">
                
                <!-- BOQ Section -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-file-invoice"></i>
                        <span>Issue Details</span>
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label>Project <span class="required">*</span></label>
                            <select name="project_id" id="project_id" required>
                                <option value="">-- Select Project --</option>
                                <?php 
                                $projects->data_seek(0);
                                while ($p = $projects->fetch_assoc()): ?>
                                    <option value="<?= $p['id'] ?>" <?= ($bbu_data['project_id'] ?? '') == $p['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($p['project_code']) ?> - <?= htmlspecialchars($p['project_name']) ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div class="form-group" style="position: relative;">
                            <label>BOQ Code</label>
                            <input type="text" name="boq_code" id="boq_code" value="<?= htmlspecialchars($bbu_data['boq_code'] ?? '') ?>" 
                                   placeholder="Search BOQ Code..." autocomplete="off">
                                   <!-- ✅ ADD THIS LINE HERE -->
                                <input type="hidden" name="boq_id" id="boq_id" 
                                    value="<?= htmlspecialchars($bbu_data['boq_id'] ?? '') ?>">
                            <div id="boqSuggestions" class="suggestions-box" style="display: none;"></div>
                        </div>

                        <div class="form-group">
                            <label>System Description <span class="required">*</span></label>
                            <textarea name="system_description" id="system_description" required><?= htmlspecialchars($bbu_data['system_description'] ?? '') ?></textarea>
                        </div>

                        <div class="form-group">
                            <label>Unit of Measurement <span class="required">*</span></label>
                            <select name="uom_id" id="uom_id" required>
                                <option value="">-- Select UOM --</option>
                                <?php foreach ($uoms as $u): ?>
                                    <option value="<?= $u['id'] ?>" <?= ($bbu_data['uom_id'] ?? '') == $u['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($u['uom_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Total Quantity <span class="required">*</span></label>
                            <input type="number" step="0.001" name="quantity" id="quantity" value="<?= $bbu_data['quantity'] ?? '' ?>" 
                                   required oninput="calculateAmounts()">
                        </div>

                        <div class="form-group">
                            <label>Rate Type <span class="required">*</span></label>
                            <select name="rate_type" id="rate_type" onchange="toggleRateFields()" required>
                                <option value="">-- Select Type --</option>
                                <option value="SITC" <?= ($bbu_data['rate_type'] ?? '') == 'SITC' ? 'selected' : '' ?>>SITC</option>
                                <option value="S+ITC" <?= ($bbu_data['rate_type'] ?? '') == 'S+ITC' ? 'selected' : '' ?>>Supply + ITC</option>
                            </select>
                        </div>
                    </div>

                    <div id="rateFields"></div>

                    <div class="form-group" style="margin-top: 20px;">
                        <label>Remarks</label>
                        <textarea name="boq_remarks" rows="2"><?= htmlspecialchars($bbu_data['boq_remarks'] ?? '') ?></textarea>
                    </div>
                </div>

                <!-- BBU Items Section -->
                <div class="form-section">
                    <div class="items-header">
                        <div class="section-title">
                            <i class="fas fa-list"></i>
                            <span>Materials to Issue</span>
                        </div>
                        <button type="button" class="btn-add" onclick="addBBUItem()">
                            <i class="fas fa-plus"></i> Add Item
                        </button>
                    </div>
                    
                    <div id="bbuItemsContainer">
                        <?php if (!empty($bbu_items)): ?>
                            <?php foreach ($bbu_items as $index => $item): ?>
                                <div class="bbu-item" data-id="<?= $index + 1 ?>">
                                    <button type="button" class="btn-remove" onclick="removeBBUItem(this)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <div class="item-grid">
                                        <div class="form-group">
                                            <label>Sr. No.</label>
                                            <input type="number" name="bbu_items[<?= $index + 1 ?>][sr_no]" value="<?= $item['sr_no'] ?>" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>RA No.</label>
                                            <input type="text" name="bbu_items[<?= $index + 1 ?>][ra_no]" value="<?= htmlspecialchars($item['ra_no']) ?>" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>Model No. <span class="required">*</span></label>
                                            <input type="text" name="bbu_items[<?= $index + 1 ?>][model_no]" value="<?= htmlspecialchars($item['model_no'] ?? '') ?>" 
                                                   placeholder="Enter model" onkeyup="searchModel(this, <?= $index + 1 ?>)" autocomplete="off" required>
                                            <div id="modelSuggestions_<?= $index + 1 ?>" class="suggestions-box" style="display: none;"></div>
                                        </div>
                                        <div class="form-group">
                                            <label>Serial No.</label>
                                            <select name="bbu_items[<?= $index + 1 ?>][serial_no]" class="serial-dropdown">
                                                <option value="<?= htmlspecialchars($item['serial_no'] ?? '') ?>">
                                                    <?= htmlspecialchars($item['serial_no'] ?? 'Select Serial') ?>
                                                </option>
                                            </select>
                                            <div id="stockWarning_<?= $index + 1 ?>" class="stock-warning" style="display: none;"></div>
                                        </div>
                                        <div class="form-group">
                                            <label>Quantity <span class="required">*</span></label>
                                            <input type="number" step="0.001" name="bbu_items[<?= $index + 1 ?>][quantity]" value="<?= $item['quantity'] ?>" 
                                                   required oninput="calculateItemAmount(this)">
                                        </div>
                                        <div class="form-group">
                                            <label>Rate (₹) <span class="required">*</span></label>
                                            <input type="number" step="0.01" name="bbu_items[<?= $index + 1 ?>][rate]" value="<?= $item['rate'] ?>" 
                                                   required oninput="calculateItemAmount(this)">
                                        </div>
                                        <div class="form-group">
                                            <label>Amount (₹)</label>
                                            <input type="text" name="bbu_items[<?= $index + 1 ?>][amount]" value="<?= $item['amount'] ?>" readonly>
                                        </div>
                                        <div class="form-group">
                                            <label>Remarks</label>
                                            <textarea name="bbu_items[<?= $index + 1 ?>][remarks]" rows="2"><?= htmlspecialchars($item['remarks'] ?? '') ?></textarea>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
                
                    <!-- Payment Section -->
                    <div class="form-section">
                        <div class="items-header">
                            <div class="section-title">
                                <i class="fas fa-list"></i>
                                <span>Payment Details</span>
                            </div>
                            <button type="button" class="btn-add" onclick="addPaymentItem()">
                                <i class="fas fa-plus"></i> Add Payment
                            </button>
                        </div>

                        <div id="paymentItemsContainer">
                            <?php if (!empty($payment_items)): ?>
                            <?php foreach ($payment_items as $index => $item): ?>
                            <div class="payment-item" data-id="<?= $index + 1 ?>">
                                <button type="button" class="btn-remove" onclick="removePaymentItem(this)">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <div class="item-grid">
                                    <div class="form-group">
                                        <label>Sr. No.</label>
                                        <input type="number" name="payment_items[<?= $index + 1 ?>][sr_no]"
                                            value="<?= $item['sr_no'] ?>" readonly>
                                    </div>
                                    <div class="form-group">
                                        <label>Payment Date</label>
                                        <input type="date" name="payment_items[<?= $index + 1 ?>][payment_date]">
                                    </div>
                                    <div class="form-group">
                                        <label>Description</label>
                                        <textarea name="payment_items[<?= $index + 1 ?>][description]"
                                            rows="2"><?= htmlspecialchars($item['description'] ?? '') ?></textarea>
                                    </div>

                                    <div class="form-group">
                                        <label>Amount (₹)</label>
                                        <input type="text" name="payment_items[<?= $index + 1 ?>][amount]"
                                            value="<?= $item['amount'] ?>">
                                    </div>
                                    <div class="form-group">
                                        <label>Remarks</label>
                                        <textarea name="payment_items[<?= $index + 1 ?>][remarks]"
                                            rows="2"><?= htmlspecialchars($item['remarks'] ?? '') ?></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label>Status</label>
                                        <select name="payment_items[<?= $index + 1 ?>][status]">
                                            <option value="Pending"
                                                <?= ($item['status'] ?? '') == 'Pending' ? 'selected' : '' ?>>Pending
                                            </option>
                                            <option value="Paid"
                                                <?= ($item['status'] ?? '') == 'Paid' ? 'selected' : '' ?>>Paid</option>
                                            <option value="Partial"
                                                <?= ($item['status'] ?? '') == 'Partial' ? 'selected' : '' ?>>Partial
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>                
                <button type="submit" class="btn-submit">
                    <i class="fas fa-save"></i>
                    Update BBU Entry
                </button>
            </form>
        </div>
    </div>
</div>

<script>
let itemCount = <?= count($bbu_items) ?: 0 ?>;
let paymentItemCount = <?= count($payment_items) ?: 0 ?>;

// Initialize on load
document.addEventListener('DOMContentLoaded', function() {
    toggleRateFields();
    calculateAmounts();
    
    if (document.getElementById('bbuItemsContainer').children.length === 0) {
        addBBUItem();
    }
});

// Toggle Rate Fields
function toggleRateFields() {
    const type = document.querySelector('[name="rate_type"]').value;
    const container = document.getElementById('rateFields');
    
    if (type === 'SITC') {
        container.innerHTML = `
            <div class="form-grid" style="margin-top: 25px;">
                <div class="form-group">
                    <label>SITC Rate (₹)</label>
                    <input type="number" step="0.01" name="sitc_rate" id="sitc_rate" value="<?= $bbu_data['sitc_rate'] ?? '' ?>" oninput="calculateAmounts()">
                </div>
                <div class="form-group">
                    <label>SITC Amount (₹)</label>
                    <input type="text" name="sitc_amount" id="sitc_amount" value="<?= $bbu_data['sitc_amount'] ?? '' ?>" readonly>
                </div>
            </div>`;
    } else if (type === 'S+ITC') {
        container.innerHTML = `
            <div class="form-grid" style="margin-top: 25px;">
                <div class="form-group">
                    <label>Supply Rate (₹)</label>
                    <input type="number" step="0.01" name="supply_rate" id="supply_rate" value="<?= $bbu_data['supply_rate'] ?? '' ?>" oninput="calculateAmounts()">
                </div>
                <div class="form-group">
                    <label>ITC Rate (₹)</label>
                    <input type="number" step="0.01" name="itc_rate" id="itc_rate" value="<?= $bbu_data['itc_rate'] ?? '' ?>" oninput="calculateAmounts()">
                </div>
                <div class="form-group">
                    <label>Supply Amount (₹)</label>
                    <input type="text" name="supply_amount" id="supply_amount" value="<?= $bbu_data['supply_amount'] ?? '' ?>" readonly>
                </div>
                <div class="form-group">
                    <label>ITC Amount (₹)</label>
                    <input type="text" name="itc_amount" id="itc_amount" value="<?= $bbu_data['itc_amount'] ?? '' ?>" readonly>
                </div>
            </div>`;
    } else {
        container.innerHTML = '';
    }
}

// Calculate Amounts
function calculateAmounts() {
    const qty = parseFloat(document.querySelector('[name="quantity"]')?.value) || 0;
    const type = document.querySelector('[name="rate_type"]')?.value;
    
    if (type === 'SITC') {
        const rate = parseFloat(document.querySelector('[name="sitc_rate"]')?.value) || 0;
        const amount = qty * rate;
        const amountField = document.querySelector('[name="sitc_amount"]');
        if (amountField) amountField.value = amount.toFixed(2);
    } else if (type === 'S+ITC') {
        const supplyRate = parseFloat(document.querySelector('[name="supply_rate"]')?.value) || 0;
        const itcRate = parseFloat(document.querySelector('[name="itc_rate"]')?.value) || 0;
        const supplyAmount = qty * supplyRate;
        const itcAmount = qty * itcRate;
        
        const supplyField = document.querySelector('[name="supply_amount"]');
        const itcField = document.querySelector('[name="itc_amount"]');
        if (supplyField) supplyField.value = supplyAmount.toFixed(2);
        if (itcField) itcField.value = itcAmount.toFixed(2);
    }
}

// Add BBU Item
function addBBUItem() {
    itemCount++;
    const container = document.getElementById('bbuItemsContainer');
    const srNo = itemCount;
    const raNo = `RA-${srNo}`;
    
    const html = `
        <div class="bbu-item" data-id="${itemCount}">
            <button type="button" class="btn-remove" onclick="removeBBUItem(this)">
                <i class="fas fa-trash"></i>
            </button>
            <div class="item-grid">
                <div class="form-group">
                    <label>Sr. No.</label>
                    <input type="number" name="bbu_items[${itemCount}][sr_no]" value="${srNo}" readonly>
                </div>
                <div class="form-group">
                    <label>RA No.</label>
                    <input type="text" name="bbu_items[${itemCount}][ra_no]" value="${raNo}" readonly>
                </div>
                <div class="form-group">
                    <label>Model No. <span class="required">*</span></label>
                    <input type="text" name="bbu_items[${itemCount}][model_no]" placeholder="Enter model" 
                           onkeyup="searchModel(this, ${itemCount})" autocomplete="off" required>
                    <div id="modelSuggestions_${itemCount}" class="suggestions-box" style="display: none;"></div>
                </div>
                <div class="form-group">
                    <label>Serial No.</label>
                    <select name="bbu_items[${itemCount}][serial_no]" class="serial-dropdown">
                        <option value="">Select Serial</option>
                    </select>
                    <div id="stockWarning_${itemCount}" class="stock-warning" style="display: none;"></div>
                </div>
                <div class="form-group">
                    <label>Quantity <span class="required">*</span></label>
                    <input type="number" step="0.001" name="bbu_items[${itemCount}][quantity]" required oninput="calculateItemAmount(this)">
                </div>
                <div class="form-group">
                    <label>Rate (₹) <span class="required">*</span></label>
                    <input type="number" step="0.01" name="bbu_items[${itemCount}][rate]" required oninput="calculateItemAmount(this)">
                </div>
                <div class="form-group">
                    <label>Amount (₹)</label>
                    <input type="text" name="bbu_items[${itemCount}][amount]" readonly>
                </div>
                <div class="form-group">
                    <label>Remarks</label>
                    <textarea name="bbu_items[${itemCount}][remarks]" rows="2"></textarea>
                </div>
            </div>
        </div>
    `;
    container.insertAdjacentHTML('beforeend', html);
}

// Remove BBU Item
function removeBBUItem(btn) {
    if (confirm('Are you sure you want to remove this item?')) {
        btn.closest('.bbu-item').remove();
        reindexItems();
    }
}

// Re-index items
function reindexItems() {
    const items = document.querySelectorAll('#bbuItemsContainer .bbu-item');
    let newIndex = 1;
    
    items.forEach(item => {
        const srNoInput = item.querySelector('input[name*="[sr_no]"]');
        const raNoInput = item.querySelector('input[name*="[ra_no]"]');
        
        if (srNoInput) {
            srNoInput.value = newIndex;
            const oldName = srNoInput.getAttribute('name');
            const newName = oldName.replace(/bbu_items\[\d+\]/, `bbu_items[${newIndex}]`);
            srNoInput.setAttribute('name', newName);
        }
        
        if (raNoInput) {
            raNoInput.value = `RA-${newIndex}`;
            const oldName = raNoInput.getAttribute('name');
            const newName = oldName.replace(/bbu_items\[\d+\]/, `bbu_items[${newIndex}]`);
            raNoInput.setAttribute('name', newName);
        }
        
        item.querySelectorAll('input, select, textarea').forEach(input => {
            if (input.getAttribute('name') && !input.getAttribute('name').includes('[sr_no]') && !input.getAttribute('name').includes('[ra_no]')) {
                const oldName = input.getAttribute('name');
                const newName = oldName.replace(/bbu_items\[\d+\]/, `bbu_items[${newIndex}]`);
                input.setAttribute('name', newName);
            }
        });
        
        const modelSuggestions = item.querySelector(`#modelSuggestions_${item.getAttribute('data-id')}`);
        if (modelSuggestions) {
            modelSuggestions.id = `modelSuggestions_${newIndex}`;
        }
        
        const stockWarning = item.querySelector(`#stockWarning_${item.getAttribute('data-id')}`);
        if (stockWarning) {
            stockWarning.id = `stockWarning_${newIndex}`;
        }
        
        item.setAttribute('data-id', newIndex);
        newIndex++;
    });
    
    itemCount = newIndex - 1;
}

// Calculate Item Amount
function calculateItemAmount(input) {
    const itemDiv = input.closest('.bbu-item');
    const qty = parseFloat(itemDiv.querySelector('input[name*="[quantity]"]').value) || 0;
    const rate = parseFloat(itemDiv.querySelector('input[name*="[rate]"]').value) || 0;
    const amount = qty * rate;
    const amountField = itemDiv.querySelector('input[name*="[amount]"]');
    if (amountField) amountField.value = amount.toFixed(2);
    
    checkStockAvailability(itemDiv);
}

// Check stock availability
async function checkStockAvailability(itemDiv) {
    const projectId = document.querySelector('[name="project_id"]').value;
    const modelNo = itemDiv.querySelector('input[name*="[model_no]"]').value;
    const quantity = parseFloat(itemDiv.querySelector('input[name*="[quantity]"]').value) || 0;
    const itemId = itemDiv.getAttribute('data-id');
    const warningDiv = document.getElementById(`stockWarning_${itemId}`);
    
    if (!projectId || !modelNo || quantity === 0) {
        if (warningDiv) warningDiv.style.display = 'none';
        return;
    }
    
    try {
        const response = await fetch(`check_stock.php?project_id=${projectId}&model_no=${encodeURIComponent(modelNo)}`);
        const data = await response.json();
        
        if (data.success && warningDiv) {
            if (data.current_stock < quantity) {
                warningDiv.style.display = 'block';
                warningDiv.innerHTML = `<i class="fas fa-exclamation-triangle"></i> Insufficient stock! Available: ${data.current_stock} ${data.uom}`;
                warningDiv.style.color = '#fca5a5';
                warningDiv.style.borderColor = '#ef4444';
            } else if (data.current_stock < quantity * 1.2) {
                warningDiv.style.display = 'block';
                warningDiv.innerHTML = `<i class="fas fa-info-circle"></i> Low stock! Available: ${data.current_stock} ${data.uom}`;
                warningDiv.style.color = '#fbbf24';
                warningDiv.style.borderColor = '#f59e0b';
            } else {
                warningDiv.style.display = 'none';
            }
        }
    } catch (error) {
        console.error('Stock check error:', error);
    }
}

// Search Model
let searchTimeout;
function searchModel(input, itemId) {
    clearTimeout(searchTimeout);
    const query = input.value.trim();
    const suggestionsDiv = document.getElementById(`modelSuggestions_${itemId}`);
    
    if (query.length < 2) {
        suggestionsDiv.style.display = 'none';
        return;
    }
    
    searchTimeout = setTimeout(() => {
        fetch(`search_inventory.php?type=model&query=${encodeURIComponent(query)}`)
            .then(res => res.json())
            .then(data => {
                suggestionsDiv.innerHTML = '';
                if (data.success && data.items && data.items.length > 0) {
                    data.items.forEach(item => {
                        const div = document.createElement('div');
                        div.className = 'suggestion-item';
                        div.innerHTML = `<strong>${escapeHtml(item.model_no)}</strong><div class="suggestion-desc">${escapeHtml(item.name || '')}</div>`;
                        div.onclick = () => {
                            input.value = item.model_no;
                            suggestionsDiv.style.display = 'none';
                            
                            const itemDiv = input.closest('.bbu-item');
                            checkStockAvailability(itemDiv);
                            loadSerials(itemId, item.model_no);
                        };
                        suggestionsDiv.appendChild(div);
                    });
                    suggestionsDiv.style.display = 'block';
                } else {
                    suggestionsDiv.innerHTML = '<div class="suggestion-item">No models found</div>';
                    suggestionsDiv.style.display = 'block';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                suggestionsDiv.style.display = 'none';
            });
    }, 300);
}

// Load Serials
async function loadSerials(itemId, modelNo) {
    const projectId = document.querySelector('[name="project_id"]').value;
    if (!projectId) {
        alert('Please select a project first');
        return;
    }
    
    const itemDiv = document.querySelector(`#bbuItemsContainer .bbu-item[data-id="${itemId}"]`);
    const serialSelect = itemDiv.querySelector('.serial-dropdown');
    if (!serialSelect) return;
    
    serialSelect.innerHTML = '<option>Loading...</option>';
    
    try {
        const response = await fetch(`get_serials.php?model_no=${encodeURIComponent(modelNo)}&project_id=${projectId}`);
        const data = await response.json();
        
        serialSelect.innerHTML = '<option value="">Select Serial (Optional)</option>';
        if (Array.isArray(data) && data.length > 0) {
            data.forEach(serial => {
                const option = document.createElement('option');
                option.value = serial;
                option.textContent = serial;
                serialSelect.appendChild(option);
            });
            serialSelect.innerHTML += '<option value="">No serial (bulk item)</option>';
        } else {
            serialSelect.innerHTML = '<option value="">No serials available for this model</option>';
        }
    } catch (error) {
        console.error('Error:', error);
        serialSelect.innerHTML = '<option value="">Error loading serials</option>';
    }
}

// Search BOQ
const boqInput = document.getElementById('boq_code');
const boqSuggestions = document.getElementById('boqSuggestions');
let boqSearchTimeout;

if (boqInput) {
    boqInput.addEventListener('input', function() {
        clearTimeout(boqSearchTimeout);
        const query = this.value.trim();
        const projectId = document.getElementById('project_id').value;
        if (query.length < 2) {
            boqSuggestions.style.display = 'none';
            return;
        }
        if (!projectId) {
            boqSuggestions.innerHTML = '<div class="suggestion-item">Please select a project first</div>';
            boqSuggestions.style.display = 'block';
            return;
            } 
        boqSearchTimeout = setTimeout(() => {
            fetch(`search_boq.php?term=${encodeURIComponent(query)}&project_id=${projectId}`)
                .then(res => res.json())
                .then(data => {
                    boqSuggestions.innerHTML = '';
                    
                    if (data && data.length > 0) {
                        data.forEach(item => {
                            const div = document.createElement('div');
                            div.className = 'suggestion-item';
                            div.innerHTML = `
                                <strong>${escapeHtml(item.boq_code)}</strong>
                                <div class="suggestion-desc">${escapeHtml(item.system_description.substring(0, 100))}</div>
                                <div class="suggestion-desc">Qty: ${item.quantity} | Type: ${item.type}</div>
                            `;
                            div.onclick = () => {
                                document.getElementById('boq_id').value = item.id;
                                document.getElementById('boq_code').value = item.boq_code;
                                document.getElementById('system_description').value = item.system_description;
                                document.getElementById('quantity').value = item.quantity;
                                document.getElementById('rate_type').value = item.type;
                                document.getElementById('uom_id').value = item.uom;
                                // const uomSelect = document.getElementById('uom_id');
                                // for (let i = 0; i < uomSelect.options.length; i++) {
                                //     if (uomSelect.options[i].text === item.uom) {
                                //         uomSelect.value = uomSelect.options[i].value;
                                //         break;
                                //     }
                                // }
                                
                                toggleRateFields();
                                if (item.type === 'SITC') {
                                    const sitcRate = document.getElementById('sitc_rate');
                                    if (sitcRate) sitcRate.value = item.sitc_rate;
                                } else if (item.type === 'S+ITC') {
                                    const supplyRate = document.getElementById('supply_rate');
                                    const itcRate = document.getElementById('itc_rate');
                                    if (supplyRate) supplyRate.value = item.supply_rate;
                                    if (itcRate) itcRate.value = item.itc_rate;
                                }
                                
                                calculateAmounts();
                                boqSuggestions.style.display = 'none';
                            };
                            boqSuggestions.appendChild(div);
                        });
                        boqSuggestions.style.display = 'block';
                    } else {
                        boqSuggestions.innerHTML = '<div class="suggestion-item">No BOQ found</div>';
                        boqSuggestions.style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    boqSuggestions.style.display = 'none';
                });
        }, 300);
    });
    
    document.addEventListener('click', function(e) {
        if (e.target !== boqInput) {
            boqSuggestions.style.display = 'none';
        }
    });
}

// Form Validation
function validateForm() {
    const project = document.querySelector('[name="project_id"]').value;
    const systemDesc = document.querySelector('[name="system_description"]').value;
    const quantity = document.querySelector('[name="quantity"]').value;
    const rateType = document.querySelector('[name="rate_type"]').value;
    
    if (!project || !systemDesc || !quantity || !rateType) {
        alert('Please fill all required fields in BOQ section');
        return false;
    }
    
    const items = document.querySelectorAll('.bbu-item');
    if (items.length === 0) {
        alert('Please add at least one item to issue');
        return false;
    }
    
    for (let item of items) {
        const modelNo = item.querySelector('input[name*="[model_no]"]').value;
        const qty = item.querySelector('input[name*="[quantity]"]').value;
        const rate = item.querySelector('input[name*="[rate]"]').value;
        
        if (!modelNo) {
            alert('Please enter model number for all items');
            return false;
        }
        if (!qty || parseFloat(qty) <= 0) {
            alert('Please enter valid quantity for all items');
            return false;
        }
        if (!rate || parseFloat(rate) < 0) {
            alert('Please enter valid rate for all items');
            return false;
        }
        
        const warningDiv = item.querySelector('.stock-warning');
        if (warningDiv && warningDiv.style.display === 'block' && warningDiv.innerHTML.includes('Insufficient')) {
            alert('Please check stock availability. Some items have insufficient stock.');
            return false;
        }
    }
    
    return confirm('Confirm update of BBU? This will adjust project inventory accordingly.');
}

// Escape HTML
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}



// Add payment Item
function addPaymentItem() {
    paymentItemCount++;
    const container = document.getElementById('paymentItemsContainer');
    const srNo = paymentItemCount;
    
    
    
    const html = `
        <div class="payment-item" data-id="${paymentItemCount}">
            <button type="button" class="btn-remove" onclick="removePaymentItem(this)">
                <i class="fas fa-trash"></i>
            </button>
            <div class="item-grid">
                <div class="form-group">
                    <label>Sr. No.</label>
                    <input type="number" name="payment_items[${paymentItemCount}][sr_no]" value="${srNo}" readonly>
                </div>
                <div class="form-group">
                    <label>Payment Date</label>
                    <input type="date" name="payment_items[${paymentItemCount}][payment_date]">
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="payment_items[${paymentItemCount}][description]" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label>Amount (₹)</label>
                    <input type="text" name="payment_items[${paymentItemCount}][amount]">
                </div>
                <div class="form-group">
                    <label>Remarks</label>
                    <textarea name="payment_items[${paymentItemCount}][remarks]" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label>Status</label>
                    <select name="payment_items[${paymentItemCount}][status]">
                        <option value="Pending">Pending</option>
                        <option value="Paid">Paid</option>
                        <option value="Partial">Partial</option>
                    </select>
</div>
                
            </div>
        </div>
    `;
    container.insertAdjacentHTML('beforeend', html);
}

// Remove BBU Item
function removePaymentItem(btn) {
    if (confirm('Are you sure you want to remove this item?')) {
        btn.closest('.payment-item').remove();
        reindexPaymentItems();
    }
}

function reindexPaymentItems() {
    const items = document.querySelectorAll('#paymentItemsContainer .payment-item');
    let index = 1;

    items.forEach(item => {
        item.querySelectorAll('input, textarea').forEach(input => {
            if (input.name) {
                input.name = input.name.replace(/payment_items\[\d+\]/, `payment_items[${index}]`);
            }
        });

        const srInput = item.querySelector('input[name*="[sr_no]"]');
        if (srInput) srInput.value = index;

        index++;
    });

    paymentItemCount = index - 1;
}
</script>

</body>
</html>

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