<?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'];
$grn_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($grn_id <= 0) {
    header("Location: grn_list.php");
    exit();
}

$success = "";
$error = "";
// Function to generate GRN Code
function generateGRNCode(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()) {
        $last = (int)substr($row['grn_code'], 4) ?: 0;
        $next = $last + 1;
    }
    return sprintf("GRN-%03d", $next);
}
// Fetch GRN Header
$stmt = $conn->prepare("
    SELECT g.*, p.project_name 
    FROM goods_received_note g 
    LEFT JOIN project_master p ON g.project_id = p.id 
    WHERE g.id = ?
");
$stmt->bind_param("i", $grn_id);
$stmt->execute();
$grn = $stmt->get_result()->fetch_assoc();

if (!$grn) {
    header("Location: grn_list.php");
    exit();
}
// Auto-generate GRN Code if it doesn't exist
if (empty($grn['grn_code'])) {
    $grn['grn_code'] = generateGRNCode($conn);
    
    // Save the generated code to database
    $update_code = $conn->prepare("UPDATE goods_received_note SET grn_code = ? WHERE id = ?");
    $update_code->bind_param("si", $grn['grn_code'], $grn_id);
    $update_code->execute();
}
// Fetch GRN Items
$items_stmt = $conn->prepare("
    SELECT gi.*, im.name, im.model_no, im.uom 
    FROM goods_received_note_items gi
    JOIN inventory_master im ON gi.item_id = im.id
    WHERE gi.grn_id = ?
    ORDER BY gi.id ASC
");
$items_stmt->bind_param("i", $grn_id);
$items_stmt->execute();
$grn_items = $items_stmt->get_result();

// Fetch supporting 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");
$vendors_result = $conn->query("SELECT vendor_name FROM vendor_master ORDER BY vendor_name ASC");
$all_items_result = $conn->query("SELECT id, name, uom FROM inventory_master ORDER BY name ASC");

// Handle Update Form Submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $grn_date   = $_POST['grn_date'] ?? $grn['grn_date'];
    $vendor     = trim($_POST['vendor'] ?? $grn['vendor']);
    $project_id = !empty($_POST['project_id']) ? (int)$_POST['project_id'] : null;
    $invoice_no = trim($_POST['invoice_no'] ?? $grn['invoice_number']);
    $remarks    = trim($_POST['remarks'] ?? $grn['remarks']);

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

    try {
        $conn->begin_transaction();

        // Update GRN Header
        $update_sql = "UPDATE goods_received_note 
                       SET grn_date = ?, vendor = ?, invoice_number = ?, project_id = ?, remarks = ?, received_by = ? 
                       WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ssssisi", $grn_date, $vendor, $invoice_no, $project_id, $remarks, $user_id, $grn_id);
        $update_stmt->execute();

        // Delete old items and re-insert (safest method for edit)
        $conn->query("DELETE FROM goods_received_note_items WHERE grn_id = $grn_id");

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

        // Project inventory update
        $stock_stmt = null;
        if ($project_id > 0) {
            $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 UOM
                $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 item
                $item_stmt->bind_param("iidids", $grn_id, $item_id, $qty, $rate, $batch, $unit);
                $item_stmt->execute();

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

        $conn->commit();
        $success = "GRN updated successfully!";
        header("Location: grn_list.php?success=1");
        exit();

    } catch (Exception $e) {
        $conn->rollback();
        $error = "Failed to update 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>Edit GRN #<?= htmlspecialchars($grn['grn_code'] ?? $grn_id) ?></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 {
            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: 14px 12px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .remove-row {
            color: #f87171;
            font-size: 1.6rem;
            cursor: pointer;
        }

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

        .grand-total {
            font-size: 1.8rem;
            font-weight: 700;
            text-align: right;
            margin: 30px 0;
            color: #ddd6fe;
        }

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

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

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

        <div class="header">
            <a href="grn_list.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:35px; font-weight:500;">
                ← Back to GRN List
            </a>
            <h1><i class="fas fa-edit"></i> Edit Goods Received Note</h1>
            <p style="margin-top:12px; opacity:0.9;">GRN #<?= htmlspecialchars($grn['grn_code']) ?></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">

                <div class="form-grid">
                    <div class="form-group">
                        <label>GRN Code</label>
                        <input type="text" value="<?= htmlspecialchars($grn['grn_code']) ?>" readonly>
                    </div>
                    <div class="form-group">
                        <label>GRN Date <span class="required">*</span></label>
                        <input type="date" name="grn_date" value="<?= htmlspecialchars($grn['grn_date']) ?>" required>
                    </div>
                </div>

                <div class="form-grid">
                    <div class="form-group">
                        <label>Vendor / Supplier <span class="required">*</span></label>
                        <select name="vendor" required>
                            <option value="">-- Select Vendor --</option>
                            <?php 
                            $vendors_result->data_seek(0);
                            while ($v = $vendors_result->fetch_assoc()): 
                                $selected = ($v['vendor_name'] == $grn['vendor']) ? 'selected' : '';
                            ?>
                                <option value="<?= htmlspecialchars($v['vendor_name']) ?>" <?= $selected ?>>
                                    <?= htmlspecialchars($v['vendor_name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Receive For Project</label>
                        <select name="project_id">
                            <option value="">Central Stock</option>
                            <?php while ($proj = $projects->fetch_assoc()): 
                                $selected = ($proj['id'] == $grn['project_id']) ? 'selected' : '';
                            ?>
                                <option value="<?= $proj['id'] ?>" <?= $selected ?>>
                                    <?= htmlspecialchars($proj['project_code']) ?> - <?= htmlspecialchars($proj['project_name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label>Supplier Invoice / DC Number</label>
                    <input type="text" name="invoice_no" value="<?= htmlspecialchars($grn['invoice_number'] ?? '') ?>">
                </div>

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

                <table class="items-table" id="itemsTable">
                    <thead>
                        <tr>
                            <th>Model No</th>
                            <th>Item Name</th>
                            <th>Received Qty <span class="required">*</span></th>
                            <th>Rate (₹)</th>
                            <th>Batch / Lot</th>
                            <th>UOM</th>
                            <th>Amount (₹)</th>
                            <th style="width:60px;"></th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">
                        <?php while ($item = $grn_items->fetch_assoc()): ?>
                        <tr>
                            <td><input type="text" name="model_no[]" value="<?= htmlspecialchars($item['model_no'] ?? '') ?>"></td>
                            <td>
                                <select name="item_id[]" onchange="updateUnit(this)" required>
                                    <?php 
                                    $all_items_result->data_seek(0);
                                    while ($opt = $all_items_result->fetch_assoc()): ?>
                                        <option value="<?= $opt['id'] ?>" 
                                            data-unit="<?= htmlspecialchars($opt['uom']) ?>"
                                            <?= $opt['id'] == $item['item_id'] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($opt['name']) ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </td>
                            <td><input type="number" name="quantity[]" step="0.001" value="<?= $item['received_qty'] ?>" required oninput="calculateLineTotal(this)"></td>
                            <td><input type="number" name="rate[]" step="0.01" value="<?= $item['rate'] ?>" oninput="calculateLineTotal(this)"></td>
                            <td><input type="text" name="batch[]" value="<?= htmlspecialchars($item['batch_no'] ?? '') ?>"></td>
                            <td class="unit-cell"><?= htmlspecialchars($item['uom']) ?></td>
                            <td class="line-total">₹ <?= number_format($item['received_qty'] * $item['rate'], 2) ?></td>
                            <td><span class="remove-row" onclick="removeRow(this)"><i class="fas fa-trash"></i></span></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>

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

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

                <div class="form-group">
                    <label>Remarks / Notes</label>
                    <textarea name="remarks" rows="3"><?= htmlspecialchars($grn['remarks'] ?? '') ?></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-save"></i> Update GRN
                </button>
            </form>
        </div>
    </div>
</div>
<script>
// Reuse the same JavaScript from create_grn.php
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('#itemsBody tr').forEach(row => {
        const qtyInput = row.querySelector('input[name="quantity[]"]');
        if (qtyInput) {
            calculateLineTotal(qtyInput);
        }
    });
});
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)" style="width:100%;">
            <div class="suggestions" style="display:none;"></div>
        </td>
        <td>
            <select name="item_id[]" onchange="updateUnit(this)" required>
                <option value="">Select Item</option>
                <?php 
                $all_items_result->data_seek(0);
                while ($item = $all_items_result->fetch_assoc()): ?>
                    <option value="<?= $item['id'] ?>" data-unit="<?= htmlspecialchars($item['uom']) ?>">
                        <?= htmlspecialchars($item['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </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;
    row.querySelector('.line-total').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)}`;
}

// You can add searchByModel if needed
// Existing JS functions (searchByModel, selectModelItem, updateUnit, calculateLineTotal, removeRow, updateGrandTotal)
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.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 || '';
    const select = row.querySelector('select[name="item_id[]"]');
    select.value = item.id;
    select.dispatchEvent(new Event('change'));
    calculateLineTotal(row.querySelector('input[name="quantity[]"]'));
}
</script>

</body>
</html>

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