<?php
session_start();
require_once("../config/config.php");

// Allowed roles (uncomment when ready)
// $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'] ?? 0;
$full_name = $_SESSION['full_name'] ?? 'Store/Admin';

function generateProjectCode(mysqli $conn): string {
    $sql = "SELECT grn_code FROM goods_received_note ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['grn_code'], 4) + 1;
    }
    return sprintf("GRN-%03d", $next);
}

$success = "";
$error = "";
$generated_code = generateProjectCode($conn);


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

$pos = $conn->query("
    SELECT 
        po.id, po.po_date, po.vendor,
        p.project_code, p.project_name
    FROM purchase_order po
    LEFT JOIN project_master p ON po.project_id = p.id
    WHERE po.status = 'Issued'
    ORDER BY po.po_date DESC
");

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

$vendors_result = $conn->query("SELECT id, vendor_name FROM vendor_master ORDER BY vendor_name ASC");

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $grn_date      = $_POST['grn_date'] ?? date('Y-m-d');
    $vendor        = trim($_POST['vendor'] ?? '');
    $po_id         = !empty($_POST['po_id']) ? (int)$_POST['po_id'] : null;
    $project_id    = !empty($_POST['project_id']) ? (int)$_POST['project_id'] : null;
    $invoice_no    = trim($_POST['invoice_no'] ?? '');
    $remarks       = trim($_POST['remarks'] ?? '');

    $item_ids      = $_POST['item_id'] ?? [];
    $quantities    = $_POST['quantity'] ?? [];
    $rates         = $_POST['rate'] ?? [];
    $batches       = $_POST['batch'] ?? [];

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

            // Insert GRN Header
            $grn_sql = "
                INSERT INTO goods_received_note (
                    grn_date, vendor, po_id, invoice_number,
                    project_id, remarks, status, received_by, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, 'Received', ?, NOW())
            ";

            $grn_stmt = $conn->prepare($grn_sql);
            $grn_stmt->bind_param("ssisisi", $grn_date, $vendor, $po_id, $invoice_no, $project_id, $remarks, $user_id);
            $grn_stmt->execute();
            $grn_id = $conn->insert_id;

            // Insert GRN Items
            $item_sql = "
                INSERT INTO goods_received_note_items 
                (grn_id, item_id, received_qty, rate, batch_no, unit) 
                VALUES (?, ?, ?, ?, ?, ?)
            ";
            $item_stmt = $conn->prepare($item_sql);

            // Update Project Inventory
            $stock_sql = "
                INSERT INTO project_inventory (project_id, item_id, current_stock, avg_rate, last_updated)
                VALUES (?, ?, ?, ?, NOW())
                ON DUPLICATE KEY UPDATE 
                    current_stock = current_stock + VALUES(current_stock),
                    avg_rate = (current_stock * avg_rate + VALUES(current_stock) * VALUES(avg_rate)) / (current_stock + VALUES(current_stock)),
                    last_updated = NOW()
            ";
            $stock_stmt = $conn->prepare($stock_sql);

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

                if ($qty > 0 && $item_id > 0) {
                    // Get unit
                    $unit_q = $conn->prepare("SELECT uom FROM inventory_master WHERE id = ?");
                    $unit_q->bind_param("i", $item_id);
                    $unit_q->execute();
                    $unit = $unit_q->get_result()->fetch_assoc()['uom'] ?? 'NOS';
                    $unit_q->close();

                    // Insert into GRN items
                    $item_stmt->bind_param("iidids", $grn_id, $item_id, $qty, $rate, $batch, $unit);
                    $item_stmt->execute();

                    // Update stock only if project is selected
                    if ($project_id > 0) {
                        $stock_stmt->bind_param("iidd", $project_id, $item_id, $qty, $rate);
                        $stock_stmt->execute();
                    }
                }
            }

            // Optional: Update PO status to Received
            // if ($po_id) {
            //     $conn->query("UPDATE purchase_order SET status = 'Received' WHERE id = $po_id");
            // }

            $conn->commit();

            $success = "GRN created successfully!<br>
                        <strong>GRN-" . str_pad($grn_id, 5, '0', STR_PAD_LEFT) . "</strong>";

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to create GRN: " . $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 Goods Received Note (GRN)</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #8b5cf6;
            --success: #22c55e;
            --danger: #ef4444;
            --glass: rgba(255,255,255,0.09);
            --border: rgba(255,255,255,0.18);
        }
        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: linear-gradient(rgba(0,0,0,0.8), rgba(0,0,0,0.95)), 
                        url('../background.jpeg') center/cover fixed;
            color: white;
            margin: 0;
            padding: 20px 15px;
        }
        .container { max-width: 1180px; margin: 0 auto; }

        .back {
            color: #c4b5fd;
            text-decoration: none;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 20px;
        }
        .back:hover { color: white; }

        h1 { margin: 0 0 12px; font-size: 2.2rem; }

        .form-area {
            background: var(--glass);
            backdrop-filter: blur(16px);
            border: 1px solid var(--border);
            border-radius: 18px;
            padding: 40px;
            box-shadow: 0 15px 40px rgba(0,0,0,0.5);
        }

        .form-group { margin-bottom: 24px; }
        label {
            display: block;
            margin-bottom: 9px;
            font-weight: 600;
            font-size: 1.05rem;
        }
        input, select, textarea {
            width: 100%;
            padding: 14px 18px;
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 12px;
            color: white;
            font-size: 1.02rem;
        }
        textarea { min-height: 120px; resize: vertical; }

        .items-table {
            width: 100%;
            margin: 30px 0 25px;
            border-collapse: collapse;
        }
        .items-table th, .items-table td {
            padding: 14px 12px;
            border-bottom: 1px solid var(--border);
            text-align: left;
        }
        .items-table th { background: rgba(255,255,255,0.13); font-weight: 600; }

        .remove-row {
            color: var(--danger);
            cursor: pointer;
            font-size: 1.4rem;
        }

        .add-row-btn {
            background: rgba(34,197,94,0.25);
            color: #86efac;
            border: 1px solid rgba(34,197,94,0.5);
            padding: 12px 30px;
            border-radius: 12px;
            cursor: pointer;
            font-weight: 600;
        }

        .submit-btn {
            background: linear-gradient(135deg, var(--primary), #a78bfa);
            color: white;
            border: none;
            padding: 17px;
            border-radius: 12px;
            font-size: 1.15rem;
            font-weight: 700;
            width: 100%;
            cursor: pointer;
            margin-top: 15px;
        }
        .submit-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 35px rgba(139,92,246,0.5);
        }

        .message {
            padding: 16px 22px;
            border-radius: 12px;
            margin-bottom: 25px;
            font-weight: 500;
        }
        .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; }

        .grand-total {
            font-size: 1.55rem;
            font-weight: 700;
            text-align: right;
            margin: 25px 0;
            padding-top: 15px;
            border-top: 1px solid rgba(255,255,255,0.2);
        }
    </style>
