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

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

// Fetch Projects
$project_result = $conn->query("SELECT id, project_code, project_name FROM project_master ORDER BY project_name ASC");

// Fetch UOMs
$uom_result = $conn->query("SELECT id, uom_name FROM uom_tbl ORDER BY uom_name ASC");
$uoms = $uom_result->fetch_all(MYSQLI_ASSOC);

// ====================== 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);
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'id' => $conn->insert_id, 'name' => $name]);
    } else {
        echo json_encode(['success' => false, 'message' => $conn->error]);
    }
    exit;
}

// ====================== FORM SUBMISSION ======================
if ($_SERVER["REQUEST_METHOD"] === "POST" && !isset($_POST['action'])) {
    $project_id = (int)($_POST['project_id'] ?? 0);

    if ($project_id <= 0) {
        $error = "Please select a project.";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Insert Planning Header (you can expand this table as needed)
            $stmt = $conn->prepare("INSERT INTO planning_master (project_id, created_by, created_at) VALUES (?, ?, NOW())");
            $user_id = $_SESSION['user_id'] ?? 1;
            $stmt->bind_param("ii", $project_id, $user_id);
            $stmt->execute();
            $planning_id = $conn->insert_id;

            // ====================== INSERT BUDGET ITEMS ======================
            if (!empty($_POST['budget'])) {
                $budget_stmt = $conn->prepare("INSERT INTO planning_budget 
                    (planning_id, bbu_item_no, name, quantity, uom, type, sitc_rate, sitc_amount, 
                     supply_rate, itc_rate, supply_amount, itc_amount, cgst, sgst, igst, description) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

                foreach ($_POST['budget'] as $item) {
                    $bbu_item_no   = trim($item['bbu_item_no'] ?? '');
                    $name          = trim($item['name'] ?? '');
                    $quantity      = floatval($item['quantity'] ?? 0);
                    $uom           = (int)($item['uom'] ?? 0);
                    $type          = trim($item['type'] ?? '');
                    $sitc_rate     = floatval($item['sitc_rate'] ?? 0);
                    $sitc_amount   = floatval($item['sitc_amount'] ?? 0);
                    $supply_rate   = floatval($item['supply_rate'] ?? 0);
                    $itc_rate      = floatval($item['itc_rate'] ?? 0);
                    $supply_amount = floatval($item['supply_amount'] ?? 0);
                    $itc_amount    = floatval($item['itc_amount'] ?? 0);
                    $cgst          = floatval($item['cgst'] ?? 0);
                    $sgst          = floatval($item['sgst'] ?? 0);
                    $igst          = floatval($item['igst'] ?? 0);
                    $description   = trim($item['description'] ?? '');

                    if (empty($name) || $quantity <= 0) continue;

                    $budget_stmt->bind_param("ississddddddddds", 
                        $planning_id, $bbu_item_no, $name, $quantity, $uom, $type,
                        $sitc_rate, $sitc_amount, $supply_rate, $itc_rate,
                        $supply_amount, $itc_amount, $cgst, $sgst, $igst, $description
                    );
                    $budget_stmt->execute();
                }
            }

            // ====================== INSERT SCHEDULE ITEMS ======================
            if (!empty($_POST['schedule'])) {
                $schedule_stmt = $conn->prepare("INSERT INTO planning_schedule 
                    (planning_id, milestone, start_date, end_date, uom, remarks) 
                    VALUES (?, ?, ?, ?, ?, ?)");

                foreach ($_POST['schedule'] as $sch) {
                    $milestone  = trim($sch['milestone'] ?? '');
                    $start_date = $sch['start_date'] ?? null;
                    $end_date   = $sch['end_date'] ?? null;
                    $uom        = (int)($sch['uom'] ?? 0);
                    $remarks    = trim($sch['remarks'] ?? '');

                    if (empty($milestone)) continue;

                    $schedule_stmt->bind_param("isssis", 
                        $planning_id, $milestone, $start_date, $end_date, $uom, $remarks
                    );
                    $schedule_stmt->execute();
                }
            }

            mysqli_commit($conn);
            $success = "Planning saved successfully! Project ID: " . $planning_id;

        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Error saving planning: " . $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 Planning</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;
        min-height: 100vh;
        background: linear-gradient(135deg, rgba(0, 0, 0, 0.78), rgba(0, 0, 0, 0.92)), url('../background.jpeg') center/cover no-repeat fixed;
        color: #f1f5f9;
        padding: 20px;
    }

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

    .header h1 {
        font-size: clamp(32px, 6vw, 44px);
        font-weight: 700;
        background: linear-gradient(to right, #e0bbff, #c084fc);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .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: 32px;
        margin-bottom: 35px;
    }

    .item-row,
    .schedule-row {
        background: rgba(255, 255, 255, 0.06);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 18px;
        padding: 28px;
        margin-bottom: 25px;
        position: relative;
    }

    .remove-btn {
        position: absolute;
        top: 18px;
        right: 18px;
        background: rgba(239, 68, 68, 0.4);
        color: white;
        border: none;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        font-size: 24px;
        cursor: pointer;
    }

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

    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 {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(168, 85, 247, 0.25);
    }

    .add-row-btn,
    .submit-btn {
        width: 100%;
        padding: 18px;
        border-radius: 16px;
        font-weight: 700;
        font-size: 17px;
        cursor: pointer;
        margin: 25px 0;
    }

    .add-row-btn {
        background: rgba(255, 255, 255, 0.06);
        border: 2px dashed #c084fc;
        color: white;
    }

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

    .totals-box {
        background: linear-gradient(135deg, rgba(168, 85, 247, 0.15), rgba(192, 132, 252, 0.12));
        border: 1px solid var(--accent);
        border-radius: 20px;
        padding: 28px;
        margin: 30px 0;
    }

    .total-row {
        display: flex;
        justify-content: space-between;
        padding: 12px 0;
        font-size: 1.15rem;
        border-bottom: 1px solid rgba(255, 255, 255, 0.15);
    }

    .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;
    }

    .modal {
        display: none;
        position: fixed;
        z-index: 2000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        align-items: center;
        justify-content: center;
    }

    .modal-content {
        background: #1f2937;
        padding: 32px;
        border-radius: 20px;
        width: 90%;
        max-width: 420px;
    }

    .add-option-btn {
        margin-top: 6px;
        font-size: 13px;
        color: #a855f7;
        cursor: pointer;
    }
    </style>
</head>

<body>
<?php include '../config/header.php'; ?>
    <div class="glass-container">
        <div class="header">
            <h1><i class="fas fa-file-invoice"></i> Add Planning</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 action="" method="POST" id="planningForm">
                <!-- Project -->
                <div class="section">
                    <label for="project_id"><i class="fas fa-building"></i> Select Project <span
                            class="required">*</span></label>
                    <select name="project_id" id="project_id" required>
                        <option value="">-- Choose Project --</option>
                        <?php while ($p = $project_result->fetch_assoc()): ?>
                        <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['project_name']) ?>
                            (<?= htmlspecialchars($p['project_code'] ?? '') ?>)</option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <!-- Budget Section -->
                <div class="section">
                    <h2 style="margin-bottom:20px;"><i class="fas fa-money-bill-wave"></i> Budget</h2>
                    <div class="items-container" id="itemsContainer"></div>
                    <div class="add-row-btn" onclick="addNewBudgetRow()">
                        <i class="fas fa-plus-circle"></i> Add Another Material
                    </div>
                </div>

                <!-- Schedule Section -->
                <div class="section">
                    <h2 style="margin-bottom:20px;"><i class="fas fa-calendar-alt"></i> Schedule</h2>
                    <div class="schedule-container" id="scheduleContainer"></div>
                    <div class="add-row-btn" onclick="addNewScheduleRow()">
                        <i class="fas fa-plus-circle"></i> Add Another Milestone
                    </div>
                </div>

                <div class="totals-box" id="totalsBox" style="display:none;">
                    <div class="total-row"><span>Basic Total:</span> <span id="basicTotal">₹ 0.00</span></div>
                    <div class="total-row"><span>GST Total:</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 Planning
                </button>
            </form>
        </div>
    </div>

    <!-- UOM Modal -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <div style="font-size:20px;font-weight:600;margin-bottom:20px;text-align:center;" id="modalTitle">Add New
                UOM</div>
            <input type="text" id="modalName" placeholder="Enter UOM Name (e.g. Nos, Kg, Ltr)">
            <div style="display:flex;gap:12px;margin-top:25px;">
                <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:#a855f7;color:white;border:none;border-radius:12px;">Save
                    UOM</button>
            </div>
        </div>
    </div>

    <script>
    let rowCount = 0;
    let scheduleCount = 0;
    let uomsList = <?= json_encode($uoms) ?>;

    function escapeHtml(str) {
        return str ? str.replace(/[&<>"']/g, m => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        })[m]) : '';
    }

    // Budget Row
    function addNewBudgetRow() {
        rowCount++;
        let uomOptions = '<option value="">Select UOM</option>';
        uomsList.forEach(u => uomOptions += `<option value="${u.id}">${escapeHtml(u.uom_name)}</option>`);

        const html = `
        <div class="item-row" id="budget-row-${rowCount}">
            <button type="button" class="remove-btn" onclick="removeBudgetRow(${rowCount})">×</button>
            <div class="form-grid">
                <div><label>BBU Item Number</label><input type="text" name="budget[${rowCount}][bbu_item_no]"></div>
                <div><label>Material Name <span class="required">*</span></label><input type="text" name="budget[${rowCount}][name]" required></div>
                <div><label>Quantity <span class="required">*</span></label><input type="number" step="0.001" name="budget[${rowCount}][quantity]" class="quantity" oninput="calculateRow(this)" required></div>
                
                <div>
                    <label>UOM <span class="required">*</span></label>
                    <select name="budget[${rowCount}][uom]" class="uom-select">${uomOptions}</select>
                    <div class="add-option-btn" onclick="openUOMModal(this)">+ Add new UOM</div>
                </div>

                <div>
                    <label>Rate Type <span class="required">*</span></label>
                    <select name="budget[${rowCount}][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-${rowCount}"></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[${rowCount}][cgst]" value="0" oninput="calculateRow(this)"></div>
                    <div><label>SGST (%)</label><input type="number" step="0.01" name="budget[${rowCount}][sgst]" value="0" oninput="calculateRow(this)"></div>
                    <div><label>IGST (%)</label><input type="number" step="0.01" name="budget[${rowCount}][igst]" value="0" oninput="calculateRow(this)"></div>
                </div>

                <div class="full-width"><label>Description</label><textarea name="budget[${rowCount}][description]" rows="2"></textarea></div>
            </div>
        </div>`;

        document.getElementById('itemsContainer').insertAdjacentHTML('beforeend', html);
        document.getElementById('totalsBox').style.display = 'block';
    }

    function toggleBudgetFields(select) {
        const rowId = select.closest('.item-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);

        calculateTotals();
    }

    function calculateTotals() {
        let basic = 0;
        let totalGst = 0;

        document.querySelectorAll('.item-row').forEach(row => {
            const sitc = parseFloat(row.querySelector('[name*="sitc_amount"]')?.value) || 0;
            const supply = parseFloat(row.querySelector('[name*="supply_amount"]')?.value) || 0;
            const itc = parseFloat(row.querySelector('[name*="itc_amount"]')?.value) || 0;

            const cgst = parseFloat(row.querySelector('[name*="cgst"]')?.value) || 0;
            const sgst = parseFloat(row.querySelector('[name*="sgst"]')?.value) || 0;
            const igst = parseFloat(row.querySelector('[name*="igst"]')?.value) || 0;

            // Row basic
            const rowBasic = sitc || (supply + itc);

            // Row GST
            const rowGst = rowBasic * (cgst + sgst + igst) / 100;

            basic += rowBasic;
            totalGst += rowGst;
        });

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

    // Schedule functions remain the same as before
    function addNewScheduleRow() {
        scheduleCount++;
        let uomOptions = '<option value="">Select UOM</option>';
        uomsList.forEach(u => uomOptions += `<option value="${u.id}">${escapeHtml(u.uom_name)}</option>`);

        const html = `
        <div class="schedule-row" id="schedule-row-${scheduleCount}">
            <button type="button" class="remove-btn" onclick="removeScheduleRow(${scheduleCount})">×</button>
            <div class="form-grid">
                <div><label>Milestone <span class="required">*</span></label><input type="text" name="schedule[${scheduleCount}][milestone]" required></div>
                <div><label>Start Date <span class="required">*</span></label><input type="date" name="schedule[${scheduleCount}][start_date]" required></div>
                <div><label>End Date <span class="required">*</span></label><input type="date" name="schedule[${scheduleCount}][end_date]" required></div>
                <div>
                    <label>UOM</label>
                    <select name="schedule[${scheduleCount}][uom]">${uomOptions}</select>
                    <div class="add-option-btn" onclick="openUOMModal(this)">+ Add new UOM</div>
                </div>
                <div class="full-width"><label>Remarks</label><textarea name="schedule[${scheduleCount}][remarks]" rows="2"></textarea></div>
            </div>
        </div>`;

        document.getElementById('scheduleContainer').insertAdjacentHTML('beforeend', html);

    }

    function removeBudgetRow(id) {
        document.getElementById(`budget-row-${id}`).remove();
        calculateTotals();
    }

    function removeScheduleRow(id) {
        document.getElementById(`schedule-row-${id}`).remove();
    }

    // ====================== UOM Modal ======================
    let currentRow = null;

    function openUOMModal(btn) {
        currentRow = btn.closest('.item-row');
        document.getElementById('modalTitle').textContent = 'Add New UOM';
        document.getElementById('modalName').value = '';
        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) {
                    uomsList.push({
                        id: data.id,
                        uom_name: data.name
                    });

                    document.querySelectorAll('.uom-select').forEach(select => {
                        const opt = document.createElement('option');
                        opt.value = data.id;
                        opt.textContent = escapeHtml(data.name);
                        select.appendChild(opt);
                    });

                    if (currentRow) {
                        const sel = currentRow.querySelector('.uom-select');
                        if (sel) sel.value = data.id;
                    }
                    closeModal();
                } else {
                    alert(data.message || "Failed to add UOM");
                }
            });
    }

    window.onload = () => {
        addNewBudgetRow();
        addNewScheduleRow();
    };
    </script>
</body>

</html>