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

// Get Inventory ID from URL
$inventory_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($inventory_id <= 0) {
    header("Location: inventory-management.php");
    exit();
}

// Fetch existing data
$stmt = $conn->prepare("
    SELECT im.*, 
           w.warehouse_name, w.location,
           c.category, 
           v.vendor_name,
           u.uom_name
    FROM inventory_master im
    LEFT JOIN warehouse_master w ON im.warehouse_id = w.id
    LEFT JOIN category_tbl c ON im.category = c.id
    LEFT JOIN vendor_master v ON im.supplier_vendor = v.id
    LEFT JOIN uom_tbl u ON im.uom = u.id
    WHERE im.id = ?
");
$stmt->bind_param("i", $inventory_id);
$stmt->execute();
$material = $stmt->get_result()->fetch_assoc();

if (!$material) {
    $error = "Material not found.";
}

// Fetch Serial Numbers
$serials_result = $conn->query("SELECT serial_number FROM inventory_serials WHERE inventory_id = $inventory_id");
$existing_serials = [];
while ($row = $serials_result->fetch_assoc()) {
    $existing_serials[] = $row['serial_number'];
}

// Fetch all dropdown data
$warehouses = $conn->query("SELECT id, warehouse_name, location FROM warehouse_master WHERE status = 'Active' ORDER BY warehouse_name ASC")->fetch_all(MYSQLI_ASSOC);
$vendors = $conn->query("SELECT id, vendor_name FROM vendor_master ORDER BY vendor_name ASC")->fetch_all(MYSQLI_ASSOC);
$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;
}