</head>
<body>

<div class="container">
    <a href="grn_list.php" class="back">
        <i class="fas fa-arrow-left"></i> Back to GRN List
    </a>

    <h1>Create Goods Received Note (GRN)</h1>

    <?php if ($success): ?>
        <div class="message success"><?= $success ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="message error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="form-area">
        <form method="post" id="grnForm">
            <div class="form-group">
                    <label for="grn_code">GRN Code <span class="required">*</span></label>
                    <input type="text" name="project_code" id="grn_code" 
                           value="<?= htmlspecialchars($generated_code) ?>" readonly>
            </div>

            <div class="form-group">
                <label>GRN Date <span style="color:#fca5a5;">*</span></label>
                <input type="date" name="grn_date" value="<?= htmlspecialchars($_POST['grn_date'] ?? date('Y-m-d')) ?>" required>
            </div>

            <div class="form-group">
                <label>Vendor / Supplier <span style="color:#fca5a5;">*</span></label>
                <select name="vendor" required>
                    <option value="">-- Select Vendor --</option>
                    <?php 
                    $vendors_result->data_seek(0);
                    while ($v = $vendors_result->fetch_assoc()): 
                        $selected = ($_POST['vendor'] ?? '') === $v['vendor_name'] ? 'selected' : '';
                    ?>
                        <option value="<?= htmlspecialchars($v['vendor_name']) ?>" <?= $selected ?>>
                            <?= htmlspecialchars($v['vendor_name']) ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Against Purchase Order (optional)</label>
                <select name="po_id" onchange="loadPOItems(this.value)">
                    <option value="">None (Direct / Manual Receipt)</option>
                    <?php 
                    $pos->data_seek(0);
                    while ($po = $pos->fetch_assoc()): 
                    ?>
                        <option value="<?= $po['id'] ?>" <?= (($_POST['po_id'] ?? 0) == $po['id']) ? 'selected' : '' ?>>
                            PO-<?= str_pad($po['id'], 5, '0', STR_PAD_LEFT) ?> 
                            | <?= date('d M Y', strtotime($po['po_date'])) ?> 
                            | <?= htmlspecialchars($po['vendor']) ?>
                            <?php if ($po['project_code']): ?> 
                                | <?= htmlspecialchars($po['project_code']) ?> - <?= htmlspecialchars($po['project_name']) ?>
                            <?php endif; ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Receive For Project (optional)</label>
                <select name="project_id">
                    <option value="">Central Stock</option>
                    <?php 
                    $projects->data_seek(0);
                    while ($proj = $projects->fetch_assoc()): 
                        $selected = (($_POST['project_id'] ?? 0) == $proj['id']) ? 'selected' : '';
                    ?>
                        <option value="<?= $proj['id'] ?>" <?= $selected ?>>
                            <?= htmlspecialchars($proj['project_code']) ?> - <?= htmlspecialchars($proj['project_name']) ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Supplier Invoice / DC Number</label>
                <input type="text" name="invoice_no" value="<?= htmlspecialchars($_POST['invoice_no'] ?? '') ?>" 
                       placeholder="INV-12345 or DC-98765">
            </div>

            <h3 style="margin: 35px 0 15px 0;">Received Items</h3>

            <table class="items-table" id="itemsTable">
                <thead>
                    <tr>
                        <th>Item Name</th>
                        <th>Ordered Qty</th>
                        <th>Received Qty <span style="color:#fca5a5;">*</span></th>
                        <th>Rate (₹)</th>
                        <th>Batch / Lot No</th>
                        <th>Unit</th>
                        <th>Total Value (₹)</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="itemsBody"></tbody>
            </table>

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

            <div class="grand-total">
                Grand Total Value: <span id="grandTotal">₹ 0.00</span>
            </div>

            <div class="form-group">
                <label>Remarks / Delivery Notes</label>
                <textarea name="remarks" placeholder="Vehicle number, condition of goods, shortages, damages..."><?= htmlspecialchars($_POST['remarks'] ?? '') ?></textarea>
            </div>

            <button type="submit" class="submit-btn">
                <i class="fas fa-truck"></i> Save Goods Received Note
            </button>
        </form>
    </div>
