<?php
require 'db.php';

// 1. Handle SAVE (Add or Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_material') {
    $name = $_POST['name'];
    $unit = $_POST['unit_type'];
    $inv  = $_POST['inventory_number'];
    $id   = $_POST['material_id'] ?? '';

    if (!empty($id)) {
        // UPDATE existing
        $stmt = $pdo->prepare("UPDATE materials SET name=?, unit_type=?, inventory_number=? WHERE id=?");
        $stmt->execute([$name, $unit, $inv, $id]);
    } else {
        // INSERT new
        $stmt = $pdo->prepare("INSERT INTO materials (name, unit_type, inventory_number) VALUES (?, ?, ?)");
        $stmt->execute([$name, $unit, $inv]);
    }
    header("Location: materials.php?success=1");
    exit;
}

// 2. Handle DELETE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    $stmt = $pdo->prepare("DELETE FROM materials WHERE id = ?");
    $stmt->execute([$_POST['delete']]);
    header("Location: materials.php?deleted=1");
    exit;
}

// 3. Handle CREATE KIT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_kit') {
    $kit_name = $_POST['kit_name'];
    $material_ids = $_POST['material_ids'] ?? [];

    if (!empty($kit_name) && !empty($material_ids)) {
        $pdo->beginTransaction();
        $stmtKit = $pdo->prepare("INSERT INTO kits (name) VALUES (?)");
        $stmtKit->execute([$kit_name]);
        $kit_id = $pdo->lastInsertId();

        $stmtItems = $pdo->prepare("INSERT INTO kit_materials (kit_id, material_id, quantity) VALUES (?, ?, 1)");
        foreach ($material_ids as $mid) {
            $stmtItems->execute([$kit_id, $mid]);
        }
        $pdo->commit();
        header("Location: materials.php?kit_created=1");
        exit;
    }
}

// 4. Fetch Data for EDIT MODE
$edit_data = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM materials WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $edit_data = $stmt->fetch();
}

// 5. Fetch All Materials
$search = $_GET['search'] ?? '';
$sql = "SELECT * FROM materials";
$params = [];
if ($search) {
    $sql .= " WHERE name LIKE ? OR inventory_number LIKE ?";
    $params = ["%$search%", "%$search%"];
}
$sql .= " ORDER BY name ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$materials = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Materials Inventory</title>
    <link rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <script>
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            document.documentElement.style.backgroundColor = '#111827';
        } else {
            document.documentElement.classList.remove('dark');
            document.documentElement.style.backgroundColor = '#f3f4f6';
        }
    </script>
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 h-full flex overflow-hidden text-sm"
      x-data="{ kitOpen: false, selectedCount: 0 }">

    <?php include 'sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-full overflow-hidden relative">
        <header class="h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0 z-10">
            <button class="open-sidebar-btn md:hidden mr-3 text-gray-500 hover:text-blue-600 transition">
    <i class="fas fa-bars text-xl"></i>
