<?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");

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit();
}

$success = "";
$error = "";

// Generate BOQ Code
function generateBOQCode(mysqli $conn): string {
    $sql = "SELECT boq_code FROM boq_master 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-%04d", $next);
}

$generated_code = generateBOQCode($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 = $conn->query("SELECT id, uom_name FROM uom_tbl ORDER BY uom_name ASC");

// ====================== AJAX: Add New UOM ======================
if (isset($_POST['action']) && $_POST['action'] === 'add_uom') {
    header('Content-Type: application/json');
    $name = trim($_POST['name'] ?? '');
    if (empty($name)) {
        echo json_encode(['success' => false, 'message' => 'UOM name is required']);
        exit;
    }
    $stmt = $conn->prepare("INSERT INTO uom_tbl (uom_name) VALUES (?)");
    $stmt->bind_param("s", $name);
    echo $stmt->execute() 
        ? json_encode(['success' => true, 'id' => $conn->insert_id, 'name' => $name])
        : json_encode(['success' => false, 'message' => $conn->error]);
    exit;
}

// ====================== FORM SUBMISSION ======================
if ($_SERVER["REQUEST_METHOD"] === "POST" && !isset($_POST['action'])) {
    $project_id         = (int)$_POST['project_id'];
    $boq_code           = trim($_POST['boq_code']);
    $system_description = trim($_POST['system_description']);
    $quantity           = floatval($_POST['quantity']);
    $uom                = (int)$_POST['uom'];
    $type               = $_POST['type'];
    $cgst_per           = floatval($_POST['cgst'] ?? 9);
    $sgst_per           = floatval($_POST['sgst'] ?? 9);
    $igst_per           = floatval($_POST['igst'] ?? 18);
    $remarks            = trim($_POST['remarks'] ?? '');

    $sitc_rate = $supply_rate = $itc_rate = 0;
    $sitc_amount = $supply_amount = $itc_amount = 0;

    if ($type === 'SITC') {
        $sitc_rate = floatval($_POST['sitc_rate'] ?? 0);
        $sitc_amount = $sitc_rate * $quantity;
    } elseif ($type === 'S+ITC') {
        $supply_rate = floatval($_POST['supply_rate'] ?? 0);
        $itc_rate = floatval($_POST['itc_rate'] ?? 0);
        $supply_amount = $supply_rate * $quantity;
        $itc_amount = $itc_rate * $quantity;
    }

    $basic_amount = ($sitc_amount > 0) ? $sitc_amount : ($supply_amount + $itc_amount);
    $gst_amount   = $basic_amount * ($cgst_per + $sgst_per + $igst_per) / 100;
    $grand_total  = $basic_amount + $gst_amount;

    if ($project_id <= 0 || empty($boq_code) || empty($system_description) || $quantity <= 0 || $uom <= 0 || empty($type)) {
        $error = "Please fill all required fields.";
    } else {
        mysqli_begin_transaction($conn);
        try {
            $stmt = $conn->prepare("INSERT INTO boq_master 
                (project_id, boq_code, system_description, quantity, uom, type, 
                 sitc_rate, sitc_amount, supply_rate, itc_rate, supply_amount, itc_amount, 
                 cgst, sgst, igst, basic_amount, gst_amount, grand_total, remarks, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

            $user_id = $_SESSION['user_id'];
            $stmt->bind_param("issidsddddddddddddsi",
                $project_id, $boq_code, $system_description, $quantity, $uom, $type,
                $sitc_rate, $sitc_amount, $supply_rate, $itc_rate,
                $supply_amount, $itc_amount, $cgst_per, $sgst_per, $igst_per,
                $basic_amount, $gst_amount, $grand_total, $remarks, $user_id
            );

            if ($stmt->execute()) {
                mysqli_commit($conn);
                $success = "BOQ added successfully! Code: <strong>$boq_code</strong>";
                $generated_code = generateBOQCode($conn);
            } else {
                throw new Exception($conn->error);
            }
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Error saving BOQ: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New BOQ</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;
        }

        .glass-container {
            max-width: 900px;
            margin: auto;
            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; }

        .section {
            background: rgba(255,255,255,0.07);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;
            padding: 30px;
            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;
        }
        input:focus, select:focus { border-color:var(--primary); box-shadow:0 0 0 4px rgba(168,85,247,0.25); }
        option{
            color:black;
        }
        .grid-2 { display:grid; grid-template-columns:repeat(auto-fit, minmax(280px,1fr)); gap:20px; }

        .totals-box {
            background: linear-gradient(135deg, rgba(168,85,247,0.2), rgba(192,132,252,0.15));
            border: 1px solid var(--accent);
            border-radius: 20px;
            padding: 25px;
            margin: 25px 0;
        }
        .total-row {
            display:flex; justify-content:space-between; padding:12px 0; font-size:1.1rem;
        }
        .total-row:last-child { font-weight:bold; font-size:1.3rem; border-top:1px solid rgba(255,255,255,0.2); padding-top:15px; }

        .submit-btn {
            width:100%; padding:18px; background:linear-gradient(135deg,var(--primary),var(--accent));
            color:white; border:none; border-radius:16px; font-size:1.1rem; font-weight:700; cursor:pointer;
            margin-top:20px;
        }

        .modal { display:none; position:fixed; z-index:10000; left:0; top:0; width:100%; height:100%; 
                  background:rgba(0,0,0,0.85); align-items:center; justify-content:center; }
        .modal-content { background:#1f2937; padding:30px; border-radius:20px; width:90%; max-width:420px; }

    .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; }
    </style>
</head>
<body>

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

<div class="glass-container">
    <div class="header">
        <a href="boq-management.php" style="color:#c4b5fd; position:absolute; left:30px; top:30px;">← Back</a>
        <h1><i class="fas fa-file-contract"></i> Add New 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="boqForm">

            <div class="section">
                <!-- Project & BOQ Code -->
                <div class="grid-2">
                    <div>
                        <label>Project <span class="required">*</span></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>
                        <label>BOQ Code</label>
                        <input type="text" name="boq_code" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                    </div>
                </div>

                <div style="margin-top:20px;">
                    <label>System Description <span class="required">*</span></label>
                    <textarea name="system_description" rows="3" required></textarea>
                </div>

                <div class="grid-2" style="margin-top:20px;">
                    <div>
                        <label>Quantity <span class="required">*</span></label>
                        <input type="number" step="0.001" name="quantity" id="quantity" oninput="calculateAll()" required>
                    </div>
                    <div>
                        <label>UOM <span class="required">*</span></label>
                        <select name="uom" id="uom" required>
                            <option value="">-- Select UOM --</option>
                            <?php while ($u = $uoms->fetch_assoc()): ?>
                                <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['uom_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                        <small onclick="openUOMModal()" style="color:var(--primary); cursor:pointer; text-decoration:underline;">+ Add New UOM</small>
                    </div>
                </div>

                <div style="margin-top:20px;">
                    <label>Rate Type <span class="required">*</span></label>
                    <select name="type" id="type" onchange="toggleFields()" required>
                        <option value="">-- Select Type --</option>
                        <option value="SITC">SITC</option>
                        <option value="S+ITC">Supply + ITC</option>
                    </select>
                </div>

                <div id="dynamicFields" class="grid-2" style="margin-top:20px;"></div>

                <div class="grid-2" style="margin-top:25px;">
                    <div><label>CGST (%)</label><input type="number" step="0.01" name="cgst" id="cgst" value="0" oninput="calculateAll()"></div>
                    <div><label>SGST (%)</label><input type="number" step="0.01" name="sgst" id="sgst" value="0" oninput="calculateAll()"></div>
                    <div><label>IGST (%)</label><input type="number" step="0.01" name="igst" id="igst" value="0" oninput="calculateAll()"></div>
                </div>

                <div style="margin-top:20px;">
                    <label>Remarks</label>
                    <textarea name="remarks" rows="3"></textarea>
                </div>
            </div>

            <!-- Totals Box -->
            <div class="totals-box" id="totalsBox">
                <div class="total-row"><span>Basic Amount:</span> <span id="basicTotal">₹ 0.00</span></div>
                <div class="total-row"><span>GST Amount:</span> <span id="gstTotal">₹ 0.00</span></div>
                <div class="total-row"><span><strong>Grand Total:</strong></span> <span id="grandTotal">₹ 0.00</span></div>
            </div>

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

<!-- UOM Modal -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <h3 style="text-align:center;margin-bottom:20px;">Add New UOM</h3>
        <input type="text" id="modalName" placeholder="e.g. Nos, Kg, Meter" style="margin-bottom:20px;">
        <div style="display:flex; gap:12px;">
            <button onclick="closeModal()" style="flex:1;padding:14px;background:#4b5563;color:white;border:none;border-radius:12px;">Cancel</button>
            <button onclick="saveUOM()" style="flex:1;padding:14px;background:var(--primary);color:white;border:none;border-radius:12px;">Save UOM</button>
        </div>
    </div>
</div>

<script>
function toggleFields() {
    const type = document.getElementById('type').value;
    const container = document.getElementById('dynamicFields');
    container.innerHTML = type === 'SITC' ? `
        <div><label>SITC Rate (₹) <span class="required">*</span></label>
            <input type="number" step="0.01" name="sitc_rate" id="sitc_rate" oninput="calculateAll()" required></div>
        <div><label>SITC Amount</label><input type="text" id="sitc_amount" readonly></div>` : type === 'S+ITC' ? `
        <div><label>Supply Rate (₹) <span class="required">*</span></label>
            <input type="number" step="0.01" name="supply_rate" id="supply_rate" oninput="calculateAll()" required></div>
        <div><label>ITC Rate (₹) <span class="required">*</span></label>
            <input type="number" step="0.01" name="itc_rate" id="itc_rate" oninput="calculateAll()" required></div>
        <div><label>Supply Amount</label><input type="text" id="supply_amount" readonly></div>
        <div><label>ITC Amount</label><input type="text" id="itc_amount" readonly></div>` : '';
}

function calculateAll() {
    const qty = parseFloat(document.getElementById('quantity').value) || 0;
    const type = document.getElementById('type').value;
    let basic = 0;

    if (type === 'SITC') {
        const rate = parseFloat(document.getElementById('sitc_rate')?.value) || 0;
        basic = rate * qty;
        document.getElementById('sitc_amount').value = basic.toFixed(2);
    } else if (type === 'S+ITC') {
        const sRate = parseFloat(document.getElementById('supply_rate')?.value) || 0;
        const iRate = parseFloat(document.getElementById('itc_rate')?.value) || 0;
        const sAmt = sRate * qty;
        const iAmt = iRate * qty;
        basic = sAmt + iAmt;
        if (document.getElementById('supply_amount')) document.getElementById('supply_amount').value = sAmt.toFixed(2);
        if (document.getElementById('itc_amount')) document.getElementById('itc_amount').value = iAmt.toFixed(2);
    }

    const cgst = parseFloat(document.getElementById('cgst').value) || 0;
    const sgst = parseFloat(document.getElementById('sgst').value) || 0;
    const igst = parseFloat(document.getElementById('igst').value) || 0;
    const gstAmt = basic * (cgst + sgst + igst) / 100;
    const grand = basic + gstAmt;

    document.getElementById('basicTotal').textContent = `₹ ${basic.toFixed(2)}`;
    document.getElementById('gstTotal').textContent = `₹ ${gstAmt.toFixed(2)}`;
    document.getElementById('grandTotal').textContent = `₹ ${grand.toFixed(2)}`;
}

function openUOMModal() { document.getElementById('addModal').style.display = 'flex'; }
function closeModal() { document.getElementById('addModal').style.display = 'none'; }

function saveUOM() {
    const name = document.getElementById('modalName').value.trim();
    if (!name) return alert("UOM name is required!");
    fetch('', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, 
        body: `action=add_uom&name=${encodeURIComponent(name)}` 
    }).then(r=>r.json()).then(data => {
        if (data.success) {
            const sel = document.getElementById('uom');
            sel.add(new Option(data.name, data.id));
            sel.value = data.id;
            closeModal();
        } else alert(data.message || "Failed");
    });
}
</script>
</body>
</html>

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