<?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 = "";
function generateBOQCode(mysqli $conn): string {
    $sql = "SELECT boq_code FROM  ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['boq_code'], 4) + 1;
    }
    return sprintf("BOQ-%03d", $next);
}

$generated_code = generateOfferCode($conn);

// 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">
    <title>Add BOQ (Biiling of Quantity)</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;
    }

    .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: 45px 40px;
        text-align: center;
    }

    .header h1 {
        font-size: 2.5rem;
        font-weight: 700;
    }

    .form-area {
        padding: 40px;
    }

    .section {
        background: rgba(255, 255, 255, 0.07);
        border: 1px solid rgba(255, 255, 255, 0.18);
        border-radius: 20px;
        padding: 28px;
        margin-bottom: 30px;
    }

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

    input,
    select,
    textarea {
        width: 100%;
        padding: 14px 16px;
        background: rgba(255, 255, 255, 0.09);
        border: 1px solid rgba(255, 255, 255, 0.25);
        border-radius: 12px;
        color: white;
        font-size: 15px;
    }
    option{
       color:black;
    }
    input:focus,
    select:focus,
    textarea:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(168, 85, 247, 0.25);
    }

    .dynamic-row {
        background: rgba(0, 0, 0, 0.25);
        padding: 20px;
        border-radius: 16px;
        margin-bottom: 18px;
        position: relative;
    }

    .remove-btn {
        position: absolute;
        top: 12px;
        right: 12px;
        background: #ef4444;
        color: white;
        border: none;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        cursor: pointer;
        font-size: 18px;
    }

    .add-row-btn,
    .submit-btn {
        width: 100%;
        padding: 18px;
        border-radius: 16px;
        font-weight: 700;
        font-size: 17px;
        cursor: pointer;
        margin: 20px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }

    .add-row-btn {
        background: rgba(168, 85, 247, 0.2);
        color: #c4b5fd;
        border: 1px solid rgba(168, 85, 247, 0.4);
    }

    .submit-btn {
        background: linear-gradient(135deg, var(--primary), var(--accent));
        color: white;
        border: none;
    }

    .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) {
        .header h1 {
            font-size: 2rem;
        }

        .form-area {
            padding: 25px 18px;
        }
    }
    </style>
</head>

