<?php
// OneLauncher - themes.php
require_once 'includes/auth.php';
require_once 'db.php';

$pageTitle = 'Gerenciar Temas';
$nav = 'themes';
$msg = "";
$error = "";

// Criar Tema
if (isset($_POST['add_theme'])) {
    $name = trim($_POST['name']);
    if (!empty($name)) {
        $stmt = $conn->prepare("INSERT INTO themes (name) VALUES (?)");
        $stmt->bind_param("s", $name);
        if ($stmt->execute()) {
            $msg = "Tema criado com sucesso!";
        } else {
            $error = "Erro ao criar tema.";
        }
    } else {
        $error = "O nome do tema não pode ser vazio.";
    }
}

// Editar Tema
if (isset($_POST['edit_theme'])) {
    $id = (int)$_POST['id'];
    $name = trim($_POST['name']);
    
    if ($id == 1) {
        $error = "Não é possível alterar o nome do Tema Padrão.";
    } elseif (!empty($name)) {
        $stmt = $conn->prepare("UPDATE themes SET name = ? WHERE id = ?");
        $stmt->bind_param("si", $name, $id);
        if ($stmt->execute()) {
            $msg = "Tema atualizado com sucesso!";
        } else {
            $error = "Erro ao atualizar tema.";
        }
    } else {
        $error = "O nome do tema não pode ser vazio.";
    }
}

// Excluir Tema
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    if ($id == 1) {
        $error = "Não é possível excluir o Tema Padrão.";
    } else {
        // Option to reassign devices using this theme to theme 1 before deleting
        $conn->query("UPDATE devices SET theme_id = 1 WHERE theme_id = $id");
        $conn->query("DELETE FROM themes WHERE id = $id");
        // Também poderíamos limpar as configs, propaganda, buttons e apps_grid associados a este tema, 
        // mas para manter simples (ou deixar órfãos que não pesam), vamos limpar o principal:
        $conn->query("DELETE FROM config WHERE theme_id = $id");
        
        // Update session if the deleted theme was active
        if (isset($_SESSION['active_theme_id']) && $_SESSION['active_theme_id'] == $id) {
            $_SESSION['active_theme_id'] = 1;
        }

        header("Location: themes.php?msg=deleted");
        exit;
    }
}

if (isset($_GET['msg']) && $_GET['msg'] == 'deleted') $msg = "Tema removido com sucesso. Dispositivos foram movidos para o Tema Padrão.";

$themes = $conn->query("SELECT * FROM themes ORDER BY id ASC");

include 'includes/head.php';
include 'includes/sidebar.php';
include 'includes/topbar.php';
include 'includes/layout-open.php';
?>

<div class="row align-items-center mb-4">
    <div class="col">
        <h2 class="mb-1"><i class="bi bi-palette-fill me-2"></i>Gerenciar Temas</h2>
        <p class="text-white-50 small mb-0">Crie e gerencie os temas visuais (pacotes de cores, botões, ícones e layouts) do sistema.</p>
    </div>
    <div class="col-auto">
        <button class="btn btn-app-primary rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#addThemeModal">
            <i class="bi bi-plus-lg me-2"></i> Novo Tema
        </button>
    </div>
</div>

<?php if ($msg): ?>
    <div class="alert alert-success border-0 bg-success bg-opacity-10 text-success rounded-4 d-flex align-items-center mb-4 p-3 animate__animated animate__fadeIn">
        <i class="bi bi-check-circle-fill me-3 fs-4"></i>
        <div><?php echo $msg; ?></div>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger border-0 bg-danger bg-opacity-10 text-danger rounded-4 d-flex align-items-center mb-4 p-3 animate__animated animate__fadeIn">
        <i class="bi bi-exclamation-triangle-fill me-3 fs-4"></i>
        <div><?php echo $error; ?></div>
    </div>
<?php endif; ?>

