<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

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'] ?? '';
$success = "";
$error = "";
function generateGRNCode(mysqli $conn): string {
    $sql = "SELECT srn_code FROM supply_return_note ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['srn_code'], 4) + 1;
    }
    return sprintf("SRN-%03d", $next);
}
$generated_code = generateGRNCode($conn);

// Fetch Active 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 Inventory Items (for return)
// Corrected
$items_result = $conn->query("
    SELECT 
        im.id AS item_id,
        im.name,
        im.model_no,
        im.uom,
        pi.current_stock
    FROM project_inventory pi
    INNER JOIN inventory_master im ON pi.item_id = im.id
    WHERE pi.current_stock > 0
    ORDER BY im.name ASC
");
                              

// Handle Form Submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $srn_date       = $_POST['srn_date'] ?? date('Y-m-d');
    $project_id     = (int)($_POST['project_id'] ?? 0);
    $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 ($project_id <= 0) {
        $error = "Please select a project.";
    } elseif (empty($item_ids)) {
        $error = "Please add at least one item to return.";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Insert SRN Header
            $stmt = $conn->prepare("INSERT INTO supply_return_note 
                (srn_code, srn_date, project_id, receiver_name, remarks, created_by) 
                VALUES (?, ?, ?, ?, ?, ?)");
            $user_id = $_SESSION['user_id'];
            $stmt->bind_param("ssisss",  $generated_code, $srn_date, $project_id, $receiver_name, $remarks, $user_id);
            $stmt->execute();
            $srn_id = $conn->insert_id;

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

                // Deduct from project inventory / main stock (safe update)
                // $conn->query("UPDATE inventory_master 
                //               SET current_stock = GREATEST(current_stock - $qty, 0) 
                //               WHERE id = $item_id");
            }

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

            mysqli_commit($conn);
            $success = "Supply Return Note created successfully! SRN ID: SRN-" . str_pad($srn_id, 5, '0', STR_PAD_LEFT);

        } catch (Exception $e) {
            mysqli_rollback($conn);
            $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>Add Supply Return Note (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 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;
    }
    option{
        color: #000000 !important;
    }
    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-undo"></i> Add Supply Return Note (SRN)</h1>
            <p>Return materials from project to store</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 action="" method="POST" id="srnForm">

                <div class="section">
                    <div class="form-grid">
                        <div>
                            <label>SRN Code</label>
                            <input type="text" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                        </div>
                        <div>
                            <label>SRN Date <span class="required">*</span></label>
                            <input type="date" name="srn_date" value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div>
                            <label>Project <span class="required">*</span></label>
                            <select name="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>
                            <label>Receiver Name <span class="required">*</span></label>
                            <input type="text" name="receiver_name" placeholder="Store In-charge / Person 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" style="display:none;">
                    <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"
                        placeholder="Damaged items, excess supply, project closed, etc."></textarea>
                </div>

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

    <script>
    let rowCount = 0;

    function addNewRow() {
        rowCount++;
        const 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)" required>
                        <option value="">-- Select Item --</option>
                        <?php 
                        $items_result->data_seek(0);
                        while ($item = $items_result->fetch_assoc()): 
                        ?>
                            <option 
    value="<?= $item['item_id'] ?>" 
    data-uom="<?= htmlspecialchars($item['uom']) ?>"
    data-model="<?= htmlspecialchars($item['model_no']) ?>"
>
                                <?= htmlspecialchars($item['name']) ?> <?= $item['model_no'] ? '(' . htmlspecialchars($item['model_no']) . ')' : '' ?> 
                                [Stock: <?= number_format($item['current_stock'], 3) ?>]
                            </option>
                        <?php endwhile; ?>
                    </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)" value="0">
                </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="Project Closed">Project Closed</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);
        document.getElementById('totalsBox').style.display = 'block';
    }

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

    function updateUnit(select) {
    const row = select.closest('.item-row');

    const model = select.options[select.selectedIndex].getAttribute('data-model');

    row.querySelector('input[name="model_no[]"]').value = model || '';

    calculateTotal(select);
}

    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>';
        });
}                
    window.onload = () => {
        addNewRow(); // Start with one row
    };
    </script>
</body>

</html>

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