<?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'] ?? 'Warehouse';

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

// Generate GRN Code
function generateGRNCode(mysqli $conn): string {
    $sql = "SELECT grn_code FROM goods_received_note_warehouse ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['grn_code'], 5) + 1;
    }
    return sprintf("GRNW-%04d", $next);
}

$generated_code = generateGRNCode($conn);

// Fetch Pending Return Challans
$rcs = $conn->query("
    SELECT rc.id, rc.rc_code, rc.rc_date, rc.sender_name, rc.project_id,
           p.project_name, p.project_code
    FROM return_challan rc
    JOIN project_master p ON rc.project_id = p.id
    WHERE rc.status = 'Issued'
    ORDER BY rc.rc_date DESC
");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $grn_date   = $_POST['grn_date'] ?? date('Y-m-d');
    $rc_id      = (int)$_POST['rc_id'];
    $remarks    = trim($_POST['remarks'] ?? '');

    $item_ids   = $_POST['item_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $rates      = $_POST['rate'] ?? [];
    $models     = $_POST['model_no'] ?? [];
    $serial_nos = $_POST['serial_no'] ?? [];

    if ($rc_id <= 0) {
        $error = "Please select a valid Return Challan.";
    } elseif (empty($item_ids) || count(array_filter($quantities, fn($q) => (float)$q > 0)) === 0) {
        $error = "No items with valid quantity.";
    } else {
        try {
            $conn->begin_transaction();

            // Get project_id from Return Challan
            $proj_q = $conn->prepare("SELECT project_id FROM return_challan WHERE id = ?");
            $proj_q->bind_param("i", $rc_id);
            $proj_q->execute();
            $project_id = $proj_q->get_result()->fetch_assoc()['project_id'] ?? null;

            // Insert GRN Header
            $grn_stmt = $conn->prepare("
                INSERT INTO goods_received_note_warehouse 
                (grn_code, grn_date, vendor, invoice_number, project_id, remarks, 
                 status, received_by, created_at, source_type, source_id)
                VALUES (?, ?, 'Return from Project', NULL, ?, ?, 'Received', ?, NOW(), 'RC', ?)
            ");
            $grn_stmt->bind_param("ssisii", 
                $generated_code, $grn_date, $project_id, $remarks, $user_id, $rc_id);
            $grn_stmt->execute();
            $grn_id = $conn->insert_id;

            // Item Insert
            $item_stmt = $conn->prepare("
                INSERT INTO goods_received_note_items_warehouse 
                (grn_id, item_id, model_no, serial_number, received_qty, rate, batch_no, unit) 
                VALUES (?, ?, ?, ?, ?, ?, '', ?)
            ");

            // ✅ UPDATED: Update inventory_master (Central Stock)
            $stock_stmt = $conn->prepare("
                INSERT INTO inventory_master (id, current_stock, last_updated)
                VALUES (?, ?,NOW())
                ON DUPLICATE KEY UPDATE 
                    current_stock = current_stock + VALUES(current_stock),
                    
                    last_updated = NOW()
            ");

            $rc_update = $conn->prepare("UPDATE return_challan SET status = 'Received' WHERE id = ?");

            $updateSerial = $conn->prepare("
            UPDATE inventory_serials 
            SET status = 'In Stock'
            WHERE serial_number = ?
            
            ");
           

            foreach ($item_ids as $i => $item_id) {
                $qty  = (float)($quantities[$i] ?? 0);
                $rate = (float)($rates[$i] ?? 0);
                $model_no  = $models[$i] ?? '';
                $serial_no = $serial_nos[$i] ?? '';

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

                    // Insert GRN Item
                    $item_stmt->bind_param("iisidss", $grn_id, $item_id, $model_no, $serial_no, $qty, $rate, $uom);
                    $item_stmt->execute();
                     // ✅ SERIAL UPDATE (VERY IMPORTANT)
                    if (!empty($serial_no)) {
                    $updateSerial->bind_param("s", $serial_no);
                    $updateSerial->execute();
                    }
                    // Update Central Inventory (inventory_master)
                    $stock_stmt->bind_param("id", $item_id, $qty);
                    $stock_stmt->execute();
                }
            }

            $rc_update->bind_param("i", $rc_id);
            $rc_update->execute();

            $conn->commit();
            $success = "Warehouse GRN created successfully!<br>
                        <strong>GRN Code: " . htmlspecialchars($generated_code) . "</strong>";

        } catch (Exception $e) {
            $conn->rollback();
            $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>Warehouse GRN from Return Challan</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: 25px 15px;
        }
        .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;
        }
        .header h1 { font-size: 2.6rem; 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: 32px;
            margin-bottom: 35px;
        }

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

        table { width: 100%; border-collapse: collapse; margin: 20px 0; background: rgba(0,0,0,0.2); border-radius: 16px; overflow: hidden; }
        th { background: rgba(168,85,247,0.25); padding: 16px; text-align: left; }
        td { padding: 16px; border-bottom: 1px solid rgba(255,255,255,0.1); }

        .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;
        }
        .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) {
            .header h1 { font-size: 2.1rem; }
            .form-area { padding: 30px 20px; }
            .section { padding: 25px; }
        }
    </style>
</head>
<body>
<?php include '../config/header.php'; ?>
<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="grn_warehouse_list.php" style="color:#c4b5fd; text-decoration:none; float:left; font-size:1.1rem;">
                ← Back to GRN List
            </a>
            <h1><i class="fas fa-warehouse"></i> Warehouse GRN from Return Challan</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="grnForm">

                <div class="section">
                    <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(280px,1fr)); gap:20px;">
                        <div>
                            <label>GRN Code *</label>
                            <input type="text" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                        </div>
                        <div>
                            <label>GRN Date *</label>
                            <input type="date" name="grn_date" value="<?= date('Y-m-d') ?>" required>
                        </div>
                    </div>
                </div>

                <div class="section">
                    <label>Select Return Challan *</label>
                    <select name="rc_id" id="rc_id" required onchange="loadRCItems()" style="padding:16px;">
                        <option value="">-- Choose Return Challan --</option>
                        <?php while ($rc = $rcs->fetch_assoc()): ?>
                            <option value="<?= $rc['id'] ?>">
                                <?= htmlspecialchars($rc['rc_code']) ?> | 
                                <?= htmlspecialchars($rc['project_code']) ?> - <?= htmlspecialchars($rc['project_name']) ?> | 
                                <?= $rc['rc_date'] ?> | From: <?= htmlspecialchars($rc['sender_name']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <div class="section">
                    <h3>Items Being Received at Warehouse</h3>
                    <table id="itemsTable">
                        <thead>
                            <tr>
                                <th>Item Name</th>
                                <th>Model No</th>
                                <th>Serial No</th>
                                <th>Received Qty</th>
                                <th>Rate (₹)</th>
                                <th>Unit</th>
                                <th>Line Total (₹)</th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody"></tbody>
                    </table>
                </div>

                <div class="section">
                    <label>Remarks / Condition of Goods</label>
                    <textarea name="remarks" rows="4" placeholder="Any damage, shortage, or additional notes..."></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-warehouse"></i> Create Warehouse GRN
                </button>
            </form>
        </div>
    </div>
</div>

<script>
function loadRCItems() {
    const rcId = document.getElementById('rc_id').value;
    const tbody = document.getElementById('itemsBody');
    tbody.innerHTML = '';

    if (!rcId) return;

    fetch(`get_rc_items.php?rc_id=${rcId}`)
        .then(r => r.json())
        .then(data => {
            if (data.success && data.items.length > 0) {
                data.items.forEach(item => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td><strong>${item.name}</strong></td>
                        <td>${item.model_no || '-'}</td>
                        <td>
                            ${item.serial_no || '-'}
                            <input type="hidden" name="serial_no[]" value="${item.serial_no || ''}">
                        </td>
                        <td>
                            <input type="number" name="quantity[]" value="${parseFloat(item.returned_qty)}" 
                                   step="0.001" min="0.001" required style="width:130px;" 
                                   oninput="calculateLineTotal(this)">
                            <input type="hidden" name="item_id[]" value="${item.item_id}">
                        </td>
                        <td>
                            <input type="number" name="rate[]" value="${parseFloat(item.rate)}" 
                                   step="0.01" style="width:130px;" oninput="calculateLineTotal(this)">
                        </td>
                        <td>${item.uom}</td>
                        <td class="line-total">₹ ${(item.returned_qty * item.rate).toFixed(2)}</td>
                        
                    `;
                    tbody.appendChild(row);
                });
            } else {
                tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;padding:40px;color:#f87171;">No items found.</td></tr>`;
            }
        })
        .catch(() => {
            tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;color:#f87171;">Failed to load items.</td></tr>`;
        });
}

function calculateLineTotal(el) {
    const row = el.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)}`;
}
</script>

</body>
</html>

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