<?php
// gerenciar_apps.php

// Configuração do banco de dados
$dbPath = __DIR__ . '/api/max.db';
$db = new PDO('sqlite:' . $dbPath);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Processa exclusão
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    try {
        // Busca o app para remover arquivos
        $stmt = $db->prepare("SELECT icon_url, apk_url FROM apps WHERE id = :id");
        $stmt->execute([':id' => $_GET['delete']]);
        $app = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($app) {
            // Extrai nomes dos arquivos das URLs
            $iconPath = __DIR__ . '/uploads/icons/' . basename($app['icon_url']);
            $apkPath = __DIR__ . '/uploads/apks/' . basename($app['apk_url']);
            
            // Remove arquivos físicos
            if (file_exists($iconPath)) unlink($iconPath);
            if (file_exists($apkPath)) unlink($apkPath);
            
            // Remove do banco
            $stmt = $db->prepare("DELETE FROM apps WHERE id = :id");
            $stmt->execute([':id' => $_GET['delete']]);
            
            header('Location: gerenciar_apps.php?msg=excluido');
            exit;
        }
    } catch (PDOException $e) {
        $erro = "Erro ao excluir: " . $e->getMessage();
    }
}

// Processa atualização
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_id'])) {
    try {
        $id = $_POST['edit_id'];
        $name = $_POST['name'];
        $package = $_POST['package'];
        
        // Atualiza dados básicos
        $stmt = $db->prepare("UPDATE apps SET name = :name, package = :package WHERE id = :id");
        $stmt->execute([
            ':name' => $name,
            ':package' => $package,
            ':id' => $id
        ]);
        
        // Atualiza ícone se enviado
        if (isset($_FILES['icon_file']) && $_FILES['icon_file']['size'] > 0) {
            // Remove ícone antigo
            $stmt = $db->prepare("SELECT icon_url FROM apps WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $app = $stmt->fetch(PDO::FETCH_ASSOC);
            $oldIconPath = __DIR__ . '/uploads/icons/' . basename($app['icon_url']);
            if (file_exists($oldIconPath)) unlink($oldIconPath);
            
            // Salva novo ícone
            $iconName = uniqid('icon_') . '_' . basename($_FILES['icon_file']['name']);
            $iconPath = __DIR__ . '/uploads/icons/' . $iconName;
            move_uploaded_file($_FILES['icon_file']['tmp_name'], $iconPath);
            
            $baseURL = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
            $iconUrl = $baseURL . "/uploads/icons/" . $iconName;
            
            $stmt = $db->prepare("UPDATE apps SET icon_url = :icon_url WHERE id = :id");
            $stmt->execute([':icon_url' => $iconUrl, ':id' => $id]);
        }
        
        // Atualiza APK se enviado
        if (isset($_FILES['apk_file']) && $_FILES['apk_file']['size'] > 0) {
            // Remove APK antigo
            $stmt = $db->prepare("SELECT apk_url FROM apps WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $app = $stmt->fetch(PDO::FETCH_ASSOC);
            $oldApkPath = __DIR__ . '/uploads/apks/' . basename($app['apk_url']);
            if (file_exists($oldApkPath)) unlink($oldApkPath);
            
            // Salva novo APK
            $apkName = uniqid('apk_') . '_' . basename($_FILES['apk_file']['name']);
            $apkPath = __DIR__ . '/uploads/apks/' . $apkName;
            move_uploaded_file($_FILES['apk_file']['tmp_name'], $apkPath);
            
            $baseURL = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
            $apkUrl = $baseURL . "/uploads/apks/" . $apkName;
            
            $stmt = $db->prepare("UPDATE apps SET apk_url = :apk_url WHERE id = :id");
            $stmt->execute([':apk_url' => $apkUrl, ':id' => $id]);
        }
        
        header('Location: gerenciar_apps.php?msg=atualizado');
        exit;
    } catch (PDOException $e) {
        $erro = "Erro ao atualizar: " . $e->getMessage();
    }
}

// Busca todos os apps
try {
    $stmt = $db->query("SELECT * FROM apps ORDER BY id DESC");
    $apps = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $erro = "Erro ao buscar apps: " . $e->getMessage();
    $apps = [];
}

// Se for uma requisição AJAX para editar
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    header('Content-Type: application/json');
    try {
        $stmt = $db->prepare("SELECT * FROM apps WHERE id = :id");
        $stmt->execute([':id' => $_GET['edit']]);
        $app = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode($app);
        exit;
    } catch (PDOException $e) {
        echo json_encode(['error' => $e->getMessage()]);
        exit;
    }
}
?>
<?php include './includes/header.php'; ?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Aplicativos</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            background-color: #663399;
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: #8e44d6;
            color: white;
        }

        .btn-primary:hover {
            background-color: #a055e8;
        }

        .btn-edit {
            background-color: #4CAF50;
            color: white;
        }

        .btn-edit:hover {
            background-color: #45a049;
        }

        .btn-delete {
            background-color: #f44336;
            color: white;
        }

        .btn-delete:hover {
            background-color: #da190b;
        }

        .card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th,
        .table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .table th {
            background-color: #663399;
            color: white;
        }

        .table tr:hover {
            background-color: #f8f8f8;
        }

        .app-icon {
            width: 40px;
            height: 40px;
            object-fit: contain;
            border-radius: 8px;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-content {
            background-color: white;
            margin: 50px auto;
            padding: 20px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .empty-state {
            text-align: center;
            padding: 50px;
            color: #666;
        }

        /* ========== RESPONSIVIDADE MOBILE ========== */
        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                text-align: center;
                gap: 15px;
                padding: 15px;
            }
            
            .table {
                display: block;
                overflow-x: auto;
            }
            
            .table th, .table td {
                padding: 10px 8px;
                font-size: 14px;
            }
            
            .btn {
                padding: 8px 12px;
                font-size: 14px;
            }
            
            .modal-content {
                width: 95%;
                margin: 20px auto;
                padding: 15px;
            }
        }

        @media (max-width: 600px) {
            .table thead {
                display: none;
            }
            
            .table, .table tbody, .table tr, .table td {
                display: block;
                width: 100%;
            }
            
            .table tr {
                margin-bottom: 15px;
                border: 1px solid #ddd;
                border-radius: 5px;
                padding: 10px;
            }
            
            .table td {
                text-align: right;
                padding-left: 50%;
                position: relative;
                border-bottom: 1px solid #eee;
            }
            
            .table td::before {
                content: attr(data-label);
                position: absolute;
                left: 10px;
                width: 45%;
                padding-right: 10px;
                text-align: left;
                font-weight: bold;
                color: #663399;
            }
            
            .table td:last-child {
                text-align: center;
                padding-left: 10px;
                display: flex;
                flex-direction: column;
                gap: 5px;
            }
            
            .table td:last-child::before {
                display: none;
            }
        }

        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 1.5rem;
            }
            
            .table td {
                padding: 8px 5px 8px 50%;
                font-size: 12px;
            }
            
            .app-icon {
                width: 30px;
                height: 30px;
            }
            
            .btn {
                padding: 6px 8px;
                font-size: 12px;
            }
            
            .btn i {
                font-size: 12px;
            }
            
            .form-control {
                padding: 8px;
            }
            
            .empty-state {
                padding: 30px 15px;
            }
            
            .empty-state i {
                font-size: 2rem;
            }
            
            .empty-state h2 {
                font-size: 1.2rem;
            }
            
            .modal-content {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                width: 100%;
                height: 100%;
                margin: 0;
                border-radius: 0;
                overflow-y: auto;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Gerenciar Aplicativos</h1>
            <a href="gerenciar_apps.php" class="btn btn-primary">
            </a>
        </div>

        <?php if (isset($_GET['msg'])): ?>
            <div class="alert alert-success">
                <?php
                if ($_GET['msg'] === 'excluido') echo 'Aplicativo excluído com sucesso!';
                if ($_GET['msg'] === 'atualizado') echo 'Aplicativo atualizado com sucesso!';
                ?>
            </div>
        <?php endif; ?>

        <?php if (isset($erro)): ?>
            <div class="alert alert-error">
                <?php echo htmlspecialchars($erro); ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <?php if (count($apps) > 0): ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Ícone</th>
                            <th>Nome</th>
                            <th>Pacote</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($apps as $app): ?>
                            <tr>
                                <td data-label="Ícone">
                                    <img src="<?php echo htmlspecialchars($app['icon_url']); ?>" 
                                         alt="Ícone" 
                                         class="app-icon">
                                </td>
                                <td data-label="Nome"><?php echo htmlspecialchars($app['name']); ?></td>
                                <td data-label="Pacote"><?php echo htmlspecialchars($app['package']); ?></td>
                                <td data-label="Ações">
                                    <button class="btn btn-edit" onclick="editApp(<?php echo $app['id']; ?>)">
                                        <i class="fas fa-edit"></i> Editar
                                    </button>
                                    <a href="?delete=<?php echo $app['id']; ?>" 
                                       class="btn btn-delete" 
                                       onclick="return confirm('Tem certeza que deseja excluir este aplicativo?')">
                                        <i class="fas fa-trash"></i> Excluir
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fas fa-box-open fa-3x"></i>
                    <h2>Nenhum aplicativo cadastrado</h2>
                    <p>Adicione um novo aplicativo no painel para começar.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Modal de Edição -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Editar Aplicativo</h2>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="edit_id" id="edit_id">
                
                <div class="form-group">
                    <label>Nome do Aplicativo:</label>
                    <input type="text" name="name" id="edit_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Pacote (ex: com.exemplo.app):</label>
                    <input type="text" name="package" id="edit_package" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>Novo Ícone (deixe em branco para manter o atual):</label>
                    <input type="file" name="icon_file" class="form-control" accept="image/*">
                </div>
                
                <div class="form-group">
                    <label>Novo APK (deixe em branco para manter o atual):</label>
                    <input type="file" name="apk_file" class="form-control" accept=".apk">
                </div>
                
                <button type="submit" class="btn btn-primary">Salvar Alterações</button>
            </form>
        </div>
    </div>

    <script>
        function editApp(id) {
            fetch('?edit=' + id)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('edit_id').value = data.id;
                    document.getElementById('edit_name').value = data.name;
                    document.getElementById('edit_package').value = data.package;
                    document.getElementById('editModal').style.display = 'block';
                })
                .catch(error => {
                    alert('Erro ao carregar dados do aplicativo');
                    console.error(error);
                });
        }

        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // Fecha o modal ao clicar fora dele
        window.onclick = function(event) {
            if (event.target == document.getElementById('editModal')) {
                closeModal();
            }
        }

        // Melhorar toques em botões (para mobile)
        document.querySelectorAll('.btn').forEach(button => {
            button.addEventListener('touchstart', function() {
                this.style.transform = 'scale(0.95)';
            });
            
            button.addEventListener('touchend', function() {
                this.style.transform = 'scale(1)';
            });
        });

        // Prevenir zoom duplo-toque em botões
        document.addEventListener('dblclick', function(e) {
            if (e.target.classList.contains('btn')) {
                e.preventDefault();
            }
        }, { passive: false });
    </script>
</body>
</html>
<?php include './includes/footer.php'; ?>