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

$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$srn_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($srn_id <= 0) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Invalid SRN ID</h2>");
}

// Fetch SRN Header
$header_query = "
    SELECT 
        srn.*,
        p.project_code,
        p.project_name
    FROM supply_return_note srn
    LEFT JOIN project_master p ON srn.project_id = p.id
    WHERE srn.id = ?
";
$stmt = $conn->prepare($header_query);
$stmt->bind_param("i", $srn_id);
$stmt->execute();
$srn = $stmt->get_result()->fetch_assoc();

if (!$srn) {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>Supply Return Note not found.</h2>");
}

// Only allow editing if status is Pending
if ($srn['status'] !== 'Pending') {
    die("<h2 style='color:#ef4444;text-align:center;padding:100px;'>This SRN cannot be edited (Status: {$srn['status']}).</h2>");
}

// Fetch Existing Items
$items_query = "
    SELECT 
        sri.*,
        i.name AS item_name,
        i.model_no
    FROM supply_return_note_items sri
    LEFT JOIN inventory_master i ON sri.item_id = i.id
    WHERE sri.srn_id = ?
    ORDER BY sri.id ASC
";
$items_stmt = $conn->prepare($items_query);
$items_stmt->bind_param("i", $srn_id);
$items_stmt->execute();
$existing_items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch All Items for dropdown
$all_items = $conn->query("SELECT id, name, model_no, uom FROM inventory_master ORDER BY name ASC");