</div>

<script>
// Initialize with one empty row
document.addEventListener('DOMContentLoaded', () => {
    addItemRow();
});

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

    row.innerHTML = `
        <td>
            <select name="item_id[]" class="item-select" onchange="updateUnit(this)" required>
                <option value="">Select Item</option>
                <?php 
                $items_result->data_seek(0);
                while ($item = $items_result->fetch_assoc()): ?>
                    <option value="<?= $item['id'] ?>" data-unit="<?= htmlspecialchars($item['uom']) ?>">
                        <?= htmlspecialchars($item['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </td>
        <td class="ordered-qty">—</td>
        <td><input type="number" name="quantity[]" step="0.001" min="0.001" placeholder="0" required oninput="calculateLineTotal(this)"></td>
        <td><input type="number" name="rate[]" step="0.01" min="0" placeholder="0.00" oninput="calculateLineTotal(this)"></td>
        <td><input type="text" name="batch[]" placeholder="Batch/Lot"></td>
        <td class="unit-cell">—</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 updateUnit(select) {
    const row = select.closest('tr');
    const unitCell = row.querySelector('.unit-cell');
    const option = select.options[select.selectedIndex];
    unitCell.textContent = option.dataset.unit || '—';
    calculateLineTotal(select);
}

function calculateLineTotal(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 totalEl = row.querySelector('.line-total');

    totalEl.textContent = `₹ ${(qty * rate).toFixed(2)}`;
    updateGrandTotal();
}

function removeRow(btn) {
    btn.closest('tr').remove();
    updateGrandTotal();
}

function updateGrandTotal() {
    let total = 0;
    document.querySelectorAll('.line-total').forEach(cell => {
        total += parseFloat(cell.textContent.replace('₹ ', '')) || 0;
    });
    document.getElementById('grandTotal').textContent = `₹ ${total.toFixed(2)}`;
}

// Load items from selected PO
function loadPOItems(poId) {
    if (!poId) {
        document.getElementById('itemsBody').innerHTML = '';
        addItemRow(); // Add one empty row
        return;
    }

    fetch(`get_po_items_for_grn.php?po_id=${poId}`)
        .then(r => r.json())
        .then(data => {
            const tbody = document.getElementById('itemsBody');
            tbody.innerHTML = '';

            data.forEach(item => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>
                        <select name="item_id[]" class="item-select" onchange="updateUnit(this)" required>
                            <option value="">Select Item</option>
                            <?php 
                            $items_result->data_seek(0);
                            while ($opt = $items_result->fetch_assoc()): ?>
                                <option value="<?= $opt['id'] ?>" data-unit="<?= htmlspecialchars($opt['uom']) ?>" 
                                    ${item.item_id == <?= $opt['id'] ?> ? 'selected' : ''}>
                                    <?= htmlspecialchars($opt['name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </td>
                    <td class="ordered-qty">${item.ordered_qty || 0}</td>
                    <td><input type="number" name="quantity[]" step="0.001" min="0.001" value="${item.ordered_qty || ''}" required oninput="calculateLineTotal(this)"></td>
                    <td><input type="number" name="rate[]" step="0.01" min="0" value="${item.rate || ''}" oninput="calculateLineTotal(this)"></td>
                    <td><input type="text" name="batch[]" placeholder="Batch/Lot"></td>
                    <td class="unit-cell">${item.unit || '—'}</td>
                    <td class="line-total">₹ 0.00</td>
                    <td><span class="remove-row" onclick="removeRow(this)"><i class="fas fa-trash"></i></span></td>
                `;
                // Auto calculate line total
                row.querySelector('input[name="quantity[]"]').dispatchEvent(new Event('input'));
            });
        })
        .catch(err => {
            console.error(err);
            alert('Failed to load PO items. Please try again.');
        });
}
</script>

</body>
</html>

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