<?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");

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

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

// Generate Next SKU
function getNextSKU(mysqli $conn): string {
    $sql = "SELECT sku FROM inventory_master ORDER BY id DESC LIMIT 1";
    $res = $conn->query($sql);
    $next = 1;
    if ($res && $row = $res->fetch_assoc()) {
        $next = (int)substr($row['sku'], 3) + 1;
    }
    return sprintf("IN-%03d", $next);
}

$nextSKU = getNextSKU($conn);

// Fetch Warehouses
$warehouses_result = $conn->query("
    SELECT id, warehouse_name, location 
    FROM warehouse_master 
    WHERE status = 'Active' 
    ORDER BY warehouse_name ASC
");

// Fetch Vendors
$vendors = $conn->query("SELECT id, vendor_name FROM vendor_master ORDER BY vendor_name ASC")->fetch_all(MYSQLI_ASSOC);

// Fetch Categories & UOMs
$categories = $conn->query("SELECT id, category FROM category_tbl ORDER BY category ASC")->fetch_all(MYSQLI_ASSOC);
$uoms = $conn->query("SELECT id, uom_name FROM uom_tbl ORDER BY uom_name ASC")->fetch_all(MYSQLI_ASSOC);

// ====================== AJAX: Add Category / UOM ======================
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => ''];

    if ($_POST['action'] === 'add_category') {
        $name = trim($_POST['name'] ?? '');
        if (empty($name)) {
            $response['message'] = "Category name is required";
        } else {
            $stmt = $conn->prepare("INSERT INTO category_tbl (category) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) {
                $response['success'] = true;
                $response['id'] = $conn->insert_id;
                $response['name'] = $name;
            } else {
                $response['message'] = "Error: " . $conn->error;
            }
        }
    }

    if ($_POST['action'] === 'add_uom') {
        $name = trim($_POST['name'] ?? '');
        if (empty($name)) {
            $response['message'] = "UOM name is required";
        } else {
            $stmt = $conn->prepare("INSERT INTO uom_tbl (uom_name) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) {
                $response['success'] = true;
                $response['id'] = $conn->insert_id;
                $response['name'] = $name;
            } else {
                $response['message'] = "Error: " . $conn->error;
            }
        }
    }

    echo json_encode($response);
    exit;
}

