<?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']) || !in_array($_SESSION['role'], ['admin', 'project manager', 'store manager'])) {
    header("Location: ../login.php");
    exit();
}

$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'] ?? '');
    $response = ['success' => false, 'message' => ''];

    if (empty($name)) {
        $response['message'] = "UOM name is required.";
    } else {
        $stmt = $conn->prepare("INSERT INTO uom_tbl (uom_name) VALUES (?)");
        $stmt->bind_param("s", $name);
        if ($stmt->execute()) {
            $response['success'] = true;
            $response['id'] = $conn->insert_id;
            $response['name'] = $name;
        } else {
            $response['message'] = "Failed to add UOM.";
        }
    }
    echo json_encode($response);
    exit;
}

// ====================== Main Form Submission ======================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    $project_id = (int)($_POST['project_id'] ?? 0);
    $items = $_POST['items'] ?? [];

    if ($project_id <= 0) {
        $error = "Please select a project.";
    } elseif (empty($items) || !is_array($items)) {
        $error = "Please add at least one material.";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Insert PO Header
            $stmt = $conn->prepare("INSERT INTO purchase_order_from_client (project_id, created_by, created_at) VALUES (?, ?, NOW())");
            $stmt->bind_param("ii", $project_id, $_SESSION['user_id']);
            $stmt->execute();
            $po_id = $conn->insert_id;

            $order_number = "POCL-" . str_pad($po_id, 5, '0', STR_PAD_LEFT);
            $conn->query("UPDATE purchase_order_from_client SET order_number = '$order_number' WHERE id = $po_id");

            // Insert Items
            $item_stmt = $conn->prepare("
                INSERT INTO purchase_order_from_client_items 
                (purchase_order_from_client_id, bbu_item_no, name, quantity, uom, type,
                 sitc_rate, sitc_amount, supply_rate, itc_rate, supply_amount, itc_amount,
                 c_gst, s_gst, i_gst, description, remarks)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");

            $basic_total = 0;

            foreach ($items as $item) {
                $bbu_item_no   = trim($item['bbu_item_no'] ?? '');
                $name          = trim($item['name'] ?? '');
                $quantity      = floatval($item['quantity'] ?? 0);
                $uom_id        = (int)($item['uom'] ?? 0);
                $type          = $item['type'] ?? '';

                $sitc_rate     = !empty($item['sitc_rate']) ? floatval($item['sitc_rate']) : null;
                $sitc_amount   = !empty($item['sitc_amount']) ? floatval($item['sitc_amount']) : null;
                $supply_rate   = !empty($item['supply_rate']) ? floatval($item['supply_rate']) : null;
                $itc_rate      = !empty($item['itc_rate']) ? floatval($item['itc_rate']) : null;
                $supply_amount = !empty($item['supply_amount']) ? floatval($item['supply_amount']) : null;
                $itc_amount    = !empty($item['itc_amount']) ? floatval($item['itc_amount']) : null;

                $c_gst = floatval($item['c_gst'] ?? 0);
                $s_gst = floatval($item['s_gst'] ?? 0);
                $i_gst = floatval($item['i_gst'] ?? 0);

                $description = trim($item['description'] ?? '');
                $remarks     = trim($item['remarks'] ?? '');

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

                $row_total = ($sitc_amount > 0) ? $sitc_amount : ($supply_amount + $itc_amount);
                $basic_total += $row_total;

                $item_stmt->bind_param(
                    "issdssssdddddddss",
                    $po_id, $bbu_item_no, $name, $quantity, $uom_id, $type,
                    $sitc_rate, $sitc_amount, $supply_rate, $itc_rate,
                    $supply_amount, $itc_amount, $c_gst, $s_gst, $i_gst,
                    $description, $remarks
                );
                $item_stmt->execute();
            }

            $gst_total = $basic_total * 0.18;
            $grand_total = $basic_total + $gst_total;

            $update = $conn->prepare("UPDATE purchase_order_from_client 
                SET total_basic = ?, total_gst = ?, grand_total = ? 
                WHERE id = ?");
            $update->bind_param("dddi", $basic_total, $gst_total, $grand_total, $po_id);
            $update->execute();

            mysqli_commit($conn);
            $success = "Purchase Order created successfully!<br><strong>Order No: $order_number</strong>";

        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Error: " . $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 Purchase Order from Client</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }
        .container { max-width: 1450px; margin: auto; }
        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
        }
        .header h1 {
            font-size: clamp(28px, 5.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: 28px;
            margin-bottom: 30px;
        }

        label {
            display: block;
            margin-bottom: 9px;
            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: 14px;
            color: white;
            font-size: 15.5px;
        }
        input:focus, select:focus, textarea:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(168,85,247,0.25);
            background: rgba(255,255,255,0.16);
        }

        .item-row {
            position: relative;
            background: rgba(255,255,255,0.06);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 18px;
            padding: 25px;
            margin-bottom: 25px;
        }
        .remove-btn {
            position: absolute;
            top: 15px;
            right: 15px;
            background: rgba(239,68,68,0.3);
            color: #fda4af;
            border: none;
            width: 38px;
            height: 38px;
            border-radius: 50%;
            font-size: 24px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .remove-btn:hover {
            background: #ef4444;
            color: white;
            transform: rotate(90deg);
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
        }
        .full-width { grid-column: 1 / -1; }

        .dynamic-fields {
            display: none;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px dashed rgba(168,85,247,0.4);
        }

        .add-uom-link {
            color: var(--primary);
            font-size: 0.9rem;
            cursor: pointer;
            margin-top: 6px;
            display: inline-block;
        }

        .add-row-btn, .submit-btn {
            width: 100%;
            padding: 18px;
            border-radius: 18px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            margin: 25px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }
        .add-row-btn {
            background: rgba(255,255,255,0.06);
            color: white;
            border: 2px dashed rgba(192,132,252,0.6);
        }
        .submit-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            box-shadow: 0 15px 40px rgba(168,85,247,0.4);
        }

        .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: 22px;
            padding: 30px;
            margin: 40px 0;
        }
        .total-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            font-size: 1.1rem;
        }
        .total-row:last-child {
            font-size: 1.5rem;
            font-weight: 700;
            color: #ddd6fe;
            border-top: 2px solid rgba(255,255,255,0.2);
            padding-top: 18px;
            margin-top: 10px;
        }

        .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 */
        .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: 30px;
            border-radius: 20px;
            width: 90%;
            max-width: 420px;
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <h1><i class="fas fa-file-invoice"></i> Add Purchase Order from Client</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="poForm">

                <!-- Project Selection -->
                <div class="section">
                    <label>Project <span class="required">*</span></label>
                    <select name="project_id" required>
                        <option value="">-- Select 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>

                <!-- Items Container -->
                <div id="itemsContainer"></div>

                <button type="button" class="add-row-btn" onclick="addNewRow()">
                    <i class="fas fa-plus"></i> Add Another Material
                </button>

                <!-- Totals -->
                <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 (18%)</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 Purchase Order
                </button>
            </form>
        </div>
    </div>
