<?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();
}
$project_id = $_GET['project_id'] ?? '';
$user_id = $_SESSION['user_id'];
$full_name = $_SESSION['full_name'] ?? 'Store/Admin';

function generateReturnCode(mysqli $conn): string {
    $sql = "SELECT rc_code FROM return_challan ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['rc_code'], 3) + 1;
    }
    return sprintf("RC-%04d", $next);
}

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

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

// Fetch SRNs
$srn_result = $conn->query("
    SELECT srn.id, srn.srn_code, srn.srn_date, 
           p.id as project_id, p.project_name, p.project_code 
    FROM supply_return_note srn
    JOIN project_master p ON srn.project_id = p.id
    WHERE (srn.status = 'Pending' OR srn.status IS NULL OR srn.status = '') AND srn.project_id = $project_id
    ORDER BY srn.srn_date DESC
");

if (!$srn_result) {
    $error = "Database Error: " . $conn->error;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $rc_code       = trim($_POST['rc_code'] ?? '');
    $rc_date       = $_POST['rc_date'] ?? date('Y-m-d');
    $srn_id        = (int)$_POST['srn_id'];
    $project_id    = (int)$_POST['project_id'];
    $sender_name   = trim($_POST['sender_name'] ?? '');
    $receiver_name = trim($_POST['receiver_name'] ?? $full_name);
    $vehicle_no    = trim($_POST['vehicle_no'] ?? '');
    $remarks       = trim($_POST['remarks'] ?? '');

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

    if ($srn_id <= 0) {
        $error = "Please select a valid SRN.";
    } elseif ($project_id <= 0) {
        $error = "Please select a project.";
    } elseif (empty($sender_name)) {
        $error = "Sender name is required.";
    } elseif (empty($item_ids) || count(array_filter($quantities, fn($q) => (float)$q > 0)) === 0) {
        $error = "No items available to return.";
    } else {
        try {
            $conn->begin_transaction();
            $rc_status = 'Issued';
            // Insert Return Challan Header
            $stmt = $conn->prepare("
                INSERT INTO return_challan 
                (rc_code, rc_date, project_id, srn_id, sender_name, receiver_name, 
                 vehicle_no, remarks, issued_by, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param("ssisssssis", $rc_code, $rc_date, $project_id, $srn_id, 
                             $sender_name, $receiver_name, $vehicle_no, $remarks, $user_id,$rc_status);
            $stmt->execute();
            $rc_id = $conn->insert_id;

            $item_stmt = $conn->prepare("INSERT INTO return_challan_items 
                (rc_id, item_id, model_no, serial_no, returned_qty, rate, uom) VALUES (?, ?, ?, ?, ? , ?, ?)");

            // Update SRN Status to Completed
            $srn_status = 'Completed';
            $srn_update = $conn->prepare("UPDATE supply_return_note 
                SET status = ? WHERE id = ?");

            $deduct_stmt = $conn->prepare("UPDATE project_inventory 
                SET current_stock = GREATEST(current_stock - ?, 0) 
                WHERE project_id = ? AND item_id = ?");

            foreach ($item_ids as $i => $item_id) {
                $qty  = (float)($quantities[$i] ?? 0);
                $rate = (float)($rates[$i] ?? 0);
                $model_no  = $model_nos[$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';

                    $item_stmt->bind_param("iisidss", $rc_id, $item_id, $model_no, $serial_no, $qty, $rate, $uom);
                    $item_stmt->execute();

                    $deduct_stmt->bind_param("dii", $qty, $project_id, $item_id);
                    $deduct_stmt->execute();
                    // ✅ ADD THIS BLOCK HERE (IMPORTANT)
                    if (!empty($serial_no)) {
                        $updateSerial = $conn->prepare("
                        UPDATE project_inventory_serials 
                        SET status = 'OUT'
                        WHERE serial_no = ? AND project_id = ?
                    ");
            $updateSerial->bind_param("si", $serial_no, $project_id);
            $updateSerial->execute();
        }
                }
            }
            // Update SRN Status
            $srn_update->bind_param("si", $srn_status, $srn_id);
            $srn_update->execute();
            $conn->commit();
            $success = "Return Challan created successfully!<br>
                        <strong>RC-" . str_pad($rc_id, 5, '0', STR_PAD_LEFT) . "</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>Create Return Challan from SRN</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);
        }
        option{
            color:black;
        }
        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; }
    </style>
</head>
<body>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="project-dc-list.php" style="color:#c4b5fd; text-decoration:none; float:left; font-size:1.1rem;">
                ← Back to Return List
            </a>
            <h1><i class="fas fa-undo"></i> Project → Warehouse 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="returnForm">

                <div class="section">
                    <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(280px,1fr)); gap:20px;">
                        <div>
                            <label>Return Challan Code *</label>
                            <input type="text" name="rc_code" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                        </div>
                        <div>
                            <label>Return Date *</label>
                            <input type="date" name="rc_date" value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div>
                            <label>Project *</label>
                            <select name="project_id" id="project_id" required>
                                <option value="">-- Select Project --</option>
                                <?php while ($p = $projects->fetch_assoc()): ?>
                                    <option value="<?= $p['id'] ?>">
                                        <?= htmlspecialchars($p['project_name']) ?> (<?= htmlspecialchars($p['project_code'] ?? '') ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="section">
                    <label>Select Supply Return Note (SRN) *</label>
                    <select name="srn_id" id="srn_id" required onchange="loadSRNItems()" style="padding:16px;">
                        <option value="">-- Choose SRN --</option>
                        <?php 
                        if ($srn_result && $srn_result->num_rows > 0) {
                            $srn_result->data_seek(0); // Reset pointer
                            while($srn = $srn_result->fetch_assoc()): 
                        ?>
                            <option value="<?= $srn['id'] ?>" data-project-id="<?= $srn['project_id'] ?>">
                                <?= htmlspecialchars($srn['srn_code']) ?> | 
                                <?= htmlspecialchars($srn['project_code'] . " - " . $srn['project_name']) ?> | 
                                <?= $srn['srn_date'] ?>
                            </option>
                        <?php 
                            endwhile; 
                        } else {
                            echo '<option value="">No SRN records found</option>';
                        }
                        ?>
                    </select>
                </div>

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

                <div class="section">
                    <label>Sender Name (From Project) *</label>
                    <input type="text" name="sender_name" placeholder="Site Incharge / Supervisor" required>

                    <label style="margin-top:15px;">Receiver Name (At Warehouse)</label>
                    <input type="text" name="receiver_name" value="<?= htmlspecialchars($full_name) ?>">

                    <label style="margin-top:15px;">Vehicle No.</label>
                    <input type="text" name="vehicle_no" placeholder="MH-31-AB-1234">

                    <label style="margin-top:15px;">Remarks / Notes</label>
                    <textarea name="remarks" rows="4" placeholder="Any additional information..."></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-truck-loading"></i> Create Return Challan
                </button>
            </form>
        </div>
    </div>
</div>

<script>
function loadSRNItems() {
    const srnId = document.getElementById('srn_id').value;
    const projectSelect = document.getElementById('project_id');
    const tbody = document.getElementById('itemsBody');
    tbody.innerHTML = '';

    if (!srnId) return;

    // Auto select project based on SRN
    const selectedOption = document.getElementById('srn_id').options[document.getElementById('srn_id').selectedIndex];
    if (selectedOption && selectedOption.dataset.projectId) {
        projectSelect.value = selectedOption.dataset.projectId;
    }

    fetch(`get_srn_items.php?srn_id=${srnId}`)
        .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 || '-'}
                            <input type="hidden" name="model_no[]" value="${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.quantity)}" 
                                   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 || 'NOS'}</td>
                        <td class="line-total">₹ ${(item.quantity * 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 in this SRN.</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(); ?>