// ====================== MAIN FORM SUBMISSION ======================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    $warehouse_id = (int)($_POST['warehouse_id'] ?? 0);
    $items = $_POST['items'] ?? [];
    $inserted = 0;

    if ($warehouse_id <= 0) {
        $error = "Please select a warehouse.";
    } elseif (empty($items)) {
        $error = "Please add at least one material.";
    } else {
        try {
            $conn->begin_transaction();

            foreach ($items as $idx => $item) {
                $sku           = trim($item['sku'] ?? '');
                $name          = trim($item['name'] ?? '');
                $description   = trim($item['description'] ?? '');
                $hsn_sac       = trim($item['hsn_sac'] ?? '');
                $category      = (int)($item['category'] ?? 0);
                $model_no      = trim($item['model_no'] ?? '');
                $serial_numbers = array_filter(array_map('trim', $item['serial_number'] ?? []));
                $supplier_vendor = (int)($item['supplier_vendor'] ?? 0);
                $uom           = (int)($item['uom'] ?? 0);
                $initial_stock = (float)($item['initial_stock'] ?? 0);
                $reorder_level = (float)($item['reorder_level'] ?? 0);

                if (empty($name) || empty($sku) || empty($model_no)) continue;

                // Insert main inventory item
                $stmt = $conn->prepare("INSERT INTO inventory_master 
                    (sku, name, description, hsn_sac, category, warehouse_id, model_no, 
                     supplier_vendor, uom, current_stock, reorder_level, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");

                $stmt->bind_param("sssssisssdd", 
                    $sku, $name, $description, $hsn_sac, $category, $warehouse_id, 
                    $model_no, $supplier_vendor, $uom, $initial_stock, $reorder_level
                );
                $stmt->execute();
                $inventory_id = $conn->insert_id;
                $stmt->close();

                // Insert Multiple Serial Numbers
                if (!empty($serial_numbers)) {
                    $serial_stmt = $conn->prepare("INSERT INTO inventory_serials (inventory_id, serial_number) VALUES (?, ?)");
                    foreach ($serial_numbers as $serial) {
                        if (!empty($serial)) {
                            $serial_stmt->bind_param("is", $inventory_id, $serial);
                            $serial_stmt->execute();
                        }
                    }
                }

                $inserted++;
            }

            $conn->commit();
            if ($inserted > 0) {
                $success = "$inserted material(s) added successfully with serial numbers!";
                $nextSKU = getNextSKU($conn); // Refresh SKU for next use
            }

        } 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>Add Materials to Inventory</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;
        }
        .header h1 { 
            font-size: clamp(28px, 5.5vw, 42px); 
            font-weight: 700; 
        }

        .form-area { padding: 45px 40px; }

        .warehouse-section {
            background: rgba(255,255,255,0.07);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 35px;
        }

        .item-row {
            background: rgba(255,255,255,0.06);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 25px;
            position: relative;
        }

        .remove-btn {
            position: absolute;
            top: 15px; right: 15px;
            background: rgba(239,68,68,0.8);
            color: white;
            border: none;
            width: 38px; height: 38px;
            border-radius: 50%;
            font-size: 22px;
            cursor: pointer;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 20px;
        }

        .serial-container {
            margin-top: 15px;
            padding: 15px;
            background: rgba(0,0,0,0.2);
            border-radius: 12px;
        }

        .serial-input {
            display: flex;
            gap: 10px;
            margin-bottom: 8px;
        }

        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);
        }
        option{
            color:black;
        }
        .add-row-btn, .submit-btn {
            width: 100%;
            padding: 18px;
            border-radius: 18px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            margin: 25px 0;
        }
        .add-row-btn {
            background: rgba(255,255,255,0.06);
            border: 2px dashed rgba(192,132,252,0.6);
            color: white;
        }
        .add-option-btn {
            color: var(--primary);
            cursor: pointer;
            text-decoration: none;
        }
        .add-serial-btn {
            color: var(--primary);
            cursor: pointer;
            text-decoration: none;
        }
        .submit-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
        }

        .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) {
            .form-area { padding: 30px 20px; }
        }
    </style>