</div>

<!-- Add New UOM Modal -->
<div id="uomModal" class="modal">
    <div class="modal-content">
        <h3 style="margin-bottom:20px; text-align:center;">Add New UOM</h3>
        <input type="text" id="newUomName" placeholder="e.g. Boxes, Rolls, Sets" style="margin-bottom:20px;">
        <div style="display:flex; gap:12px;">
            <button onclick="closeUomModal()" style="flex:1; padding:14px; background:#4b5563; color:white; border:none; border-radius:12px; cursor:pointer;">Cancel</button>
            <button onclick="saveNewUOM()" style="flex:1; padding:14px; background:var(--primary); color:white; border:none; border-radius:12px; cursor:pointer;">Save UOM</button>
        </div>
    </div>
</div>

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

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

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

                <div>
                    <label>Type <span class="required">*</span></label>
                    <select name="items[${rowCount}][type]" onchange="toggleDynamicFields(this)">
                        <option value="">Select Type</option>
                        <option value="SITC">SITC</option>
                        <option value="S+ITC">Supply + ITC</option>
                    </select>
                </div>

                <div class="dynamic-fields full-width" id="dynamic-${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="items[${rowCount}][c_gst]" value="0" oninput="calculateTotals()"></div>
                    <div><label>SGST (%)</label><input type="number" step="0.01" name="items[${rowCount}][s_gst]" value="0" oninput="calculateTotals()"></div>
                    <div><label>IGST (%)</label><input type="number" step="0.01" name="items[${rowCount}][i_gst]" value="0" oninput="calculateTotals()"></div>
                </div>

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

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