</button>
            <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200">
                <?= $edit_data ? 'Edit Material' : 'Materials Inventory' ?>
            </h2>
        </header>

        <div class="flex-1 overflow-auto p-4">
            
            <form method="POST" class="bg-white dark:bg-gray-800 p-4 rounded shadow border dark:border-gray-700 mb-6 transition-all">
                <input type="hidden" name="action" value="save_material">
                <input type="hidden" name="material_id" value="<?= $edit_data['id'] ?? '' ?>">

                <div class="flex flex-col md:flex-row gap-4 items-end">
                    <div class="flex-1 w-full">
                        <label class="block text-xs font-bold mb-1 text-gray-500 dark:text-gray-400 uppercase">Material Name</label>
                        <input type="text" name="name" value="<?= htmlspecialchars($edit_data['name'] ?? '') ?>" placeholder="e.g. Fiber Drop Cable" required class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2 focus:outline-none focus:border-blue-500 transition h-[38px]">
                    </div>
                    <div class="w-full md:w-32">
                        <label class="block text-xs font-bold mb-1 text-gray-500 dark:text-gray-400 uppercase">Inventory #</label>
                        <input type="text" name="inventory_number" value="<?= htmlspecialchars($edit_data['inventory_number'] ?? '') ?>" placeholder="Inv #" class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2 focus:outline-none focus:border-blue-500 transition h-[38px]">
                    </div>
                    <div class="w-full md:w-32">
                        <label class="block text-xs font-bold mb-1 text-gray-500 dark:text-gray-400 uppercase">Unit Type</label>
                        <select name="unit_type" class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2 focus:outline-none focus:border-blue-500 transition h-[38px]">
                            <?php 
                            $u = $edit_data['unit_type'] ?? 'ea';
                            $opts = ['ea'=>'Each', 'ft'=>'Feet', 'm'=>'Meters', 'box'=>'Box', 'roll'=>'Roll'];
                            foreach($opts as $val => $label) {
                                $sel = ($u === $val) ? 'selected' : '';
                                echo "<option value='$val' $sel>$label</option>";
                            }
                            ?>
                        </select>
                    </div>
                    
                    <div class="flex gap-2 w-full md:w-auto">
                        <?php if($edit_data): ?>
                            <a href="materials.php" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded font-bold uppercase text-xs shadow transition h-[38px] flex items-center justify-center">
                                Cancel
                            </a>
                            <button type="submit" class="flex-1 bg-green-600 hover:bg-green-500 text-white px-6 py-2 rounded font-bold uppercase text-xs shadow transition h-[38px] flex items-center justify-center">
                                <i class="fas fa-save mr-2"></i> Update
                            </button>
                        <?php else: ?>
                            <button type="submit" class="w-full bg-blue-600 hover:bg-blue-500 text-white px-6 py-2 rounded font-bold uppercase text-xs shadow transition h-[38px] flex items-center justify-center">
                                <i class="fas fa-plus mr-2"></i> Add
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </form>

            <?php if (isset($_GET['kit_created'])): ?>
                <div class="mb-4 bg-amber-100 border-l-4 border-amber-500 text-amber-800 p-3 rounded shadow">
                    <p class="font-bold"><i class="fas fa-box mr-2"></i> Kit Created Successfully!</p>
                </div>
            <?php endif; ?>

            <div class="flex justify-between items-center mb-2">
                <form class="w-full md:w-auto relative">
                    <i class="fas fa-search absolute left-3 top-2.5 text-gray-400"></i>
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search inventory..." class="pl-9 pr-4 py-1.5 w-full md:w-64 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded shadow-sm focus:outline-none focus:border-blue-500 text-sm h-[34px]">
                </form>
                <div class="text-xs text-gray-500 italic">Select items below to build a Kit</div>
            </div>

            <form id="materialsForm" method="POST">
                <input type="hidden" name="action" value="create_kit">
                <input type="hidden" name="kit_name" id="kitNameInput">

                <div x-show="selectedCount > 0" x-cloak
                     class="absolute bottom-6 left-1/2 transform -translate-x-1/2 bg-slate-800 text-white px-6 py-3 rounded-full shadow-2xl z-50 flex items-center gap-4 animate-bounce-in">
                    <span class="text-xs font-bold uppercase" x-text="selectedCount + ' Selected'"></span>
                    <button type="button" @click="kitOpen = true; $nextTick(() => $refs.kitName.focus())"
                            class="bg-amber-600 hover:bg-amber-500 text-white px-4 py-1 rounded-full text-xs font-bold uppercase transition">
                        <i class="fas fa-box-open mr-1"></i> Create Kit
                    </button>
                </div>

                <div class="bg-white dark:bg-gray-800 rounded shadow overflow-hidden border dark:border-gray-700">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="bg-gray-100 dark:bg-gray-700 text-xs uppercase text-gray-600 dark:text-gray-300 font-bold border-b dark:border-gray-600">
                                <th class="px-4 py-3 w-10 text-center">
                                    <input type="checkbox" @click="document.querySelectorAll('.mat-check').forEach(cb => cb.checked = $event.target.checked); selectedCount = document.querySelectorAll('.mat-check:checked').length"
                           class="cursor-pointer rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                </th>
                                <th class="px-4 py-3 w-32">Inv #</th>
                                <th class="px-4 py-3">Material Name</th>
                                <th class="px-4 py-3 w-24 text-center">Unit</th>
                                <th class="px-4 py-3 w-24 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200 dark:divide-gray-700 text-sm">
                            <?php foreach ($materials as $m): ?>
                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors group">
                                <td class="px-4 py-2 text-center">
                                    <input type="checkbox" name="material_ids[]" value="<?= $m['id'] ?>" @change="selectedCount = document.querySelectorAll('.mat-check:checked').length" class="mat-check cursor-pointer rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                                </td>
                                <td class="px-4 py-2 font-mono text-gray-500"><?= htmlspecialchars($m['inventory_number'] ?? '-') ?></td>
                                <td class="px-4 py-2 font-medium"><?= htmlspecialchars($m['name']) ?></td>
                                <td class="px-4 py-2 text-center text-gray-500"><?= htmlspecialchars($m['unit_type']) ?></td>
                                <td class="px-4 py-2 text-right">
                                    <div class="flex justify-end gap-3">
                                        <a href="?edit=<?= $m['id'] ?>" class="text-gray-400 hover:text-blue-500 transition" title="Edit">
                                            <i class="fas fa-pen"></i>
                                        </a>
                                        <form method="POST" class="inline" onsubmit="return confirm('Delete this material?');">
                                            <input type="hidden" name="delete" value="<?= $m['id'] ?>">
                                            <button type="submit" class="text-gray-400 hover:text-red-600 transition" title="Delete"><i class="fas fa-trash-alt"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
    </main>

    <script>
        function submitKit() {
            const name = document.getElementById('kitModalInput').value.trim();
            if (!name) return;
            document.getElementById('kitNameInput').value = name;
            document.getElementById('materialsForm').submit();
        }
    </script>

    <!-- Kit Name Modal -->
    <div x-show="kitOpen" x-cloak @click.self="kitOpen = false" @keydown.escape.window="kitOpen = false"
         class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-sm mx-4">
            <h3 class="font-bold text-sm uppercase tracking-wide text-gray-700 dark:text-gray-200 mb-4">Name this Kit</h3>
            <input x-ref="kitName" type="text" id="kitModalInput" placeholder="e.g. Fiber Splice A"
                @keydown.enter="submitKit()" @keydown.escape="kitOpen = false"
                class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2 text-sm mb-4 focus:outline-none focus:border-amber-500">
            <div class="flex gap-2 justify-end">
                <button type="button" @click="kitOpen = false"
                    class="px-4 py-2 text-xs font-bold uppercase rounded bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition">Cancel</button>
                <button type="button" @click="submitKit()"
                    class="px-4 py-2 text-xs font-bold uppercase rounded bg-amber-600 hover:bg-amber-500 text-white shadow transition">Create Kit</button>
            </div>
        </div>
    </div>
</body>
</html>