<?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'];
$full_name = $_SESSION['full_name'] ?? 'Store/Admin';

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

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

$prs = $conn->query("
    SELECT pr.id, pr.pr_date, pr.project_id, p.project_code, p.project_name
    FROM procurement_request pr
    LEFT JOIN project_master p ON pr.project_id = p.id
    WHERE pr.status = 'Approved'
    AND NOT EXISTS (SELECT 1 FROM purchase_order WHERE pr_id = pr.id)
    ORDER BY pr.pr_date DESC
");

$items_result = $conn->query("SELECT id, name, uom, model_no, hsn_sac FROM inventory_master ORDER BY name ASC");
$vendors_result = $conn->query("SELECT id, vendor_name FROM vendor_master ORDER BY vendor_name ASC");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $po_date         = $_POST['po_date'] ?? date('Y-m-d');
    $delivery_date   = $_POST['delivery_date'] ?? null;
    $vendor          = trim($_POST['vendor'] ?? '');
    $pr_id           = !empty($_POST['pr_id']) ? (int)$_POST['pr_id'] : null;
    $project_id      = !empty($_POST['project_id']) ? (int)$_POST['project_id'] : null;
    $ship_to_address = trim($_POST['ship_to_address'] ?? '');
    $amd_number      = trim($_POST['amd_number'] ?? '');
    $amd_date        = $_POST['amd_date'] ?? null;
    $offer_number    = trim($_POST['offer_number'] ?? '');
    $offer_date      = $_POST['offer_date'] ?? null;
    $terms           = trim($_POST['terms'] ?? '');
    $remarks         = trim($_POST['remarks'] ?? '');

    $item_ids        = $_POST['item_id'] ?? [];
    $model_nos       = $_POST['model_no'] ?? [];
    $descriptions    = $_POST['description'] ?? [];
    $hsn_sacs        = $_POST['hsn_sac'] ?? [];
    $quantities      = $_POST['quantity'] ?? [];
    $rates           = $_POST['rate'] ?? [];
    $cgst_rates      = $_POST['cgst_rate'] ?? [];
    $sgst_rates      = $_POST['sgst_rate'] ?? [];
    $igst_rates      = $_POST['igst_rate'] ?? [];

    if (empty($po_date) || empty($vendor)) {
        $error = "PO Date and Vendor are required.";
    } elseif (empty($item_ids) || count(array_filter($quantities, fn($q) => (float)$q > 0)) === 0) {
        $error = "Please add at least one item with quantity > 0.";
    } else {
        
        try {
            $conn->begin_transaction();

            // === INSERT PO HEADER ===
            $po_sql = "
                INSERT INTO purchase_order (
                    po_date, delivery_date, vendor, pr_id, project_id, ship_to_address,
                    amd_number, amd_date, offer_number, offer_date, terms_conditions, 
                    remarks, status, created_by, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Issued', ?, NOW())
            ";

            $po_stmt = $conn->prepare($po_sql);
            $po_stmt->bind_param("sssiisssssssi", 
                $po_date, $delivery_date, $vendor, $pr_id, $project_id, $ship_to_address,
                $amd_number, $amd_date, $offer_number, $offer_date, $terms, $remarks, $user_id
            );
            $po_stmt->execute();
            $po_id = $conn->insert_id;

            // === INSERT ITEMS ===
            $item_sql = "
                INSERT INTO purchase_order_items 
                (po_id, item_id, model_no, description, hsn_sac, ordered_qty, rate, unit, 
                 cgst_rate, sgst_rate, igst_rate)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ";
            $item_stmt = $conn->prepare($item_sql);

            $basic_total = 0;
            $total_gst   = 0;

                foreach ($item_ids as $idx => $item_id) {
                    $qty   = isset($quantities[$idx]) ? (float)$quantities[$idx] : 0;
                    $rate  = isset($rates[$idx]) ? (float)$rates[$idx] : 0;

                    if ($qty > 0 && $item_id > 0) {
                        $model_no    = trim($model_nos[$idx] ?? '');
                        $description = trim($descriptions[$idx] ?? '');
                        $hsn_sac     = trim($hsn_sacs[$idx] ?? '');
                        $unit        = 'NOS';

                        $cgst_rate = (float)($cgst_rates[$idx] ?? 0);
                        $sgst_rate = (float)($sgst_rates[$idx] ?? 0);
                        $igst_rate = (float)($igst_rates[$idx] ?? 0);

                        $basic_amount = $qty * $rate;

                    // ✅ Correct GST per row
                    $gst_rate = $cgst_rate + $sgst_rate + $igst_rate;
                    $gst_amount = $basic_amount * ($gst_rate / 100);

                    $item_stmt->bind_param("iisssddssdd", 
                    $po_id, $item_id, $model_no, $description, $hsn_sac, 
                    $qty, $rate, $unit, $cgst_rate, $sgst_rate, $igst_rate
                );
                $item_stmt->execute();

                $basic_total += $basic_amount;
                $total_gst   += $gst_amount; // ✅ accumulate GST
                }
            }

            $taxable_amount = $basic_total;
            $grand_total    = $taxable_amount + $total_gst;
            // Update header totals
            $update = $conn->prepare("UPDATE purchase_order 
                SET basic_total=?, taxable_amount=?, total_gst=?, grand_total=? 
                WHERE id=?");
            $update->bind_param("ddddi", $basic_total, $taxable_amount, $total_gst, $grand_total, $po_id);
            $update->execute();

            $conn->commit();

            $success = "Purchase Order created successfully!<br>
                        <strong>PO-" . str_pad($po_id, 5, '0', STR_PAD_LEFT) . "</strong>";

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to create PO: " . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Purchase Order</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: 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: 50px 40px;
            text-align: center;
            position: relative;
        }
        .header h1 {
            font-size: clamp(28px, 5vw, 42px);
            font-weight: 700;
        }

        .form-area { padding: 45px 40px; }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            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, textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(168,85,247,0.25);
        }

        .items-table {
            width: 100%;
            margin: 35px 0;
            border-collapse: collapse;
            background: rgba(255,255,255,0.05);
            border-radius: 16px;
            overflow: hidden;
        }

        .items-table th {
            background: rgba(168,85,247,0.3);
            padding: 16px 12px;
            text-align: left;
            font-weight: 600;
        }

        .items-table td {
            padding: 12px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .items-table input, .items-table select {
            padding: 10px 12px;
            font-size: 15px;
        }

        .remove-row {
            color: #f87171;
            font-size: 1.5rem;
            cursor: pointer;
            padding: 8px;
        }

        .add-row-btn {
            background: linear-gradient(135deg, #22c55e, #86efac);
            color: #052e16;
            border: none;
            padding: 14px 32px;
            border-radius: 16px;
            font-weight: 700;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }

        .totals-box {
            background: rgba(168,85,247,0.15);
            border: 2px solid var(--primary);
            border-radius: 20px;
            padding: 30px;
            margin: 35px 0;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            font-size: 1.1rem;
        }

        .grand-total {
            font-size: 1.85rem;
            font-weight: 700;
            color: #ddd6fe;
            border-top: 2px solid rgba(255,255,255,0.3);
            padding-top: 15px;
            margin-top: 10px;
        }

        .submit-btn {
            width: 100%;
            padding: 18px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 1.2rem;
            font-weight: 700;
            cursor: pointer;
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .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) {
            .glass-container { border-radius: 24px; }
            .header, .form-area { padding: 35px 25px; }
            .items-table th, .items-table td { padding: 10px 8px; font-size: 0.95rem; }
        }
        .suggestions {
        position: absolute;
        z-index: 1000;
        background: #1f2937;
        border: 1px solid var(--primary);
        border-radius: 12px;
        max-height: 280px;
        overflow-y: auto;
        width: 100%;
        margin-top: 4px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.6);
    }

    .suggestion-item {
        padding: 12px 16px;
        cursor: pointer;
    }

    .suggestion-item:hover {
        background: rgba(168, 85, 247, 0.3);
    }
    </style>
</head>
<body>

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

<div class="container">
    <div class="glass-container">

        <div class="header">
            <a href="po_list.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                ← Back to Purchase Orders
            </a>
            <h1><i class="fas fa-file-invoice"></i> Create New Purchase Order</h1>
            <p style="margin-top:12px; opacity:0.9;">Fill details and add items</p>
        </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">

                <!-- Header Fields -->
                <div class="form-grid">
                    <div class="form-group">
                        <label>PO Date <span class="required">*</span></label>
                        <input type="date" name="po_date" value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Expected Delivery Date</label>
                        <input type="date" name="delivery_date">
                    </div>
                    <div class="form-group">
                        <label>Vendor <span class="required">*</span></label>
                        <select name="vendor" required>
                            <option value="">-- Select Vendor --</option>
                            <?php while ($v = $vendors_result->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($v['vendor_name']) ?>"><?= htmlspecialchars($v['vendor_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>

                <!-- More fields -->
                <div class="form-grid">
                    <div class="form-group"><label>AMD Number</label><input type="text" name="amd_number"></div>
                    <div class="form-group"><label>AMD Date</label><input type="date" name="amd_date"></div>
                    <div class="form-group"><label>Offer Number</label><input type="text" name="offer_number"></div>
                    <div class="form-group"><label>Offer Date</label><input type="date" name="offer_date"></div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Link Approved PR</label>
                        <select name="pr_id">
                            <option value="">None (Direct PO)</option>
                            <?php while ($pr = $prs->fetch_assoc()): ?>
                                <option value="<?= $pr['id'] ?>">
                                    PR-<?= str_pad($pr['id'],5,'0',STR_PAD_LEFT) ?> - <?= htmlspecialchars($pr['project_name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>For Project</label>
                        <select name="project_id">
                            <option value="">Central / General Purchase</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>

                <div class="form-group">
                    <label>Ship To Address</label>
                    <textarea name="ship_to_address" rows="2" placeholder="Full delivery address..."></textarea>
                </div>

                <h3 style="margin:40px 0 15px; color:#ddd6fe;">Purchase Order Items</h3>

                <table class="items-table" id="itemsTable">
                    <thead>
                        <tr>
                            <th>Model No</th>
                            <th>Description</th>
                            <th>HSN/SAC</th>
                            <th>Qty</th>
                            <th>Rate (₹)</th>
                            <th>UOM</th>
                            <th>Basic Amount</th>
                            <th>CGST %</th>
                            <th>SGST %</th>
                            <th>IGST %</th>
                            <th>Line Total</th>
                            <th style="width:50px;"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody"></tbody>
                </table>

                <button type="button" class="add-row-btn" onclick="addItemRow()">
                    <i class="fas fa-plus"></i> Add New Item
                </button>

                <!-- Totals -->
                <div class="totals-box">
                    <div class="total-row"><span>Basic Total</span><span id="basicTotal">₹ 0.00</span></div>
                    <div class="total-row"><span>Taxable Amount</span><span id="taxableTotal">₹ 0.00</span></div>
                    <div class="total-row"><span>Total GST</span><span id="gstTotal">₹ 0.00</span></div>
                    <div class="total-row grand-total"><span>Grand Total</span><span id="grandTotal">₹ 0.00</span></div>
                </div>

                <div class="form-group"><label>Terms & Conditions</label>
                    <textarea name="terms" rows="3"></textarea>
                </div>
                <div class="form-group"><label>Remarks / Notes</label>
                    <textarea name="remarks" rows="2"></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-file-invoice"></i> Create Purchase Order
                </button>
            </form>
        </div>
    </div>
</div>
    <script>
    document.addEventListener('DOMContentLoaded', () => addItemRow());

    function addItemRow() {
        const tbody = document.getElementById('itemsBody');
        const row = tbody.insertRow();

        row.innerHTML = `
        <td>
            <input type="text" name="model_no[]" placeholder="Type Model No" onkeyup="searchByModel(this)">
            <div class="suggestions" style="display:none;"></div>
        </td>
        <td><input type="text" name="description[]" placeholder="Item Description"></td>
        <td><input type="text" name="hsn_sac[]" placeholder="HSN/SAC"></td>
        <td><input type="number" name="quantity[]" step="0.001" min="0.001" placeholder="0" required oninput="calculateRow(this)"></td>
        <td><input type="number" name="rate[]" step="0.01" min="0" placeholder="0.00" required oninput="calculateRow(this)"></td>
        <td><input type="text" name="uom[]" readonly placeholder="UOM"></td>
        <td class="basic-amount">₹ 0.00</td>
        <td><input type="number" name="cgst_rate[]" step="0.01" value="9" oninput="calculateRow(this)"></td>
        <td><input type="number" name="sgst_rate[]" step="0.01" value="9" oninput="calculateRow(this)"></td>
        <td><input type="number" name="igst_rate[]" step="0.01" value="18" oninput="calculateRow(this)"></td>
        <td class="line-total">₹ 0.00</td>
        <td><span class="remove-row" onclick="removeRow(this)"><i class="fas fa-trash"></i></span></td>
    `;
    }

    function searchByModel(input) {
        const model = input.value.trim();
        const row = input.closest('tr');
        const suggestionsDiv = row.querySelector('.suggestions');

        if (model.length < 2) {
            suggestionsDiv.style.display = 'none';
            return;
        }

        fetch(`search_by_model.php?model=${encodeURIComponent(model)}`)
            .then(r => r.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>${item.model_no}</strong> — ${item.name}`;
                        div.onclick = () => {
                            selectModelItem(row, item);
                            suggestionsDiv.style.display = 'none';
                        };
                        suggestionsDiv.appendChild(div);
                    });
                    suggestionsDiv.style.display = 'block';
                } else {
                    suggestionsDiv.style.display = 'none';
                }
            });
    }

    function selectModelItem(row, item) {
        row.querySelector('input[name="model_no[]"]').value = item.model_no || '';
        row.querySelector('input[name="description[]"]').value = item.name || '';
        row.querySelector('input[name="hsn_sac[]"]').value = item.hsn_sac || '';
        row.querySelector('input[name="uom[]"]').value = item.uom || 'NOS';

        // Important: Set item_id so it gets saved in database
        let hidden = row.querySelector('input[name="item_id[]"]');
        if (!hidden) {
            hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = 'item_id[]';
            row.appendChild(hidden);
        }
        hidden.value = item.id;

        calculateRow(row.querySelector('input[name="quantity[]"]'));
    }

    function calculateRow(input) {
        const row = input.closest('tr');
        const qty = parseFloat(row.querySelector('input[name="quantity[]"]').value) || 0;
        const rate = parseFloat(row.querySelector('input[name="rate[]"]').value) || 0;
        const cgst = parseFloat(row.querySelector('input[name="cgst_rate[]"]').value) || 0;
        const sgst = parseFloat(row.querySelector('input[name="sgst_rate[]"]').value) || 0;
        const igst = parseFloat(row.querySelector('input[name="igst_rate[]"]').value) || 0;

        const basic = qty * rate;
        const gstAmount = basic * ((cgst + sgst + igst) / 100);
        const lineTotal = basic + gstAmount;

        row.querySelector('.basic-amount').textContent = `₹ ${basic.toFixed(2)}`;
        row.querySelector('.line-total').textContent = `₹ ${lineTotal.toFixed(2)}`;

        updateTotals();
    }

    function updateTotals() {
    let basicTotal = 0;
    let totalGST = 0;

    document.querySelectorAll('#itemsBody tr').forEach(row => {
        const qty  = parseFloat(row.querySelector('input[name="quantity[]"]').value) || 0;
        const rate = parseFloat(row.querySelector('input[name="rate[]"]').value) || 0;

        const cgst = parseFloat(row.querySelector('input[name="cgst_rate[]"]').value) || 0;
        const sgst = parseFloat(row.querySelector('input[name="sgst_rate[]"]').value) || 0;
        const igst = parseFloat(row.querySelector('input[name="igst_rate[]"]').value) || 0;

        const basic = qty * rate;
        const gstRate = cgst + sgst + igst;
        const gstAmount = basic * (gstRate / 100);

        basicTotal += basic;
        totalGST += gstAmount;
    });

    const taxable = basicTotal;
    const grand = taxable + totalGST;

    document.getElementById('basicTotal').textContent = `₹ ${basicTotal.toFixed(2)}`;
    document.getElementById('taxableTotal').textContent = `₹ ${taxable.toFixed(2)}`;
    document.getElementById('gstTotal').textContent = `₹ ${totalGST.toFixed(2)}`;
    document.getElementById('grandTotal').textContent = `₹ ${grand.toFixed(2)}`;
}
function removeRow(btn) {
    btn.closest('tr').remove();
    updateTotals();
}
    </script>

</body>

</html>

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