function toggleDynamicFields(select) {
    const rowId = select.closest('.item-row').id.split('-')[1];
    const container = document.getElementById(`dynamic-${rowId}`);

    if (select.value === 'SITC') {
        container.innerHTML = `
            <div><label>SITC Rate (₹)</label><input type="number" step="0.01" name="items[${rowId}][sitc_rate]" oninput="calculateRow(this)"></div>
            <div><label>SITC Amount (₹)</label><input type="number" step="0.01" name="items[${rowId}][sitc_amount]" readonly></div>`;
    } else if (select.value === 'S+ITC') {
        container.innerHTML = `
            <div><label>Supply Rate (₹)</label><input type="number" step="0.01" name="items[${rowId}][supply_rate]" oninput="calculateRow(this)"></div>
            <div><label>ITC Rate (₹)</label><input type="number" step="0.01" name="items[${rowId}][itc_rate]" oninput="calculateRow(this)"></div>
            <div><label>Supply Amount (₹)</label><input type="number" step="0.01" name="items[${rowId}][supply_amount]" readonly></div>
            <div><label>ITC Amount (₹)</label><input type="number" step="0.01" name="items[${rowId}][itc_amount]" readonly></div>`;
    } else {
        container.innerHTML = '';
    }
    container.style.display = select.value ? 'grid' : 'none';
    calculateTotals();
}

function calculateRow(el) {
    const row = el.closest('.item-row');
    const qty = parseFloat(row.querySelector('.qty-input')?.value) || 0;
    const sitcRate = parseFloat(row.querySelector('[name*="sitc_rate"]')?.value) || 0;
    const supplyRate = parseFloat(row.querySelector('[name*="supply_rate"]')?.value) || 0;
    const itcRate = parseFloat(row.querySelector('[name*="itc_rate"]')?.value) || 0;

    if (row.querySelector('[name*="sitc_amount"]')) row.querySelector('[name*="sitc_amount"]').value = (sitcRate * qty).toFixed(2);
    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 rowBasic = sitc || (supply + itc);

        // GST %
        const cgst = parseFloat(row.querySelector('[name*="c_gst"]')?.value) || 0;
        const sgst = parseFloat(row.querySelector('[name*="s_gst"]')?.value) || 0;
        const igst = parseFloat(row.querySelector('[name*="i_gst"]')?.value) || 0;

        let rowGST = 0;

        // If IGST is used → ignore CGST + SGST
        if (igst > 0) {
            rowGST = rowBasic * (igst / 100);
        } else {
            rowGST = rowBasic * ((cgst + sgst) / 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)}`;
}

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

// UOM Modal
let currentUomSelect = null;

function openUomModal(link) {
    currentUomSelect = link.previousElementSibling;
    document.getElementById('newUomName').value = '';
    document.getElementById('uomModal').style.display = 'flex';
}

function closeUomModal() {
    document.getElementById('uomModal').style.display = 'none';
}

function saveNewUOM() {
    const name = document.getElementById('newUomName').value.trim();
    if (!name) return alert("UOM name cannot be empty");

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

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

            if (currentUomSelect) currentUomSelect.value = data.id;
            closeUomModal();
        } else {
            alert(data.message || "Failed to add UOM");
        }
    });
}

window.onload = () => {
    addNewRow();   // Start with one row
};
</script>
</body>
</html>

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