<?php
/**
 * Página de Categorias - MontaLoja SaaS
 * Versão Responsiva (Modo Loja/Varejo)
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Verificar se tabela existe
$tableExists = false;
try {
    $checkTable = $pdo->query("SHOW TABLES LIKE 'categories'");
    $tableExists = $checkTable->rowCount() > 0;
} catch (Exception $e) {
    $tableExists = false;
}

// Processar ações
$message = '';
$messageType = '';
$categories = [];

// Verificar mensagens flash
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'info';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

if ($tableExists) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        try {
            if ($action === 'add') {
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $color = $_POST['color'] ?? '#6366F1';
                $icon = trim($_POST['icon'] ?? 'solar:box-bold');
                
                if ($name) {
                    $stmt = $pdo->prepare("INSERT INTO categories (store_id, name, description, color, icon, is_active, sort_order, created_at) VALUES (?, ?, ?, ?, ?, 1, 0, NOW())");
                    $stmt->execute([$storeId, $name, $description, $color, $icon]);
                    $_SESSION['flash_message'] = 'Categoria adicionada com sucesso!';
                    $_SESSION['flash_type'] = 'success';
                }
            } elseif ($action === 'edit') {
                $id = intval($_POST['id'] ?? 0);
                $name = trim($_POST['name'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $color = $_POST['color'] ?? '#6366F1';
                $icon = trim($_POST['icon'] ?? 'solar:box-bold');
                
                if ($id && $name) {
                    $stmt = $pdo->prepare("UPDATE categories SET name = ?, description = ?, color = ?, icon = ? WHERE id = ? AND store_id = ?");
                    $stmt->execute([$name, $description, $color, $icon, $id, $storeId]);
                    $_SESSION['flash_message'] = 'Categoria atualizada!';
                    $_SESSION['flash_type'] = 'success';
                }
            } elseif ($action === 'delete' && isset($_POST['id'])) {
                // Verificar se há produtos na categoria
                $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category_id = ? AND store_id = ?");
                $checkStmt->execute([$_POST['id'], $storeId]);
                $productCount = $checkStmt->fetchColumn();
                
                if ($productCount > 0) {
                    $_SESSION['flash_message'] = 'Não é possível excluir: há produtos nesta categoria.';
                    $_SESSION['flash_type'] = 'error';
                } else {
                    $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ? AND store_id = ?");
                    $stmt->execute([$_POST['id'], $storeId]);
                    $_SESSION['flash_message'] = 'Categoria removida!';
                    $_SESSION['flash_type'] = 'success';
                }
            } elseif ($action === 'toggle' && isset($_POST['id'])) {
                $stmt = $pdo->prepare("UPDATE categories SET is_active = NOT is_active WHERE id = ? AND store_id = ?");
                $stmt->execute([$_POST['id'], $storeId]);
                $_SESSION['flash_message'] = 'Status atualizado!';
                $_SESSION['flash_type'] = 'success';
            }
        } catch (Exception $e) {
            $_SESSION['flash_message'] = 'Erro ao processar: ' . $e->getMessage();
            $_SESSION['flash_type'] = 'error';
        }
        
        // Redirect para evitar resubmissão (PRG pattern)
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }

    // Buscar categorias com contagem de produtos
    try {
        $sql = "SELECT c.*, COUNT(p.id) as product_count 
                FROM categories c 
                LEFT JOIN products p ON c.id = p.category_id AND p.store_id = c.store_id
                WHERE c.store_id = ? 
                GROUP BY c.id 
                ORDER BY c.sort_order ASC, c.name ASC";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$storeId]);
        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $categories = [];
    }
}

$pageTitle = 'Categorias';
include __DIR__ . '/../includes/dashboard-header.php';
?>

<?php include __DIR__ . '/../includes/responsive-styles.php'; ?>


<style>
/* Estilos reutilizáveis movidos para dashboard-components.css */
</style>

    <main class="main-content">
        <div class="page-header page-header-flex">
            <div>
                <h1><iconify-icon icon="solar:folder-bold"></iconify-icon> Categorias</h1>
                <p>Organize seus produtos em categorias</p>
            </div>
            <button class="btn btn-primary" onclick="openAddModal()">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                <span>Nova Categoria</span>
            </button>
        </div>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>">
            <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
            <?php echo $message; ?>
        </div>
        <?php endif; ?>
        
        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <iconify-icon icon="solar:folder-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo count($categories); ?></span>
                    <span class="stat-label">Total de Categorias</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(34, 197, 94, 0.1); color: #22C55E;">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo count(array_filter($categories, fn($c) => $c['is_active'])); ?></span>
                    <span class="stat-label">Ativas</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(59, 130, 246, 0.1); color: #3B82F6;">
                    <iconify-icon icon="solar:box-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo array_sum(array_column($categories, 'product_count')); ?></span>
                    <span class="stat-label">Total de Produtos</span>
                </div>
            </div>
        </div>
        
        <?php if (empty($categories)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:folder-bold"></iconify-icon>
            <h3>Nenhuma categoria cadastrada</h3>
            <p>Crie categorias para organizar seus produtos.</p>
            <button class="btn btn-primary" onclick="openAddModal()" style="margin-top: 1rem;">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                Criar Categoria
            </button>
        </div>
        <?php else: ?>
        
        <!-- Versão Cards (Mobile) -->
        <div class="mobile-cards">
            <?php foreach ($categories as $category): ?>
            <div class="mobile-card">
                <div class="mobile-card-header">
                    <div class="category-icon" style="background: <?php echo htmlspecialchars($category['color'] ?? '#6366F1'); ?>;">
                        <iconify-icon icon="<?php echo htmlspecialchars($category['icon'] ?? 'solar:box-bold'); ?>"></iconify-icon>
                    </div>
                    <div style="flex: 1; margin-left: 0.75rem;">
                        <div class="mobile-card-title"><?php echo htmlspecialchars($category['name']); ?></div>
                        <?php if ($category['description']): ?>
                        <div class="mobile-card-subtitle"><?php echo htmlspecialchars($category['description']); ?></div>
                        <?php endif; ?>
                    </div>
                    <?php if ($category['is_active']): ?>
                    <span class="badge badge-success">Ativa</span>
                    <?php else: ?>
                    <span class="badge badge-secondary">Inativa</span>
                    <?php endif; ?>
                </div>
                
                <div class="mobile-card-info">
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Produtos</div>
                        <div class="mobile-card-info-value"><?php echo $category['product_count']; ?></div>
                    </div>
                    <div class="mobile-card-info-item">
                        <div class="mobile-card-info-label">Criada em</div>
                        <div class="mobile-card-info-value"><?php echo date('d/m/Y', strtotime($category['created_at'])); ?></div>
                    </div>
                </div>
                
                <div class="mobile-card-actions">
                    <button type="button" class="btn btn-secondary btn-sm" style="flex: 1;" onclick='openEditModal(<?php echo json_encode($category); ?>)'>
                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                        Editar
                    </button>
                    <form method="POST" style="flex: 1;">
                        <input type="hidden" name="action" value="toggle">
                        <input type="hidden" name="id" value="<?php echo $category['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="width: 100%;">
                            <iconify-icon icon="<?php echo $category['is_active'] ? 'solar:eye-closed-bold' : 'solar:eye-bold'; ?>"></iconify-icon>
                        </button>
                    </form>
                    <form method="POST" onsubmit="return confirm('Remover esta categoria?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $category['id']; ?>">
                        <button type="submit" class="btn btn-secondary btn-sm" style="color: var(--error);">
                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Versão Tabela (Desktop) -->
        <div class="card desktop-table">
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Categoria</th>
                            <th>Produtos</th>
                            <th>Status</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($categories as $category): ?>
                        <tr>
                            <td>
                                <div style="display: flex; align-items: center; gap: 0.75rem;">
                                    <div class="category-icon" style="background: <?php echo htmlspecialchars($category['color'] ?? '#6366F1'); ?>; width: 40px; height: 40px; font-size: 1.2rem;">
                                        <iconify-icon icon="<?php echo htmlspecialchars($category['icon'] ?? 'solar:box-bold'); ?>"></iconify-icon>
                                    </div>
                                    <div>
                                        <div style="font-weight: 600;"><?php echo htmlspecialchars($category['name']); ?></div>
                                        <?php if ($category['description']): ?>
                                        <div style="font-size: 0.85rem; color: var(--text-muted);"><?php echo htmlspecialchars($category['description']); ?></div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span style="display: flex; align-items: center; gap: 0.5rem;">
                                    <iconify-icon icon="solar:box-bold" style="color: var(--primary);"></iconify-icon>
                                    <?php echo $category['product_count']; ?> produto(s)
                                </span>
                            </td>
                            <td>
                                <span class="badge <?php echo $category['is_active'] ? 'badge-success' : 'badge-secondary'; ?>">
                                    <?php echo $category['is_active'] ? 'Ativa' : 'Inativa'; ?>
                                </span>
                            </td>
                            <td>
                                <div class="actions-cell">
                                    <button type="button" class="btn btn-secondary btn-sm" title="Editar" onclick='openEditModal(<?php echo json_encode($category); ?>)'>
                                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                    </button>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle">
                                        <input type="hidden" name="id" value="<?php echo $category['id']; ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm">
                                            <iconify-icon icon="<?php echo $category['is_active'] ? 'solar:eye-closed-bold' : 'solar:eye-bold'; ?>"></iconify-icon>
                                        </button>
                                    </form>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Remover esta categoria?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $category['id']; ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm" style="color: var(--error);">
                                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </main>
    
    <!-- Modal Adicionar/Editar -->
    <div id="categoryModal" class="modal-overlay">
        <div class="modal-content card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                <h2 id="modalTitle" style="font-size: 1.25rem;">Nova Categoria</h2>
                <button onclick="closeModal()" style="background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 1.5rem;">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </button>
            </div>
            <form method="POST" id="categoryForm">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="categoryId" value="">
                <input type="hidden" name="color" id="categoryColor" value="#6366F1">
                
                <div class="form-group">
                    <label class="form-label">Nome da Categoria *</label>
                    <input type="text" name="name" id="categoryName" class="form-input" placeholder="Ex: Eletrônicos" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Descrição</label>
                    <input type="text" name="description" id="categoryDescription" class="form-input" placeholder="Descrição breve da categoria">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Cor</label>
                    <div class="color-options">
                        <div class="color-option selected" style="background: #6366F1;" data-color="#6366F1" onclick="selectColor(this)"></div>
                        <div class="color-option" style="background: #EC4899;" data-color="#EC4899" onclick="selectColor(this)"></div>
                        <div class="color-option" style="background: #F59E0B;" data-color="#F59E0B" onclick="selectColor(this)"></div>
                        <div class="color-option" style="background: #10B981;" data-color="#10B981" onclick="selectColor(this)"></div>
                        <div class="color-option" style="background: #3B82F6;" data-color="#3B82F6" onclick="selectColor(this)"></div>
                        <div class="color-option" style="background: #8B5CF6;" data-color="#8B5CF6" onclick="selectColor(this)"></div>
                        <div class="color-option" style="background: #EF4444;" data-color="#EF4444" onclick="selectColor(this)"></div>
                        <div class="color-option" style="background: #06B6D4;" data-color="#06B6D4" onclick="selectColor(this)"></div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Ícone</label>
                    <input type="hidden" name="icon" id="categoryIcon" value="solar:box-bold">
                    <div class="icon-picker-box">
                        <input type="text" class="icon-search" id="iconSearch" placeholder="Buscar ícone..." oninput="filterIcons(this.value)">
                        <div class="icon-grid" id="iconGrid">
                            <div class="icon-item" data-icon="solar:t-shirt-bold" onclick="selectIcon('solar:t-shirt-bold')"><iconify-icon icon="solar:t-shirt-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:hanger-bold" onclick="selectIcon('solar:hanger-bold')"><iconify-icon icon="solar:hanger-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:wineglass-bold" onclick="selectIcon('solar:wineglass-bold')"><iconify-icon icon="solar:wineglass-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:watch-square-bold" onclick="selectIcon('solar:watch-square-bold')"><iconify-icon icon="solar:watch-square-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:glasses-bold" onclick="selectIcon('solar:glasses-bold')"><iconify-icon icon="solar:glasses-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:box-bold" onclick="selectIcon('solar:box-bold')"><iconify-icon icon="solar:box-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:bag-bold" onclick="selectIcon('solar:bag-bold')"><iconify-icon icon="solar:bag-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:bag-3-bold" onclick="selectIcon('solar:bag-3-bold')"><iconify-icon icon="solar:bag-3-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:bag-heart-bold" onclick="selectIcon('solar:bag-heart-bold')"><iconify-icon icon="solar:bag-heart-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:cart-bold" onclick="selectIcon('solar:cart-bold')"><iconify-icon icon="solar:cart-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:cart-large-bold" onclick="selectIcon('solar:cart-large-bold')"><iconify-icon icon="solar:cart-large-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:gift-bold" onclick="selectIcon('solar:gift-bold')"><iconify-icon icon="solar:gift-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:crown-bold" onclick="selectIcon('solar:crown-bold')"><iconify-icon icon="solar:crown-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:star-bold" onclick="selectIcon('solar:star-bold')"><iconify-icon icon="solar:star-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:heart-bold" onclick="selectIcon('solar:heart-bold')"><iconify-icon icon="solar:heart-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:tag-bold" onclick="selectIcon('solar:tag-bold')"><iconify-icon icon="solar:tag-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:bookmark-bold" onclick="selectIcon('solar:bookmark-bold')"><iconify-icon icon="solar:bookmark-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:fire-bold" onclick="selectIcon('solar:fire-bold')"><iconify-icon icon="solar:fire-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:home-bold" onclick="selectIcon('solar:home-bold')"><iconify-icon icon="solar:home-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:sofa-bold" onclick="selectIcon('solar:sofa-bold')"><iconify-icon icon="solar:sofa-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:lightbulb-bold" onclick="selectIcon('solar:lightbulb-bold')"><iconify-icon icon="solar:lightbulb-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:phone-bold" onclick="selectIcon('solar:phone-bold')"><iconify-icon icon="solar:phone-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:laptop-bold" onclick="selectIcon('solar:laptop-bold')"><iconify-icon icon="solar:laptop-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:monitor-bold" onclick="selectIcon('solar:monitor-bold')"><iconify-icon icon="solar:monitor-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:headphones-round-bold" onclick="selectIcon('solar:headphones-round-bold')"><iconify-icon icon="solar:headphones-round-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:gamepad-bold" onclick="selectIcon('solar:gamepad-bold')"><iconify-icon icon="solar:gamepad-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:camera-bold" onclick="selectIcon('solar:camera-bold')"><iconify-icon icon="solar:camera-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:cup-hot-bold" onclick="selectIcon('solar:cup-hot-bold')"><iconify-icon icon="solar:cup-hot-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:chef-hat-bold" onclick="selectIcon('solar:chef-hat-bold')"><iconify-icon icon="solar:chef-hat-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:running-bold" onclick="selectIcon('solar:running-bold')"><iconify-icon icon="solar:running-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:dumbbells-bold" onclick="selectIcon('solar:dumbbells-bold')"><iconify-icon icon="solar:dumbbells-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:bolt-bold" onclick="selectIcon('solar:bolt-bold')"><iconify-icon icon="solar:bolt-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:sun-bold" onclick="selectIcon('solar:sun-bold')"><iconify-icon icon="solar:sun-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:palette-bold" onclick="selectIcon('solar:palette-bold')"><iconify-icon icon="solar:palette-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:scissors-bold" onclick="selectIcon('solar:scissors-bold')"><iconify-icon icon="solar:scissors-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:delivery-bold" onclick="selectIcon('solar:delivery-bold')"><iconify-icon icon="solar:delivery-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:map-point-bold" onclick="selectIcon('solar:map-point-bold')"><iconify-icon icon="solar:map-point-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:folder-bold" onclick="selectIcon('solar:folder-bold')"><iconify-icon icon="solar:folder-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:widget-bold" onclick="selectIcon('solar:widget-bold')"><iconify-icon icon="solar:widget-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:user-bold" onclick="selectIcon('solar:user-bold')"><iconify-icon icon="solar:user-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:users-group-rounded-bold" onclick="selectIcon('solar:users-group-rounded-bold')"><iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:book-bold" onclick="selectIcon('solar:book-bold')"><iconify-icon icon="solar:book-bold"></iconify-icon></div>
                            <div class="icon-item" data-icon="solar:document-bold" onclick="selectIcon('solar:document-bold')"><iconify-icon icon="solar:document-bold"></iconify-icon></div>
                        </div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 1rem; justify-content: flex-end; flex-wrap: wrap;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        <span id="submitBtnText">Salvar</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

<script>
function selectColor(el) {
    document.querySelectorAll('.color-option').forEach(c => c.classList.remove('selected'));
    el.classList.add('selected');
    document.getElementById('categoryColor').value = el.dataset.color;
}

function openAddModal() {
    document.getElementById('modalTitle').textContent = 'Nova Categoria';
    document.getElementById('formAction').value = 'add';
    document.getElementById('categoryId').value = '';
    document.getElementById('categoryName').value = '';
    document.getElementById('categoryDescription').value = '';
    document.getElementById('categoryColor').value = '#6366F1';
    document.getElementById('categoryIcon').value = 'solar:box-bold';
    document.querySelectorAll('.color-option').forEach(c => c.classList.remove('selected'));
    selectIcon('solar:box-bold');
    document.querySelector('.color-option[data-color="#6366F1"]').classList.add('selected');
    document.getElementById('submitBtnText').textContent = 'Salvar';
    document.getElementById('categoryModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function openEditModal(category) {
    document.getElementById('modalTitle').textContent = 'Editar Categoria';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('categoryId').value = category.id;
    document.getElementById('categoryName').value = category.name;
    document.getElementById('categoryDescription').value = category.description || '';
    document.getElementById('categoryColor').value = category.color || '#6366F1';
    document.getElementById('categoryIcon').value = category.icon || 'solar:box-bold';
    selectIcon(category.icon || 'solar:box-bold');
    
    document.querySelectorAll('.color-option').forEach(c => {
        c.classList.remove('selected');
        if (c.dataset.color === (category.color || '#6366F1')) {
            c.classList.add('selected');
        }
    });
    
    document.getElementById('submitBtnText').textContent = 'Atualizar';
    document.getElementById('categoryModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

// Função closeModal e listeners de evento removidos.
// Agora controlados globalmente por dashboard-utils.js

// Icon Picker
function selectIcon(iconName) {
    document.getElementById("categoryIcon").value = iconName;
    document.querySelectorAll(".icon-item").forEach(function(el) {
        el.classList.remove("selected");
        if (el.dataset.icon === iconName) el.classList.add("selected");
    });
}

function filterIcons(search) {
    var items = document.querySelectorAll(".icon-item");
    search = search.toLowerCase();
    items.forEach(function(item) {
        var icon = item.dataset.icon.toLowerCase();
        item.style.display = icon.includes(search) ? "" : "none";
    });
}
</script>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
