<?php
// app/Controllers/CategoryController.php

class CategoryController {
    private function requireAdmin() {
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
            header('Location: /login'); exit;
        }
    }

    public function index() {
        $this->requireAdmin();
        $db = getDB();
        $stmt = $db->prepare('SELECT * FROM categories WHERE restaurant_id = ? ORDER BY name ASC');
        $stmt->execute([$_SESSION['restaurant_id']]);
        $categories = $stmt->fetchAll();
        $pageTitle = 'Categories';

        ob_start(); ?>
<div class="space-y-6">
    <!-- Action/Toast Messages -->
    <?php if(isset($_GET['msg']) || isset($_GET['success'])): ?>
    <div x-data="{ show: true }" x-show="show" x-init="setTimeout(() => show = false, 4000)" class="flex items-center gap-3 px-4 py-3 rounded-xl shadow-xl text-sm font-medium border mb-4" style="background:rgba(16,185,129,0.1); color:#6ee7b7; border-color:rgba(16,185,129,0.2)">
        <i class="fas fa-check-circle"></i> <?php echo isset($_GET['msg']) ? htmlspecialchars($_GET['msg']) : 'Category saved successfully!'; ?>
    </div>
    <?php endif; ?>

    <div class="flex gap-4">
        <form action="/admin/categories/store" method="POST" class="flex gap-3 flex-1 max-w-lg">
            <input type="text" name="name" required placeholder="New category name..." class="flex-1 px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
            <button type="submit" class="px-5 py-2.5 rounded-xl text-white font-semibold text-sm transition" style="background:linear-gradient(135deg,#10b981,#059669)"><i class="fas fa-plus mr-1"></i> Add Category</button>
        </form>
    </div>

    <div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
        <table class="w-full text-sm">
            <thead><tr class="border-b border-white/5">
                <th class="text-left px-6 py-4 text-slate-500 font-medium">Category Name</th>
                <th class="text-left px-6 py-4 text-slate-500 font-medium">Status</th>
                <th class="text-right px-6 py-4 text-slate-500 font-medium">Actions</th>
            </tr></thead>
            <tbody>
                <?php if(empty($categories)): ?><tr><td colspan="3" class="px-6 py-10 text-center text-slate-500">No categories yet.</td></tr><?php endif; ?>
                <?php foreach($categories as $c): ?>
                <tr class="border-b border-white/5 hover:bg-white/5 transition">
                    <td class="px-6 py-4 font-medium text-white"><?php echo htmlspecialchars($c['name']); ?></td>
                    <td class="px-6 py-4">
                        <span class="px-2.5 py-0.5 rounded-full text-xs font-semibold" 
                              style="<?php echo $c['status'] === 'active' ? 'background:rgba(16,185,129,0.15); color:#6ee7b7' : 'background:rgba(239,68,68,0.15); color:#f87171'; ?>">
                            <?php echo ucfirst($c['status'] ?? 'active'); ?>
                        </span>
                    </td>
                    <td class="px-6 py-4 text-right">
                        <div class="flex justify-end items-center gap-2">
                            <!-- Edit Button -->
                            <button onclick="openEditCategoryModal(<?php echo $c['id']; ?>, '<?php echo addslashes($c['name']); ?>', '<?php echo $c['status'] ?? 'active'; ?>')" 
                                    class="w-8 h-8 rounded-lg flex items-center justify-center text-xs transition bg-blue-500/10 text-blue-400 border border-blue-500/20 hover:bg-blue-500/20">
                                <i class="fas fa-edit"></i>
                            </button>
                            <!-- Delete Button Form -->
                            <form action="/admin/categories/delete" method="POST" class="inline" 
                                  onsubmit="return confirm('WARNING: Deleting the category \'<?php echo addslashes($c['name']); ?>\' will AUTOMATICALLY delete all products under it!\n\nAre you sure you want to delete this category? This action cannot be undone.')">
                                <input type="hidden" name="category_id" value="<?php echo $c['id']; ?>">
                                <button type="submit" 
                                        class="w-8 h-8 rounded-lg flex items-center justify-center text-xs transition bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Edit Category Modal -->
<div id="editCategoryModal" class="hidden fixed inset-0 z-50 flex items-center justify-center modal-backdrop">
    <div class="modal-box w-full max-w-md mx-4 shadow-2xl overflow-hidden">
        <div class="px-6 py-4 border-b border-white/5 flex justify-between items-center bg-white/5">
            <h3 class="font-semibold text-white text-base">Edit Category</h3>
            <button onclick="closeEditCategoryModal()" class="text-slate-400 hover:text-white transition">
                <i class="fas fa-times text-lg"></i>
            </button>
        </div>
        <form action="/admin/categories/update" method="POST" class="p-6 space-y-4">
            <input type="hidden" name="category_id" id="editCategoryId">
            
            <!-- Category Name -->
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Category Name *</label>
                <input type="text" name="name" id="editCategoryName" required placeholder="Category name..." 
                       class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500 transition" 
                       style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
            </div>

            <!-- Status Selection -->
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Status</label>
                <div class="flex gap-4">
                    <label class="flex items-center gap-2 cursor-pointer text-sm text-slate-300">
                        <input type="radio" name="status" id="statusActive" value="active" class="accent-emerald-500"> Active
                    </label>
                    <label class="flex items-center gap-2 cursor-pointer text-sm text-slate-300">
                        <input type="radio" name="status" id="statusInactive" value="inactive" class="accent-red-500"> Inactive
                    </label>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex gap-3 pt-3 border-t border-white/5 mt-6">
                <button type="submit" class="flex-1 py-2.5 rounded-xl font-semibold text-white text-sm transition" 
                        style="background:linear-gradient(135deg,#10b981,#059669)">
                    <i class="fas fa-save mr-1.5"></i> Save Changes
                </button>
                <button type="button" onclick="closeEditCategoryModal()" 
                        class="px-5 py-2.5 rounded-xl text-slate-400 hover:text-white text-sm transition" 
                        style="background:rgba(255,255,255,0.05)">
                    Cancel
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function openEditCategoryModal(id, name, status) {
    document.getElementById('editCategoryId').value = id;
    document.getElementById('editCategoryName').value = name;
    if (status === 'active') {
        document.getElementById('statusActive').checked = true;
    } else {
        document.getElementById('statusInactive').checked = true;
    }
    document.getElementById('editCategoryModal').classList.remove('hidden');
}

function closeEditCategoryModal() {
    document.getElementById('editCategoryModal').classList.add('hidden');
}
</script>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function store() {
        $this->requireAdmin();
        $db = getDB();
        $db->prepare('INSERT INTO categories (restaurant_id, name) VALUES (?, ?)')
           ->execute([$_SESSION['restaurant_id'], $_POST['name']]);
        header('Location: /admin/categories?success=1'); exit;
    }

    public function update() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $cat_id = intval($_POST['category_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $status = $_POST['status'] ?? 'active';

        if ($cat_id > 0 && !empty($name)) {
            $stmt = $db->prepare('UPDATE categories SET name = ?, status = ? WHERE id = ? AND restaurant_id = ?');
            $stmt->execute([$name, $status, $cat_id, $rest_id]);
        }

        header('Location: /admin/categories?msg=Category+updated');
        exit;
    }

    public function delete() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $cat_id = intval($_POST['category_id'] ?? 0);

        if ($cat_id > 0) {
            $stmt = $db->prepare('DELETE FROM categories WHERE id = ? AND restaurant_id = ?');
            $stmt->execute([$cat_id, $rest_id]);
        }

        header('Location: /admin/categories?msg=Category+deleted');
        exit;
    }
}