<body>
    <?php include('../config/header.php'); ?>
    <div class="container">
        <div class="glass-container">
            <div class="header">
                <a href="boq_list.php" style="color:#c4b5fd; text-decoration:none; float:left; font-size:1.1rem;">
                    ← Back to BOQ List
                </a>
                <h1><i class="fas fa-calendar-plus"></i> Add BOQ</h1>
            </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" id="dprForm">

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

                   
                    <div class="section">
                        <label>Sr.No</label>
                        
                    </div>            
                    
                    <div class="section">
                        <h2></h2>
                        <div id="boqContainer"></div>
                        <div class="add-row-btn" onclick="addNewboqRow()">
                            <i class="fas fa-plus-circle"></i> Add BOQ
                        </div>
                    </div>

                    

                    <button type="submit" class="submit-btn">
                        <i class="fas fa-save"></i> Save BOQ
                    </button>
                </form>
            </div>
        </div>
    </div>

    <script>
    let boqCount = 0;
    
        
    const uoms = <?= json_encode($uoms) ?>;

    function addNewboqRow() {
        boqCount++;
        const html = `
        <div class="dynamic-row" id="boq-${boqCount}">
            <button type="button" class="remove-btn" onclick="this.parentElement.remove()">×</button>
            <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(200px,1fr)); gap:15px;">
                <div><label>Sr No</label><input type="number" name="boq[${boqCount}][sr_no]" value="${generated_code}" readonly></div>
                <div><label>BOQ Code</label><input type="text" name="boq[${boqCount}][boq_code]" value=""></div>
                <div><label>System Description</label><textarea name="boq[${boqCount}][system_description]" rows="3" placeholder="Enter System Description"></textarea></div>
                <div><label>Quantity</label><input type="number" step="0.01" name="boq[${boqCount}][quantity]"></div>
                <div><label>UOM</label><select name="boq[${boqCount}][uom]">${uoms.map(u => `<option value="${u.id}">${u.uom_name}</option>`).join('')}</select></div>
                <div>
                    <label>Rate Type <span class="required">*</span></label>
                    <select name="budget[${boqCount}][type]" onchange="toggleBudgetFields(this)">
                        <option value="">Select Type</option>
                        <option value="SITC">SITC</option>
                        <option value="S+ITC">S + ITC</option>
                    </select>
                </div>
                <div class="dynamic-fields full-width" id="dynamic-fields-${boqCount}"></div>

                <div class="full-width" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:18px;">
                    <div><label>CGST (%)</label><input type="number" step="0.01" name="budget[${boqCount}][cgst]" value="0" oninput="calculateRow(this)"></div>
                    <div><label>SGST (%)</label><input type="number" step="0.01" name="budget[${boqCount}][sgst]" value="0" oninput="calculateRow(this)"></div>
                    <div><label>IGST (%)</label><input type="number" step="0.01" name="budget[${boqCount}][igst]" value="0" oninput="calculateRow(this)"></div>
                </div>
               
                <div><label>Remarks</label><textarea name="boq[${boqCount}][remarks]" rows="2"></textarea></div>
               

            </div>
            
        </div>`;
        document.getElementById('boqContainer').insertAdjacentHTML('beforeend', html);
        document.getElementById('totalsBox').style.display = 'block';
    }
    function toggleBudgetFields(select) {
        const rowId = select.closest('.dynamic-row').id.split('-')[2];
        const div = document.getElementById(`dynamic-fields-${rowId}`);
        if (select.value === 'SITC') {
            div.innerHTML =
                `
            <div><label>SITC Rate (₹)</label><input type="number" step="0.01" name="budget[${rowId}][sitc_rate]" oninput="calculateRow(this)"></div>
            <div><label>SITC Amount (₹)</label><input type="number" step="0.01" name="budget[${rowId}][sitc_amount]" readonly></div>`;
        } else if (select.value === 'S+ITC') {
            div.innerHTML =
                `
            <div><label>Supply Rate (₹)</label><input type="number" step="0.01" name="budget[${rowId}][supply_rate]" oninput="calculateRow(this)"></div>
            <div><label>ITC Rate (₹)</label><input type="number" step="0.01" name="budget[${rowId}][itc_rate]" oninput="calculateRow(this)"></div>
            <div><label>Supply Amount (₹)</label><input type="number" step="0.01" name="budget[${rowId}][supply_amount]" readonly></div>
            <div><label>ITC Amount (₹)</label><input type="number" step="0.01" name="budget[${rowId}][itc_amount]" readonly></div>`;
        } else div.innerHTML = '';
        div.style.display = select.value ? 'grid' : 'none';
        calculateRow(select);
    }

    function calculateRow(el) {
        const row = el.closest('.item-row');
        const qty = parseFloat(row.querySelector('.quantity')?.value) || 0;

        // SITC
        const sitcRate = parseFloat(row.querySelector('[name*="sitc_rate"]')?.value) || 0;
        if (row.querySelector('[name*="sitc_amount"]')) row.querySelector('[name*="sitc_amount"]').value = (sitcRate *
            qty).toFixed(2);

        // S+ITC
        const supplyRate = parseFloat(row.querySelector('[name*="supply_rate"]')?.value) || 0;
        const itcRate = parseFloat(row.querySelector('[name*="itc_rate"]')?.value) || 0;
        if (row.querySelector('[name*="supply_amount"]')) row.querySelector('[name*="supply_amount"]').value = (
            supplyRate * qty).toFixed(2);
        if (row.querySelector('[name*="itc_amount"]')) row.querySelector('[name*="itc_amount"]').value = (itcRate * qty)
            .toFixed(2);

        
    }
                            
    
    

    window.onload = () => {
    addNewboqRow(); 
};
    </script>

</body>

</html>

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