<div class="app-card border-white border-opacity-10 overflow-hidden p-0">
    <div class="table-responsive">
        <table class="table table-hover table-dark bg-transparent mb-0">
            <thead class="bg-dark bg-opacity-5">
                <tr>
                    <th class="ps-4 py-3 border-0">ID</th>
                    <th class="py-3 border-0">Nome do Tema</th>
                    <th class="py-3 border-0">Dispositivos Vinculados</th>
                    <th class="text-end pe-4 py-3 border-0">Ações</th>
                </tr>
            </thead>
            <tbody class="border-top-0">
                <?php while($t = $themes->fetch_assoc()): ?>
                    <?php 
                        $devCount = $conn->query("SELECT count(*) as total FROM devices WHERE theme_id = {$t['id']}")->fetch_assoc()['total'];
                    ?>
                    <tr class="align-middle border-white border-opacity-5" style="transition: background 0.15s;">
                        <td class="ps-4">
                            <span class="badge bg-secondary bg-opacity-25 text-white-50 px-2 py-1 rounded-3">#<?php echo $t['id']; ?></span>
                        </td>
                        <td>
                            <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($t['name']); ?></h6>
                            <?php if($t['id'] == 1): ?>
                                <span class="badge bg-primary bg-opacity-25 text-primary border border-primary border-opacity-25 mt-1" style="font-size: 0.65rem;">SISTEMA / DEFAULT</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge bg-white bg-opacity-10 text-white border border-white border-opacity-10 px-3 py-2 rounded-pill">
                                <i class="bi bi-tv me-1"></i> <?php echo $devCount; ?> boxes
                            </span>
                        </td>
                        <td class="text-end pe-4">
                            <?php if ($t['id'] != 1): ?>
                                <button class="btn btn-sm btn-outline-primary border-opacity-25 rounded-3 px-3 me-1" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $t['id']; ?>" title="Editar">
                                    <i class="bi bi-pencil-fill"></i>
                                </button>
                                <button type="button" onclick="globalConfirmDelete('themes.php?delete=<?php echo $t['id']; ?>', 'Remover Tema?', 'ATENÇÃO: Ao excluir este tema, as boxes vinculadas voltarão ao Tema Padrão. Deseja continuar?')" class="btn btn-sm btn-outline-danger border-opacity-25 rounded-3 px-3" title="Excluir">
                                    <i class="bi bi-trash3-fill"></i>
                                </button>
                            <?php else: ?>
                                <button class="btn btn-sm btn-outline-secondary border-opacity-25 rounded-3 px-3 disabled" title="Não é possível alterar o Tema Padrão">
                                    <i class="bi bi-lock-fill"></i> Padrão
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php 
                    $theme_list[] = $t;
                endwhile; 
                ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Adicionar Tema -->
<div class="modal fade" id="addThemeModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-white border-opacity-10 rounded-4" style="background: rgba(16, 25, 53, 0.98); backdrop-filter: blur(20px);">
            <div class="modal-header border-bottom border-white border-opacity-10 p-4">
                <h5 class="modal-title text-white"><i class="bi bi-plus-lg me-2 text-primary"></i>Criar Novo Tema</h5>
                <button type="button" class="btn-close btn-close-white opacity-50" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="form-label text-white-50">Nome de Identificação</label>
                        <input type="text" name="name" class="form-control form-control-lg border-opacity-10 text-white" style="background: rgba(255,255,255,0.05);" required placeholder="Ex: Tema Black, Tema Kids, Cliente XYZ...">
                        <div class="form-text text-white-50 mt-2">Escolha um nome fácil de lembrar. Depois de criado, selecione-o no menu superior para personalizar as cores, botões e grade de apps.</div>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-outline-light border-opacity-25 px-4" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" name="add_theme" class="btn btn-app-primary px-4">Salvar Tema</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modais de Edição -->
<?php if(isset($theme_list)): foreach($theme_list as $t): if($t['id'] != 1): ?>
    <div class="modal fade" id="editModal<?php echo $t['id']; ?>" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-white border-opacity-10 rounded-4" style="background: rgba(16, 25, 53, 0.98); backdrop-filter: blur(20px);">
                <div class="modal-header border-bottom border-white border-opacity-10 p-4">
                    <h5 class="modal-title text-white"><i class="bi bi-pencil-fill me-2 text-primary"></i>Editar Nome do Tema</h5>
                    <button type="button" class="btn-close btn-close-white opacity-50" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body p-4">
                        <input type="hidden" name="id" value="<?php echo $t['id']; ?>">
                        <div class="mb-3">
                            <label class="form-label text-white-50">Nome do Tema</label>
                            <input type="text" name="name" class="form-control form-control-lg border-opacity-10 text-white" style="background: rgba(255,255,255,0.05);" value="<?php echo htmlspecialchars($t['name']); ?>" required>
                        </div>
                    </div>
                    <div class="modal-footer border-0 p-4 pt-0">
                        <button type="button" class="btn btn-outline-light border-opacity-25 px-4" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" name="edit_theme" class="btn btn-app-primary px-4">Salvar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endif; endforeach; endif; ?>

<?php
include 'includes/layout-close.php';
include 'includes/footer.php';
?>