// ====================== FORM SUBMISSION ======================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    $warehouse_id   = (int)($_POST['warehouse_id'] ?? 0);
    $name           = trim($_POST['name'] ?? '');
    $description    = trim($_POST['description'] ?? '');
    $hsn_sac        = trim($_POST['hsn_sac'] ?? '');
    $category       = (int)($_POST['category'] ?? 0);
    $model_no       = trim($_POST['model_no'] ?? '');
    $supplier_vendor = (int)($_POST['supplier_vendor'] ?? 0);
    $uom            = (int)($_POST['uom'] ?? 0);
    $current_stock  = (float)($_POST['current_stock'] ?? 0);
    $reorder_level  = (float)($_POST['reorder_level'] ?? 0);
    $serial_numbers = array_filter(array_map('trim', $_POST['serial_number'] ?? []));

    if ($warehouse_id <= 0 || empty($name) || empty($model_no)) {
        $error = "Please fill all required fields.";
    } else {
        try {
            $conn->begin_transaction();

            // Update main record
            $stmt = $conn->prepare("UPDATE inventory_master SET 
                warehouse_id = ?, name = ?, description = ?, hsn_sac = ?, category = ?,
                model_no = ?, supplier_vendor = ?, uom = ?, current_stock = ?, 
                reorder_level = ? WHERE id = ?");

            $stmt->bind_param("issssisssdi", 
                $warehouse_id, $name, $description, $hsn_sac, $category,
                $model_no, $supplier_vendor, $uom, $current_stock, 
                $reorder_level, $inventory_id
            );
            $stmt->execute();

            // Delete old serials and insert new ones
            $conn->query("DELETE FROM inventory_serials WHERE inventory_id = $inventory_id");

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

            $conn->commit();
            $success = "Material updated successfully!";

            // Refresh data
            $stmt->close();
            header("Location: edit-materials.php?id=$inventory_id&success=1");
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Update failed: " . $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 Material - <?= htmlspecialchars($material['name'] ?? '') ?></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: 1100px; 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;
            position: relative;
        }
        .header h1 { 
            font-size: clamp(28px, 5vw, 40px); 
            font-weight: 700; 
        }

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

        .info-card {
            background: rgba(255,255,255,0.07);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 30px;
        }

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

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

        .serial-input {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
            align-items: center;
        }

        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;
        }

        .remove-serial {
            background: #ef4444;
            color: white;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
        }

        .add-row-btn, .submit-btn {
            width: 100%;
            padding: 18px;
            border-radius: 18px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            margin: 25px 0;
        }
        .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; }
            .form-grid { grid-template-columns: 1fr; }
        }
    </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-edit"></i> Edit Material</h1>
            <p style="margin-top:10px; opacity:0.9;"><?= htmlspecialchars($material['sku'] ?? '') ?></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 method="POST" id="editForm">

                <div class="info-card">
                    <strong>SKU:</strong> <?= htmlspecialchars($material['sku'] ?? '') ?> 
                    | <strong>Warehouse:</strong> <?= htmlspecialchars($material['warehouse_name'] ?? '') ?> 
                    (<?= htmlspecialchars($material['location'] ?? '') ?>)
                </div>

                <div class="form-grid">
                    <div>
                        <label>Material Name <span class="required">*</span></label>
                        <input type="text" name="name" value="<?= htmlspecialchars($material['name'] ?? '') ?>" required>
                    </div>
                    <div>
                        <label>Model No <span class="required">*</span></label>
                        <input type="text" name="model_no" value="<?= htmlspecialchars($material['model_no'] ?? '') ?>" required>
                    </div>

                    <div>
                        <label>Warehouse <span class="required">*</span></label>
                        <select name="warehouse_id" required>
                            <?php foreach ($warehouses as $w): ?>
                                <option value="<?= $w['id'] ?>" <?= $w['id'] == $material['warehouse_id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($w['warehouse_name']) ?> — <?= htmlspecialchars($w['location']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label>Category</label>
                        <select name="category" class="category-select">
                            <option value="">-- Select Category --</option>
                            <?php foreach ($categories as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= $c['id'] == $material['category'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['category']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="add-option-btn" onclick="openAddModal(this, 'category')" style="margin-top:8px; cursor:pointer; color:var(--primary);">
                            + Add new category
                        </div>
                    </div>

                    <div>
                        <label>Vendor</label>
                        <select name="supplier_vendor">
                            <option value="">-- Choose Vendor --</option>
                            <?php foreach ($vendors as $v): ?>
                                <option value="<?= $v['id'] ?>" <?= $v['id'] == $material['supplier_vendor'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($v['vendor_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label>UOM</label>
                        <select name="uom" class="uom-select">
                            <option value="">-- Select UOM --</option>
                            <?php foreach ($uoms as $u): ?>
                                <option value="<?= $u['id'] ?>" <?= $u['id'] == $material['uom'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($u['uom_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="add-option-btn" onclick="openAddModal(this, 'uom')" style="margin-top:8px; cursor:pointer; color:var(--primary);">
                            + Add new UOM
                        </div>
                    </div>

                    <div>
                        <label>HSN/SAC</label>
                        <input type="text" name="hsn_sac" value="<?= htmlspecialchars($material['hsn_sac'] ?? '') ?>">
                    </div>

                    <div>
                        <label>Current Stock</label>
                        <input type="number" step="0.01" name="current_stock" value="<?= $material['current_stock'] ?? 0 ?>">
                    </div>

                    <div>
                        <label>Reorder Level</label>
                        <input type="number" step="0.01" name="reorder_level" value="<?= $material['reorder_level'] ?? 0 ?>">
                    </div>
                </div>

                <!-- Serial Numbers -->
                <div style="margin-top: 30px;">
                    <label>Serial Numbers (One per line)</label>
                    <div class="serial-container" id="serial-container">
                        <?php if (!empty($existing_serials)): ?>
                            <?php foreach ($existing_serials as $serial): ?>
                                <div class="serial-input">
                                    <input type="text" name="serial_number[]" value="<?= htmlspecialchars($serial) ?>">
                                    <button type="button" class="remove-serial" onclick="this.parentElement.remove()">×</button>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="serial-input">
                                <input type="text" name="serial_number[]" placeholder="Enter serial number">
                                <button type="button" class="remove-serial" onclick="this.parentElement.remove()">×</button>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div onclick="addSerialField()" style="color:var(--primary); cursor:pointer; margin-top:10px; display:inline-block;">
                        + Add another serial number
                    </div>
                </div>

                <div style="margin-top: 30px;">
                    <label>Description</label>
                    <textarea name="description" rows="4"><?= htmlspecialchars($material['description'] ?? '') ?></textarea>
                </div>

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

<!-- Add Modal (Same as Add Page) -->
<div id="addModal" class="modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.8); align-items:center; justify-content:center; z-index:1000;">
    <div style="background:#1e2937; padding:30px; border-radius:20px; width:90%; max-width:420px;">
        <h3 id="modalTitle" style="margin-bottom:20px;">Add New</h3>
        <input type="text" id="modalName" placeholder="Enter Name" style="width:100%; padding:14px; margin-bottom:20px; border-radius:12px; border:none;">
        <div style="display:flex; gap:12px;">
            <button onclick="closeModal()" style="flex:1; padding:14px; background:#334155; color:white; border:none; border-radius:12px; cursor:pointer;">Cancel</button>
            <button onclick="saveModal()" style="flex:1; padding:14px; background:linear-gradient(135deg,#a855f7,#c084fc); color:white; border:none; border-radius:12px; cursor:pointer;">Save</button>
        </div>
    </div>
</div>

<script>
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");
        }
    });
}

function addSerialField() {
    const container = document.getElementById('serial-container');
    const div = document.createElement('div');
    div.className = 'serial-input';
    div.innerHTML = `
        <input type="text" name="serial_number[]" placeholder="Enter serial number">
        <button type="button" class="remove-serial" onclick="this.parentElement.remove()">×</button>
    `;
    container.appendChild(div);
}

// Auto focus first input
window.onload = () => {
    const firstInput = document.querySelector('input[name="name"]');
    if (firstInput) firstInput.focus();
};
</script>

</body>
</html>

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