// Handle Update Form
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $srn_date      = $_POST['srn_date'] ?? $srn['srn_date'];
    $receiver_name = trim($_POST['receiver_name'] ?? '');
    $remarks       = trim($_POST['remarks'] ?? '');

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

    if (empty($receiver_name)) {
        $error = "Receiver name is required.";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Update Header
            $update_header = $conn->prepare("UPDATE supply_return_note 
                SET srn_date = ?, receiver_name = ?, remarks = ?, updated_at = NOW() 
                WHERE id = ?");
            $update_header->bind_param("sssi", $srn_date, $receiver_name, $remarks, $srn_id);
            $update_header->execute();

            // Delete old items
            $conn->query("DELETE FROM supply_return_note_items WHERE srn_id = $srn_id");

            // Insert updated items
            $item_stmt = $conn->prepare("INSERT INTO supply_return_note_items 
                (srn_id, item_id, model_no, serial_no, quantity, rate, reason, line_total) 
                VALUES (?, ?, ?, ?, ?, ? , ?, ?)");

            $grand_total = 0;

            foreach ($item_ids as $index => $item_id) {
                $qty    = floatval($quantities[$index] ?? 0);
                $rate   = floatval($rates[$index] ?? 0);
                $reason = trim($reasons[$index] ?? '');
                $serial  = trim($serials[$index] ?? '');
                $model   = trim($models[$index] ?? '');
                if ($qty <= 0 || $item_id <= 0) continue;

                $line_total = $qty * $rate;
                $grand_total += $line_total;

                $item_stmt->bind_param("iisiddsd", $srn_id, $item_id, $model, $serial, $qty, $rate, $reason, $line_total);
                $item_stmt->execute();
            }

            // Update grand total
            $conn->query("UPDATE supply_return_note SET grand_total = $grand_total WHERE id = $srn_id");

            mysqli_commit($conn);
            $success = "Supply Return Note updated successfully!";

            // Refresh page to show updated data
            header("Location: srn_view.php?id=$srn_id");
            exit;

        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Error updating SRN: " . $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 SRN #<?= htmlspecialchars($srn['srn_code']) ?></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 no-repeat fixed;
            color: #f1f5f9;
            padding: 20px;
        }
        .glass-container {
            max-width: 1350px;
            margin: 0 auto;
            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: clamp(32px, 5.5vw, 42px);
            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;
        }
        .item-row {
            background: rgba(255,255,255,0.06);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 18px;
            padding: 28px;
            margin-bottom: 25px;
            position: relative;
        }
        .remove-btn {
            position: absolute; top: 20px; right: 20px;
            background: rgba(239,68,68,0.4); color: white;
            border: none; width: 40px; height: 40px;
            border-radius: 50%; font-size: 24px; cursor: pointer;
        }
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 20px;
        }
        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); }
        .add-row-btn, .submit-btn {
            width: 100%; padding: 18px; border-radius: 16px; font-weight: 700; font-size: 17px; cursor: pointer; margin: 25px 0;
        }
        .add-row-btn { background: rgba(255,255,255,0.06); border: 2px dashed #c084fc; color: white; }
        .submit-btn { background: linear-gradient(135deg, var(--primary), var(--accent)); color: white; border: none; }
        .totals-box {
            background: linear-gradient(135deg, rgba(168,85,247,0.15), rgba(192,132,252,0.12));
            border: 1px solid var(--accent);
            border-radius: 20px;
            padding: 28px;
            margin: 30px 0;
        }
        .total-row {
            display: flex; justify-content: space-between; padding: 12px 0; font-size: 1.15rem;
            border-bottom: 1px solid rgba(255,255,255,0.15);
        }
        .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>
<?php include '../config/header.php'; ?>
<div class="glass-container">
    <div class="header">
        <h1><i class="fas fa-edit"></i> Edit Supply Return Note #<?= htmlspecialchars($srn['srn_code']) ?></h1>
    </div>

    <div class="form-area">
        <?php if (isset($success)): ?><div class="message success"><?= $success ?></div><?php endif; ?>
        <?php if (isset($error)): ?><div class="message error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

        <form action="" method="POST">
            <input type="hidden" name="project_id" value="<?= $srn['project_id'] ?>">
            <div class="section">
                <div class="form-grid">
                    <div>
                        <label>SRN Code</label>
                        <input type="text" value="<?= htmlspecialchars($srn['srn_code']) ?>" readonly>
                    </div>
                    <div>
                        <label>SRN Date <span class="required">*</span></label>
                        <input type="date" name="srn_date" value="<?= $srn['srn_date'] ?>" required>
                    </div>
                    <div>
                        <label>Project</label>
                        <input type="text" value="<?= htmlspecialchars($srn['project_name']) ?> (<?= htmlspecialchars($srn['project_code'] ?? '') ?>)" readonly>
                    </div>
                    <div>
                        <label>Receiver Name <span class="required">*</span></label>
                        <input type="text" name="receiver_name" value="<?= htmlspecialchars($srn['receiver_name']) ?>" required>
                    </div>
                </div>
            </div>

            <!-- Items Section -->
            <div class="section">
                <h2><i class="fas fa-boxes"></i> Returned Items</h2>
                <div class="items-container" id="itemsContainer"></div>
                <div class="add-row-btn" onclick="addNewRow()">
                    <i class="fas fa-plus-circle"></i> Add Another Item
                </div>
            </div>

            <div class="totals-box" id="totalsBox">
                <div class="total-row"><span>Basic Total:</span> <span id="basicTotal">₹ 0.00</span></div>
                <div class="total-row"><span><strong>Grand Total:</strong></span> <span id="grandTotal">₹ 0.00</span></div>
            </div>

            <div class="section">
                <label>Remarks / Reason for Return</label>
                <textarea name="remarks" rows="3"><?= htmlspecialchars($srn['remarks'] ?? '') ?></textarea>
            </div>

            <button type="submit" class="submit-btn">
                <i class="fas fa-save"></i> Update Supply Return Note
            </button>
        </form>
    </div>
</div>

<script>
let rowCount = 0;

// Load Existing Items
const existingItems = <?= json_encode($existing_items) ?>;

function addNewRow(data = null) {
    rowCount++;
    let html = `
        <div class="item-row" id="row-${rowCount}">
            <button type="button" class="remove-btn" onclick="removeRow(${rowCount})">×</button>
            <div class="form-grid">
                <div>
                    <label>Item <span class="required">*</span></label>
                    <select name="item_id[]" class="item-select" onchange=" loadSerials(this); updateUnit(this); calculateTotal(this)" required>
                        <option value="">-- Select Item --</option>`;
    
    // Populate dropdown with all items
    <?php $all_items->data_seek(0); ?>
    <?php while ($item = $all_items->fetch_assoc()): ?>
        html += `<option value="<?= $item['id'] ?>" <?= $item['model_no'] ? 'data-model="'.htmlspecialchars($item['model_no']).'"' : '' ?>>
                    <?= htmlspecialchars($item['name']) ?> <?= $item['model_no'] ? '(' . htmlspecialchars($item['model_no']) . ')' : '' ?>
                 </option>`;
    <?php endwhile; ?>

    html += `</select>
                </div>
                <div>
                    <label>Model No</label>
                    <input type="text" name="model_no[]">
                </div>
                <div>
                    <label>Serial No</label>
                    <select name="serial_no[]" class="serial-dropdown">
                        <option value="">-- Select Serial --</option>
                    </select>
                </div>
                <div>
                    <label>Quantity <span class="required">*</span></label>
                    <input type="number" step="0.001" min="0.001" name="quantity[]" class="quantity" oninput="calculateTotal(this)" required>
                </div>
                <div>
                    <label>Rate (₹)</label>
                    <input type="number" step="0.01" min="0" name="rate[]" oninput="calculateTotal(this)">
                </div>
                <div>
                    <label>Reason</label>
                    <select name="reason[]">
                        <option value="Excess Supply">Excess Supply</option>
                        <option value="Damaged">Damaged</option>
                        <option value="Wrong Item">Wrong Item</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div>
                    <label>Line Total (₹)</label>
                    <input type="text" name="line_total[]" readonly class="line-total" value="0.00">
                </div>
            </div>
        </div>`;

    document.getElementById('itemsContainer').insertAdjacentHTML('beforeend', html);

    // If data exists (for editing), populate the row
    if (data) {
    const newRow = document.getElementById(`row-${rowCount}`);

    newRow.querySelector('select[name="item_id[]"]').value = data.item_id;
    newRow.querySelector('input[name="quantity[]"]').value = data.quantity;
    newRow.querySelector('input[name="rate[]"]').value = data.rate;
    newRow.querySelector('select[name="reason[]"]').value = data.reason || 'Other';

    // ✅ NEW
    newRow.querySelector('input[name="model_no[]"]').value = data.model_no || '';

    // Load serials first, then set selected
    loadSerials(newRow.querySelector('select[name="item_id[]"]'));

    setTimeout(() => {
        newRow.querySelector('select[name="serial_no[]"]').value = data.serial_no || '';
    }, 300);

    newRow.querySelector('.line-total').value = (data.quantity * data.rate).toFixed(2);
}

    calculateGrandTotal();
}

function removeRow(id) {
    document.getElementById(`row-${id}`).remove();
    calculateGrandTotal();
}

function calculateTotal(el) {
    const row = el.closest('.item-row');
    const qty = parseFloat(row.querySelector('input[name="quantity[]"]').value) || 0;
    const rate = parseFloat(row.querySelector('input[name="rate[]"]').value) || 0;
    const lineTotal = (qty * rate).toFixed(2);
    row.querySelector('.line-total').value = lineTotal;
    calculateGrandTotal();
}

function calculateGrandTotal() {
    let total = 0;
    document.querySelectorAll('.line-total').forEach(input => {
        total += parseFloat(input.value) || 0;
    });
    document.getElementById('basicTotal').textContent = `₹ ${total.toFixed(2)}`;
    document.getElementById('grandTotal').textContent = `₹ ${total.toFixed(2)}`;
}
 function loadSerials(select) {
    const row = select.closest('.item-row');
    const item_id = select.value;
    const project_id = document.querySelector('[name="project_id"]').value;

    const serialDropdown = row.querySelector('.serial-dropdown');

    if (!item_id || !project_id) {
        serialDropdown.innerHTML = '<option value="">Select project first</option>';
        return;
    }

    fetch(`get_project_serials.php?project_id=${project_id}&item_id=${item_id}`)
        .then(res => res.json())
        .then(data => {
            serialDropdown.innerHTML = '<option value="">-- Select Serial --</option>';

            if (data.serials.length === 0) {
                serialDropdown.innerHTML += `<option>No serials available</option>`;
                return;
            }

            data.serials.forEach(serial => {
                serialDropdown.innerHTML += `<option value="${serial}">${serial}</option>`;
            });
        })
        .catch(err => {
            console.error(err);
            serialDropdown.innerHTML = '<option>Error loading serials</option>';
        });
}           
// Load existing items on page load
window.onload = () => {
    if (existingItems.length > 0) {
        existingItems.forEach(item => {
            addNewRow(item);
        });
    } else {
        addNewRow(); // Start with empty row if no items
    }
};
</script>
</body>
</html>

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