</head>
<body>

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

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="inventory-management.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:40px;">
                ← Back to Inventory
            </a>
            <h1><i class="fas fa-boxes-stacked"></i> Add Materials to Inventory</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="inventoryForm">

                <div class="warehouse-section">
                    <label>Warehouse <span class="required">*</span></label>
                    <select name="warehouse_id" required>
                        <option value="">-- Select Warehouse --</option>
                        <?php while ($w = $warehouses_result->fetch_assoc()): ?>
                            <option value="<?= $w['id'] ?>">
                                <?= htmlspecialchars($w['warehouse_name']) ?> — <?= htmlspecialchars($w['location']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <div id="itemsContainer"></div>

                <button type="button" class="add-row-btn" onclick="addNewRow()">
                    <i class="fas fa-plus"></i> Add Another Material
                </button>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-save"></i> Save All Materials to Inventory
                </button>
            </form>
        </div>
    </div>
</div>

<!-- Modal -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <div class="modal-header" id="modalTitle">Add New</div>
        <input type="text" id="modalName" placeholder="Enter Name">
        <div class="modal-buttons">
            <button class="btn-cancel" onclick="closeModal()">Cancel</button>
            <button class="btn-save" onclick="saveModal()">Save</button>
        </div>
    </div>
</div>

<script>
let rowCount = 0;
const baseSKU = "<?= $nextSKU ?>";
const vendors = <?= json_encode($vendors) ?>;
const categories = <?= json_encode($categories) ?>;
const uomsList = <?= json_encode($uoms) ?>;

function generateSKU(index) {
    const num = parseInt(baseSKU.substring(3)) + index;
    return "IN-" + String(num).padStart(3, '0');
}

function addNewRow() {
    rowCount++;
    const sku = generateSKU(rowCount - 1);

    let vendorOptions = '<option value="">-- Choose Vendor --</option>';
    vendors.forEach(v => vendorOptions += `<option value="${v.id}">${v.vendor_name}</option>`);

    let catOptions = '<option value="">Select Category</option>';
    categories.forEach(c => catOptions += `<option value="${c.id}">${c.category}</option>`);

    let uomOptions = '<option value="">Select UOM</option>';
    uomsList.forEach(u => uomOptions += `<option value="${u.id}">${u.uom_name}</option>`);

    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>SKU</label><input type="text" name="items[${rowCount}][sku]" value="${sku}" readonly></div>
                <div><label>Material Name <span class="required">*</span></label><input type="text" name="items[${rowCount}][name]" required></div>
                <div><label>Model No <span class="required">*</span></label><input type="text" name="items[${rowCount}][model_no]" required></div>
                
                <!-- Multiple Serial Numbers -->
                <div class="full-width">
                    <label>Serial Numbers (One per line)</label>
                    <div class="serial-container" id="serial-container-${rowCount}">
                        <div class="serial-input">
                            <input type="text" name="items[${rowCount}][serial_number][]" placeholder="Enter serial number">
                        </div>
                    </div>
                    <div class="add-serial-btn" onclick="addSerialField(${rowCount})">+ Add another serial number</div>
                </div>

                <div><label>HSN/SAC</label><input type="text" name="items[${rowCount}][hsn_sac]"></div>
                
                <div>
                    <label>Category</label>
                    <select name="items[${rowCount}][category]" class="category-select">${catOptions}</select>
                    <div class="add-option-btn" onclick="openAddModal(this, 'category')">+ Add new category</div>
                </div>
                
                <div>
                    <label>Vendor</label>
                    <select name="items[${rowCount}][supplier_vendor]">${vendorOptions}</select>
                </div>
                
                <div>
                    <label>UOM</label>
                    <select name="items[${rowCount}][uom]" class="uom-select">${uomOptions}</select>
                    <div class="add-option-btn" onclick="openAddModal(this, 'uom')">+ Add new UOM</div>
                </div>

                <div><label>Initial Stock</label><input type="number" step="0.01" name="items[${rowCount}][initial_stock]" value="0"></div>
                <div><label>Reorder Level</label><input type="number" step="0.01" name="items[${rowCount}][reorder_level]" value="0"></div>
            </div>

            <div style="margin-top:20px;">
                <label>Description</label>
                <textarea name="items[${rowCount}][description]" rows="2" placeholder="Detailed description..."></textarea>
            </div>
        </div>`;

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

function addSerialField(rowId) {
    const container = document.getElementById(`serial-container-${rowId}`);
    const div = document.createElement('div');
    div.className = 'serial-input';
    div.innerHTML = `<input type="text" name="items[${rowId}][serial_number][]" placeholder="Enter serial number">`;
    container.appendChild(div);
}

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

// Modal
let currentType = '';
let currentSelect = null;

function openAddModal(btn, type) {
    currentType = type;
    currentSelect = btn.previousElementSibling;
    document.getElementById('modalTitle').textContent = type === 'category' ? 'Add New Category' : 'Add New UOM';
    document.getElementById('modalName').value = '';
    document.getElementById('addModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('addModal').style.display = 'none';
}

function saveModal() {
    const name = document.getElementById('modalName').value.trim();
    if (!name) return alert("Name is required");

    const action = currentType === 'category' ? 'add_category' : 'add_uom';

    fetch('', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `action=${action}&name=${encodeURIComponent(name)}`
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            const selects = document.querySelectorAll(currentType === 'category' ? '.category-select' : '.uom-select');
            selects.forEach(select => {
                const opt = document.createElement('option');
                opt.value = data.id;
                opt.textContent = data.name;
                select.appendChild(opt);
            });
            if (currentSelect) currentSelect.value = data.id;
            closeModal();
        } else {
            alert(data.message || "Failed to add");
        }
    });
}

window.onload = () => {
    addNewRow(); // Start with one row
};
</script>
</body>
</html>

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