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

$pageTitle = 'Loja de Apps (App Store)';
$nav = 'apps';
$msg = "";

// Função auxiliar para salvar imagem base64
function saveBase64Image($base64_string, $upload_dir) {
    if (preg_match('/^data:image\/(\w+);base64,/', $base64_string, $type)) {
        $data = substr($base64_string, strpos($base64_string, ',') + 1);
        $type = strtolower($type[1]); // jpg, png, gif

        if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
            return false; // Tipo inválido
        }

        $data = base64_decode($data);
        if ($data === false) {
            return false; // Base64 inválido
        }

        $filename = "icon_" . time() . "_" . bin2hex(random_bytes(4)) . "." . $type;
        $filepath = $upload_dir . '/' . $filename;
        
        if (file_put_contents($filepath, $data)) {
            return $filename;
        }
    }
    return false;
}

// Upload de Novo App
if (isset($_POST['add_app'])) {
    $name = $_POST['name'];
    $package = $_POST['package'];
    $version = $_POST['version'] ?? '1.0.0';
    $add_method = $_POST['add_method'] ?? 'manual';
    
    $icon_url = "";
    $apk_url = "";
    $errors = [];

    $upload_dir = __DIR__ . '/uploads';
    if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);

    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https://' : 'http://';
    $base_url = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/uploads/";

    // Tratamento de Ícone
    if (!empty($_POST['icon_base64'])) {
        $saved_filename = saveBase64Image($_POST['icon_base64'], $upload_dir);
        if ($saved_filename) {
            $icon_url = $base_url . $saved_filename;
        } else {
            $errors[] = "Falha ao processar a imagem do ícone.";
        }
    } else if (isset($_FILES['icon']) && $_FILES['icon']['error'] == 0) {
        $ext = strtolower(pathinfo($_FILES['icon']['name'], PATHINFO_EXTENSION));
        $allowed_image_exts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        if (in_array($ext, $allowed_image_exts)) {
            $filename = "icon_" . time() . "_" . bin2hex(random_bytes(4)) . ".$ext";
            if (move_uploaded_file($_FILES['icon']['tmp_name'], "$upload_dir/$filename")) {
                $icon_url = $base_url . $filename;
            } else {
                $errors[] = "Falha ao salvar o arquivo do ícone.";
            }
        } else {
            $errors[] = "A extensão do arquivo de ícone não é permitida.";
        }
    } else {
        $errors[] = "O ícone do aplicativo é obrigatório.";
    }

    // Tratamento de APK
    if ($add_method !== 'package') {
        if (isset($_FILES['apk']) && $_FILES['apk']['error'] == 0) {
            $ext = strtolower(pathinfo($_FILES['apk']['name'], PATHINFO_EXTENSION));
            if ($ext === 'apk') {
                $filename = "app_" . time() . "_" . bin2hex(random_bytes(4)) . ".apk";
                if (move_uploaded_file($_FILES['apk']['tmp_name'], "$upload_dir/$filename")) {
                    $apk_url = $base_url . $filename;
                } else {
                    $errors[] = "Falha ao salvar o arquivo APK.";
                }
            } else {
                $errors[] = "Apenas arquivos com a extensão .apk são permitidos para o aplicativo.";
            }
        } else {
            $errors[] = "O arquivo APK do aplicativo é obrigatório para este método.";
        }
    }

    if (!empty($errors)) {
        http_response_code(400);
        echo implode(" | ", $errors);
        exit;
    }

    $stmt = $conn->prepare("INSERT INTO app_store (theme_id, name, package_name, icon_url, apk_url, version) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("isssss", $active_theme_id, $name, $package, $icon_url, $apk_url, $version);
    if ($stmt->execute()) {
        echo "App adicionado com sucesso!";
        exit;
    } else {
        http_response_code(500);
        echo "Erro ao adicionar app no banco de dados: " . $conn->error;
        exit;
    }
}

// Ações em Massa (Excluir Selecionados)
if (isset($_POST['bulk_delete']) && !empty($_POST['selected_apps'])) {
    $ids = array_map('intval', $_POST['selected_apps']);
    $ids_string = implode(',', $ids);
    if (!empty($ids_string)) {
        $conn->query("DELETE FROM app_store WHERE id IN ($ids_string) AND theme_id = $active_theme_id");
        echo json_encode(['success' => true]);
        exit;
    }
}

// Excluir App (mantido GET para compatibilidade, mas será usado via AJAX)
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM app_store WHERE id = $id AND theme_id = $active_theme_id");
    header("Location: apps.php?msg=deleted");
    exit;
}

if (isset($_GET['msg']) && $_GET['msg'] == 'deleted') $msg = "App removido da loja.";

$apps = $conn->query("SELECT * FROM app_store WHERE theme_id = $active_theme_id ORDER BY item_order ASC");

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

<!-- Importar biblioteca JS para extrair informações do APK -->
<script src="https://cdn.jsdelivr.net/npm/app-info-parser/dist/app-info-parser.min.js">
// ==========================================
// CUSTOM ICON NO AUTOMÁTICO
// ==========================================
document.getElementById('autoCustomIcon').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if(file) {
        const reader = new FileReader();
        reader.onload = function(evt) {
            document.getElementById('autoPreviewIcon').src = evt.target.result;
            document.getElementById('auto_icon_base64').value = evt.target.result;
        };
        reader.readAsDataURL(file);
    }
});

// ==========================================
// BULK DELETE LÓGICA
// ==========================================
const selectAll = document.getElementById('selectAll');
const appCheckboxes = document.querySelectorAll('.app-checkbox');
const bulkActions = document.getElementById('bulkActions');
const bulkCount = document.getElementById('bulkCount');

function updateBulkUI() {
    const selected = document.querySelectorAll('.app-checkbox:checked').length;
    if (selected > 0) {
        bulkActions.style.display = 'flex';
        bulkCount.textContent = selected;
    } else {
        bulkActions.style.display = 'none';
        selectAll.checked = false;
    }
}

if(selectAll) {
    selectAll.addEventListener('change', function() {
        appCheckboxes.forEach(cb => {
            if(cb.closest('tr').style.display !== 'none') {
                cb.checked = this.checked;
            }
        });
        updateBulkUI();
    });
}

appCheckboxes.forEach(cb => {
    cb.addEventListener('change', updateBulkUI);
});

window.confirmBulkDelete = function() {
    if(confirm('Tem certeza que deseja remover os apps selecionados da loja?')) {
        const formData = new FormData(document.getElementById('bulkDeleteForm'));
        formData.append('bulk_delete', '1');
        
        fetch('apps.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if(data.success) location.reload();
            else alert('Erro ao excluir em massa.');
        })
        .catch(err => {
            console.error(err);
            alert('Erro de conexão.');
        });
    }
};

</script>

<style>
    /* ========== DESIGN SYSTEM ========== */
    :root {
        --bg-primary: #0a0e17;
        --bg-secondary: #111827;
        --bg-tertiary: #1a2235;
        --accent: #3b82f6;
        --accent-hover: #2563eb;
        --accent-glow: rgba(59, 130, 246, 0.15);
        --danger: #ef4444;
        --danger-hover: #dc2626;
        --success: #10b981;
        --text-primary: #f1f5f9;
        --text-secondary: rgba(255, 255, 255, 0.85);
        --text-muted: rgba(255, 255, 255, 0.65);
        --border: rgba(255, 255, 255, 0.08);
        --border-light: rgba(255, 255, 255, 0.05);
        --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.3);
        --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
        --shadow-lg: 0 10px 40px rgba(0, 0, 0, 0.5);
        --radius-sm: 10px;
        --radius-md: 14px;
        --radius-lg: 18px;
        --transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    }

    /* Sobrescrever text-muted do Bootstrap para fundos escuros */
    .text-muted {
        color: var(--text-muted) !important;
    }

    /* ========== PAGE HEADER ========== */
    .page-header {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(139, 92, 246, 0.05) 100%);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        padding: 1.75rem 2rem;
        margin-bottom: 2rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        flex-wrap: wrap;
        box-shadow: var(--shadow-md);
    }

    .page-header-content h2 {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 0.25rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .page-header-content h2 i {
        font-size: 1.35rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .page-header-content p {
        color: var(--text-muted);
        font-size: 0.875rem;
        margin: 0;
    }

    .btn-primary-custom {
        background: linear-gradient(135deg, var(--accent), #4f46e5);
        border: none;
        color: white;
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.9rem;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
        cursor: pointer;
        text-decoration: none;
    }

    .btn-primary-custom:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        color: white;
    }

    /* ========== ALERTS ========== */
    .alert-custom {
        border-radius: var(--radius-md);
        padding: 1rem 1.5rem;
        margin-bottom: 1.5rem;
        border: none;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        animation: slideDown 0.4s ease;
    }

    .alert-success-custom {
        background: rgba(16, 185, 129, 0.1);
        color: #34d399;
        border-left: 4px solid var(--success);
    }

    @keyframes slideDown {
        from { opacity: 0; transform: translateY(-15px); }
        to { opacity: 1; transform: translateY(0); }
    }

    /* ========== TABLE CONTAINER ========== */
    .table-container {
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        overflow: hidden;
        box-shadow: var(--shadow-lg);
    }

    .table-header {
        background: var(--bg-tertiary);
        padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .table-header-title {
        color: var(--text-secondary);
        font-size: 0.8rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

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

    .table-custom thead th {
        background: rgba(255, 255, 255, 0.02);
        color: var(--text-muted);
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        padding: 1rem 1.5rem;
        border-bottom: 2px solid var(--border-light);
        white-space: nowrap;
    }

    .table-custom tbody td {
        padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border-light);
        color: var(--text-secondary);
        vertical-align: middle;
        transition: var(--transition);
    }

    .table-custom tbody tr {
        transition: var(--transition);
    }

    .table-custom tbody tr:hover {
        background: rgba(59, 130, 246, 0.03);
    }

    .table-custom tbody tr:last-child td {
        border-bottom: none;
    }

    /* ========== ACTION BUTTONS ========== */
    .btn-action-custom {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border: 1px solid rgba(239, 68, 68, 0.3);
        background: transparent;
        color: var(--danger);
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .btn-action-custom:hover {
        background: rgba(239, 68, 68, 0.15);
        border-color: var(--danger);
        transform: scale(1.1);
    }
    
    .btn-action-edit {
        border: 1px solid rgba(59, 130, 246, 0.3);
        color: var(--accent);
        margin-right: 0.5rem;
    }
    
    .btn-action-edit:hover {
        background: rgba(59, 130, 246, 0.15);
        border-color: var(--accent);
    }

    /* ========== EMPTY STATE ========== */
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
    }

    .empty-state-icon {
        font-size: 4rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        opacity: 0.5;
        margin-bottom: 1rem;
    }

    .empty-state-text {
        color: var(--text-muted);
        font-size: 1rem;
        font-style: italic;
    }

    /* ========== MODAL ========== */
    .modal-content-custom {
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-lg);
    }

    .modal-header-custom {
        padding: 1.5rem;
        border-bottom: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .modal-title-custom {
        color: var(--text-primary);
        font-weight: 700;
        font-size: 1.15rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .modal-title-custom i {
        font-size: 1.1rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .modal-body-custom {
        padding: 1.5rem;
    }

    .modal-footer-custom {
        padding: 1rem 1.5rem 1.5rem;
        border-top: 1px solid var(--border);
        display: flex;
        gap: 0.75rem;
    }

    .btn-close-custom {
        background: none;
        border: none;
        color: var(--text-muted);
        font-size: 1.25rem;
        cursor: pointer;
        transition: var(--transition);
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .btn-close-custom:hover {
        background: rgba(255, 255, 255, 0.05);
        color: var(--text-primary);
    }

    /* ========== FORM ELEMENTS ========== */
    .form-label-custom {
        color: var(--text-muted);
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
        display: block;
    }

    .form-control-custom {
        background: var(--bg-primary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        padding: 0.75rem 1rem;
        color: var(--text-primary);
        width: 100%;
        transition: var(--transition);
        font-size: 0.9rem;
    }

    .form-control-custom:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 4px var(--accent-glow);
        background: var(--bg-primary);
    }

    .form-control-custom::placeholder {
        color: var(--text-muted);
        opacity: 0.6;
    }

    /* ========== UPLOAD ZONE ========== */
    .upload-zone {
        background: var(--bg-primary);
        border: 2px dashed rgba(59, 130, 246, 0.3);
        border-radius: var(--radius-md);
        padding: 2rem;
        text-align: center;
        cursor: pointer;
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .upload-zone:hover,
    .upload-zone.drag-over {
        border-color: var(--accent);
        background: rgba(59, 130, 246, 0.05);
    }

    .upload-zone-icon {
        font-size: 2.5rem;
        color: var(--accent);
        opacity: 0.7;
        margin-bottom: 0.5rem;
    }

    .upload-zone-text {
        color: var(--text-muted);
        font-size: 0.85rem;
    }

    .btn-submit-custom {
        background: linear-gradient(135deg, var(--accent), #4f46e5);
        border: none;
        color: white;
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
        transition: var(--transition);
        flex: 1;
        box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
    }

    .btn-submit-custom:hover {
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        transform: translateY(-1px);
    }

    .btn-submit-custom:disabled {
        opacity: 0.7;
        cursor: not-allowed;
        transform: none;
    }

    /* Tabs Custom */
    .nav-tabs-custom {
        border-bottom: 1px solid var(--border);
        margin-bottom: 1.5rem;
    }
    .nav-tabs-custom .nav-link {
        color: var(--text-muted);
        border: none;
        border-bottom: 2px solid transparent;
        font-weight: 600;
        padding: 0.75rem 1.25rem;
        transition: var(--transition);
        background: transparent;
    }
    .nav-tabs-custom .nav-link:hover {
        color: var(--text-primary);
        border-color: rgba(255,255,255,0.1);
    }
    .nav-tabs-custom .nav-link.active {
        color: var(--accent);
        border-bottom-color: var(--accent);
        background: transparent;
    }

    /* Progress Loader */
    .parsing-loader {
        display: none;
        text-align: center;
        padding: 2rem;
    }
    .parsing-loader .spinner-border {
        color: var(--accent);
        width: 3rem;
        height: 3rem;
        margin-bottom: 1rem;
    }

    /* Preview Card */
    .app-preview-card {
        background: rgba(59,130,246,0.05);
        border: 1px solid var(--accent-glow);
        border-radius: var(--radius-sm);
        padding: 1rem;
        display: none;
        gap: 1rem;
        margin-top: 1rem;
    }
    .app-preview-icon {
        width: 64px;
        height: 64px;
        border-radius: 12px;
        object-fit: cover;
        background: var(--bg-primary);
    }
    .app-preview-info h5 { margin: 0; color: var(--text-primary); font-size: 1rem; font-weight: 600;}
    .app-preview-info p { margin: 0; color: var(--text-muted); font-size: 0.8rem; }
    
    /* ========== RESPONSIVIDADE E AJUSTES PARA MOBILE ========== */
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            align-items: stretch;
            padding: 1.25rem;
            gap: 1rem;
        }
        .btn-primary-custom {
            width: 100%;
            justify-content: center;
        }
        .table-responsive {
            overflow-x: visible !important;
            padding: 0 !important;
            margin: 0 !important;
            border: none !important;
            width: 100% !important;
        }
        .table-header {
            flex-direction: column;
            align-items: stretch;
            gap: 1rem;
            padding: 1rem;
        }
        .table-header .position-relative {
            width: 100%;
        }
        #searchApps {
            width: 100% !important;
        }
        #appsTable,
        #appsTable tbody {
            display: block;
            width: 100% !important;
        }
        #appsTable thead {
            display: none;
        }
        #appsTable tbody tr {
            display: block;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: var(--radius-md);
            margin-bottom: 0.75rem;
            padding: 0.85rem 1rem;
            width: 100% !important;
            box-sizing: border-box;
        }
        #appsTable tbody tr:hover {
            background: rgba(59, 130, 246, 0.05);
        }
        #appsTable tbody td {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid var(--border-light);
            font-size: 0.82rem;
            width: 100% !important;
            box-sizing: border-box;
        }
        #appsTable tbody td:last-child {
            border-bottom: none;
            padding-top: 0.6rem;
            justify-content: flex-end;
            gap: 0.4rem;
        }
        #appsTable tbody td::before {
            content: attr(data-label);
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: var(--text-muted);
            flex-shrink: 0;
            margin-right: 0.75rem;
        }
        #appsTable tbody td.checkbox-cell {
            justify-content: flex-start;
            gap: 0.5rem;
        }
        #appsTable tbody td.checkbox-cell::before {
            content: 'Selecionar';
        }
        .app-package {
            font-size: 0.75rem;
            word-break: break-all;
            text-align: right;
            justify-content: flex-end;
        }
        .app-name {
            font-size: 0.8rem;
            text-align: right;
            justify-content: flex-end;
        }
        #bulkActions {
            flex-direction: column;
            align-items: stretch;
            gap: 0.75rem;
            padding: 1rem;
        }
        #bulkActions button {
            width: 100%;
            justify-content: center;
        }
    }
</style>

<div class="container-fluid">

    <!-- Header da Página -->
    <div class="page-header">
        <div class="page-header-content">
            <h2>
                <i class="bi bi-shop-window"></i>
                Loja de Apps
            </h2>
            <p>Gerencie os aplicativos disponíveis para instalação na TV</p>
        </div>
        <button type="button" class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addAppModal">
            <i class="bi bi-plus-lg"></i>
            Adicionar App
        </button>
    </div>



    <!-- Tabela de Apps -->
    <div class="table-container">
        <div class="table-header">
            <span class="table-header-title">
                <i class="bi bi-list-ul me-2"></i>Aplicativos na Loja
            </span>
            <div class="position-relative">
                <i class="bi bi-search position-absolute start-0 top-50 translate-middle-y ms-3 text-white-50"></i>
                <input type="text" id="searchApps" class="form-control-custom ps-5 py-1" placeholder="Buscar..." style="width: 200px; font-size: 0.8rem;">
            </div>
        </div>
        
        <!-- Ações em Massa -->
        <div id="bulkActions" style="display: none; background: var(--bg-tertiary); padding: 0.75rem 1.5rem; border-bottom: 1px solid var(--border); align-items: center; justify-content: space-between;">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-check-square text-warning"></i>
                <span style="color: var(--warning); font-weight: 600; font-size: 0.85rem;">
                    <span id="bulkCount">0</span> selecionado(s)
                </span>
            </div>
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="confirmBulkDelete()" style="border-radius: 50px;">
                <i class="bi bi-trash"></i> Remover Selecionados
            </button>
        </div>

        <form id="bulkDeleteForm">
        <div class="table-responsive">
            <table class="table-custom" id="appsTable">
                <thead>
                    <tr>
                        <th style="width: 40px;" class="text-center">
                            <input type="checkbox" class="form-check-input" id="selectAll">
                        </th>
                        <th style="width: 80px;" class="text-center">Ícone</th>
                        <th>Nome do App</th>
                        <th>Pacote (ID)</th>
                        <th>Versão</th>
                        <th class="text-end">Ações</th>
                    </tr>
                </thead>
                <tbody id="appsTableBody">
                    <?php if ($apps->num_rows == 0): ?>
                        <tr id="noAppsRow">
                            <td colspan="6">
                                <div class="empty-state">
                                    <div class="empty-state-icon">
                                        <i class="bi bi-inbox"></i>
                                    </div>
                                    <p class="empty-state-text">
                                        Nenhum aplicativo cadastrado na loja.<br>
                                        Clique em "Adicionar App" para começar.
                                    </p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php while($app = $apps->fetch_assoc()): ?>
                            <tr class="app-row" data-app-id="<?php echo $app['id']; ?>">
                                <td class="text-center checkbox-cell">
                                    <input type="checkbox" name="selected_apps[]" value="<?php echo $app['id']; ?>" class="form-check-input app-checkbox">
                                </td>
                                <td data-label="Ícone" class="text-center">
                                    <img src="<?php echo htmlspecialchars($app['icon_url']); ?>" style="width: 48px; height: 48px; border-radius: 8px; object-fit: cover;" onerror="this.src='assets/img/default-icon.png'">
                                </td>
                                <td data-label="Nome do App">
                                    <strong class="text-white app-name"><?php echo htmlspecialchars($app['name']); ?></strong>
                                </td>
                                <td data-label="Pacote (ID)">
                                    <span class="text-muted app-package" style="font-family: monospace; font-size: 0.85rem;">
                                        <?php echo htmlspecialchars($app['package_name']); ?>
                                    </span>
                                </td>
                                <td data-label="Versão">
                                    <span class="badge" style="background: rgba(255,255,255,0.1); color: var(--text-secondary);">
                                        v<?php echo htmlspecialchars($app['version']); ?>
                                    </span>
                                </td>
                                <td class="text-end">
                                    <button type="button" class="btn-action-custom" onclick="globalAjaxDelete('apps.php?delete=<?php echo $app['id']; ?>', 'tr[data-app-id=\'<?php echo $app['id']; ?>\']', 'Remover Aplicativo?', 'Deseja remover &quot;<?php echo htmlspecialchars($app['name']); ?>&quot; da loja?')" title="Excluir app">
                                        <i class="bi bi-trash3"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        </form>
    </div>
</div>

<!-- Modal Adicionar App -->
<div class="modal fade" id="addAppModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-content-custom">
            <div class="modal-header-custom">
                <h5 class="modal-title-custom">
                    <i class="bi bi-cloud-arrow-up"></i>
                    Adicionar Aplicativo
                </h5>
                <button type="button" class="btn-close-custom" data-bs-dismiss="modal">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            
            <div class="modal-body-custom">
                <!-- Abas -->
                <ul class="nav nav-tabs nav-tabs-custom" id="addAppTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="auto-tab" data-bs-toggle="tab" data-bs-target="#auto" type="button" role="tab">Automático</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="package-tab" data-bs-toggle="tab" data-bs-target="#package" type="button" role="tab">Por Pacote</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="manual-tab" data-bs-toggle="tab" data-bs-target="#manual" type="button" role="tab">Manual</button>
                    </li>
                </ul>

                <!-- Conteúdo das Abas -->
                <div class="tab-content" id="addAppTabsContent">
                    
                    <!-- Aba: Automático -->
                    <div class="tab-pane fade show active" id="auto" role="tabpanel">
                        <form id="formAuto" enctype="multipart/form-data">
                            <input type="hidden" name="add_method" value="auto">
                            <input type="hidden" name="version" id="auto_version">
                            <input type="hidden" name="icon_base64" id="auto_icon_base64">
                            
                            <p class="text-muted small mb-3">Selecione o arquivo APK. O sistema irá extrair os dados (você poderá editá-los antes de enviar).</p>
                            
                            <div class="upload-zone" id="autoApkDropzone">
                                <i class="bi bi-android2 upload-zone-icon"></i>
                                <div class="upload-zone-text">Clique ou arraste o arquivo APK aqui</div>
                                <input type="file" name="apk" id="autoApkInput" accept=".apk" class="d-none" required>
                            </div>

                            <div class="parsing-loader" id="autoLoader">
                                <div class="spinner-border" role="status"></div>
                                <h6 class="text-white">Analisando APK...</h6>
                                <p class="small text-muted">Extraindo informações e ícone.</p>
                            </div>

                            <div class="app-preview-card flex-column align-items-stretch" id="autoPreview" style="display: none; padding: 1.25rem;">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6 class="text-primary m-0"><i class="bi bi-pencil-square me-2"></i>Revise os Dados</h6>
                                    <button type="button" class="btn btn-sm btn-outline-danger" id="autoResetBtn" title="Cancelar"><i class="bi bi-x"></i></button>
                                </div>
                                <div class="d-flex gap-3">
                                    <div class="text-center position-relative" style="width: 80px; flex-shrink: 0;">
                                        <img src="" id="autoPreviewIcon" style="width: 80px; height: 80px; border-radius: 12px; object-fit: cover; background: var(--bg-primary); border: 1px solid var(--border);">
                                        <button type="button" class="btn btn-sm btn-primary position-absolute bottom-0 start-50 translate-middle-x mb-n2 shadow" style="font-size: 0.6rem; padding: 0.2rem 0.5rem; border-radius: 10px;" onclick="document.getElementById('autoCustomIcon').click()">MUDAR</button>
                                        <input type="file" id="autoCustomIcon" accept="image/*" class="d-none">
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="mb-2">
                                            <label class="form-label-custom" style="font-size: 0.7rem; margin-bottom: 0.25rem;">Nome do Aplicativo</label>
                                            <input type="text" name="name" id="auto_name" class="form-control-custom py-1" style="font-size: 0.85rem;" required>
                                        </div>
                                        <div>
                                            <label class="form-label-custom" style="font-size: 0.7rem; margin-bottom: 0.25rem;">Package Name</label>
                                            <input type="text" name="package" id="auto_package" class="form-control-custom py-1" style="font-size: 0.85rem;" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="mt-3 text-end">
                                    <span class="badge bg-primary bg-opacity-10 text-primary border" id="autoPreviewVersion">v2.0</span>
                                </div>
                            </div>

                            <div class="alert alert-danger mt-3 d-none" id="autoError"></div>

                            <div class="mt-4 text-end">
                                <button type="submit" class="btn-submit-custom w-100" id="autoSubmitBtn" disabled>
                                    <i class="bi bi-cloud-arrow-up me-2"></i> Confirmar Upload
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Aba: Por Pacote -->
                    <div class="tab-pane fade" id="package" role="tabpanel">
                        <form id="formPackage" enctype="multipart/form-data">
                            <input type="hidden" name="add_method" value="package">
                            <p class="text-muted small mb-3">Use este método para apps de sistema ou instalação manual, não requer envio de APK.</p>
                            
                            <div class="mb-3">
                                <label class="form-label-custom">Nome do Aplicativo</label>
                                <input type="text" name="name" class="form-control-custom" required placeholder="Ex: Configurações">
                            </div>
                            <div class="mb-3">
                                <label class="form-label-custom">Package Name</label>
                                <input type="text" name="package" class="form-control-custom" required placeholder="Ex: com.android.settings">
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label-custom">Ícone do App (PNG/JPG/WEBP)</label>
                                <input type="file" name="icon" class="form-control-custom" accept="image/*" required>
                            </div>
                            
                            <div class="mt-4 text-end">
                                <button type="submit" class="btn-submit-custom w-100" id="packageSubmitBtn">
                                    <i class="bi bi-check-lg me-2"></i> Salvar Aplicativo
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Aba: Manual -->
                    <div class="tab-pane fade" id="manual" role="tabpanel">
                        <form id="formManual" enctype="multipart/form-data">
                            <input type="hidden" name="add_method" value="manual">
                            
                            <div class="mb-3">
                                <label class="form-label-custom">Nome do Aplicativo</label>
                                <input type="text" name="name" class="form-control-custom" required placeholder="Ex: Netflix">
                            </div>
                            <div class="mb-3">
                                <label class="form-label-custom">Package Name</label>
                                <input type="text" name="package" class="form-control-custom" required placeholder="Ex: com.netflix.mediaclient">
                            </div>
                            <div class="row">
                                <div class="col-6 mb-3">
                                    <label class="form-label-custom">Versão</label>
                                    <input type="text" name="version" class="form-control-custom" value="2.1.2">
                                </div>
                                <div class="col-6 mb-3">
                                    <label class="form-label-custom">Ícone</label>
                                    <input type="file" name="icon" class="form-control-custom" accept="image/*" required>
                                </div>
                            </div>
                            <div class="mb-4">
                                <label class="form-label-custom">Arquivo APK</label>
                                <input type="file" name="apk" class="form-control-custom" accept=".apk" required>
                            </div>
                            
                            <div class="mt-4 text-end">
                                <button type="submit" class="btn-submit-custom w-100" id="manualSubmitBtn">
                                    <i class="bi bi-cloud-arrow-up me-2"></i> Fazer Upload
                                </button>
                            </div>
                        </form>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal de Upload Progressivo Universal -->
<div class="modal fade" id="uploadProgressModal" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-content-custom">
            <div class="modal-body p-5 text-center">
                <div class="spinner-border mb-4" role="status" style="width: 3rem; height: 3rem; color: var(--accent);"></div>
                <h4 class="text-white mb-2">Processando...</h4>
                <p class="text-white-50 small mb-4">Aguarde enquanto os dados são enviados.</p>
                <div class="progress rounded-pill mb-3" style="height: 12px; background: rgba(255,255,255,0.05);">
                    <div id="univProgressBar" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%; background: linear-gradient(135deg, var(--accent), #8b5cf6);"></div>
                </div>
                <div class="d-flex justify-content-between small text-white-50">
                    <span id="univUploadStatus">Iniciando...</span>
                    <span id="univPercentLabel">0%</span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// ==========================================
// 1. LÓGICA DO MÉTODO AUTOMÁTICO (APK PARSER)
// ==========================================
const autoApkInput = document.getElementById('autoApkInput');
const autoApkDropzone = document.getElementById('autoApkDropzone');
const autoLoader = document.getElementById('autoLoader');
const autoPreview = document.getElementById('autoPreview');
const autoError = document.getElementById('autoError');
const autoSubmitBtn = document.getElementById('autoSubmitBtn');

if(autoApkDropzone && autoApkInput) {
    autoApkDropzone.addEventListener('click', () => autoApkInput.click());
    autoApkDropzone.addEventListener('dragover', (e) => { e.preventDefault(); autoApkDropzone.classList.add('drag-over'); });
    autoApkDropzone.addEventListener('dragleave', () => { autoApkDropzone.classList.remove('drag-over'); });
    autoApkDropzone.addEventListener('drop', (e) => {
        e.preventDefault();
        autoApkDropzone.classList.remove('drag-over');
        if (e.dataTransfer.files.length && e.dataTransfer.files[0].name.endsWith('.apk')) {
            autoApkInput.files = e.dataTransfer.files;
            processApk(e.dataTransfer.files[0]);
        }
    });
    autoApkInput.addEventListener('change', () => {
        if (autoApkInput.files.length) processApk(autoApkInput.files[0]);
    });
}

function processApk(file) {
    // UI states
    autoApkDropzone.style.display = 'none';
    autoLoader.style.display = 'block';
    autoPreview.style.display = 'none';
    autoError.classList.add('d-none');
    autoSubmitBtn.disabled = true;

    // Usando AppInfoParser
    const parser = new AppInfoParser(file);
    parser.parse().then(result => {
        autoLoader.style.display = 'none';
        
        // Populando campos editáveis
        const nameEl = document.getElementById('auto_name');
        const packageEl = document.getElementById('auto_package');
        const versionEl = document.getElementById('auto_version');
        const iconBase64El = document.getElementById('auto_icon_base64');
        const previewIconEl = document.getElementById('autoPreviewIcon');

        const appName = result.application?.label?.[0] || file.name.replace('.apk','');
        if(nameEl) nameEl.value = appName;
        if(packageEl) packageEl.value = result.package || '';
        if(versionEl) versionEl.value = result.versionName || '1.0';
        if(iconBase64El) iconBase64El.value = result.icon || '';
        if(previewIconEl) previewIconEl.src = result.icon || 'assets/img/default-icon.png';

        autoPreview.style.display = 'flex';
        autoPreview.style.flexDirection = 'column';
        autoSubmitBtn.disabled = false;
        
    }).catch(err => {
        console.error(err);
        autoLoader.style.display = 'none';
        autoApkDropzone.style.display = 'block';
        autoError.textContent = "Erro ao analisar APK: " + (err.message || 'Arquivo inválido.');
        autoError.classList.remove('d-none');
        autoApkInput.value = '';
    });
}

const autoResetBtn = document.getElementById('autoResetBtn');
if(autoResetBtn) {
    autoResetBtn.addEventListener('click', () => {
        autoPreview.style.display = 'none';
        autoApkDropzone.style.display = 'block';
        autoApkInput.value = '';
        autoSubmitBtn.disabled = true;
    });
}


// ==========================================
// 2. SUBMISSÃO DOS FORMULÁRIOS COM PROGRESSO
// ==========================================
function submitAppForm(formId) {
    const form = document.getElementById(formId);
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(form);
        formData.append('add_app', '1');

        // Mostra modal de progresso (esconde o atual se aberto)
        const mainModal = bootstrap.Modal.getInstance(document.getElementById('addAppModal'));
        if(mainModal) mainModal.hide();
        
        const progModal = new bootstrap.Modal(document.getElementById('uploadProgressModal'));
        progModal.show();

        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'apps.php', true);
        
        xhr.upload.onprogress = function(e) {
            if (e.lengthComputable) {
                const percent = Math.round((e.loaded / e.total) * 100);
                document.getElementById('univProgressBar').style.width = percent + '%';
                document.getElementById('univPercentLabel').innerHTML = percent + '%';
                document.getElementById('univUploadStatus').innerHTML = percent === 100 ? "Salvando..." : "Enviando arquivos...";
            }
        };
        
        xhr.onload = function() {
            if (xhr.status === 200) {
                location.reload();
            } else {
                progModal.hide();
                alert('Erro: ' + xhr.responseText);
                if(mainModal) mainModal.show();
            }
        };
        xhr.onerror = () => { alert('Erro de conexão.'); progModal.hide(); };
        xhr.send(formData);
    });
}

submitAppForm('formAuto');
submitAppForm('formPackage');
submitAppForm('formManual');

// ==========================================
// 3. BUSCA NA TABELA
// ==========================================
document.getElementById('searchApps').addEventListener('input', function() {
    const term = this.value.toLowerCase().trim();
    let hasVisible = false;
    document.querySelectorAll('.app-row').forEach(row => {
        const name = row.querySelector('.app-name')?.innerText.toLowerCase() || '';
        const pack = row.querySelector('.app-package')?.innerText.toLowerCase() || '';
        const matches = name.includes(term) || pack.includes(term);
        row.style.display = matches ? '' : 'none';
        if (matches) hasVisible = true;
    });
    
    let noResult = document.getElementById('noSearchAppRow');
    if (!hasVisible && document.querySelectorAll('.app-row').length > 0) {
        if (!noResult) {
            document.getElementById('appsTableBody').insertAdjacentHTML('beforeend', 
                `<tr id="noSearchAppRow"><td colspan="5" class="text-center py-4 text-muted"><i class="bi bi-search-slash fs-4 d-block mb-2"></i>Nenhum app encontrado.</td></tr>`
            );
        }
    } else if (noResult) {
        noResult.remove();
    }
});

// ==========================================
// CUSTOM ICON NO AUTOMÁTICO
// ==========================================
const autoCustomIconInput = document.getElementById('autoCustomIcon');
if (autoCustomIconInput) {
    autoCustomIconInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if(file) {
            const reader = new FileReader();
            reader.onload = function(evt) {
                const iconEl = document.getElementById('autoPreviewIcon');
                const base64El = document.getElementById('auto_icon_base64');
                if(iconEl) iconEl.src = evt.target.result;
                if(base64El) base64El.value = evt.target.result;
            };
            reader.readAsDataURL(file);
        }
    });
}

// ==========================================
// BULK DELETE LÓGICA
// ==========================================
const selectAll = document.getElementById('selectAll');
const appCheckboxes = document.querySelectorAll('.app-checkbox');
const bulkActions = document.getElementById('bulkActions');
const bulkCount = document.getElementById('bulkCount');

function updateBulkUI() {
    const selected = document.querySelectorAll('.app-checkbox:checked').length;
    if (selected > 0) {
        bulkActions.style.display = 'flex';
        bulkCount.textContent = selected;
    } else {
        bulkActions.style.display = 'none';
        selectAll.checked = false;
    }
}

if(selectAll) {
    selectAll.addEventListener('change', function() {
        appCheckboxes.forEach(cb => {
            if(cb.closest('tr').style.display !== 'none') {
                cb.checked = this.checked;
            }
        });
        updateBulkUI();
    });
}

appCheckboxes.forEach(cb => {
    cb.addEventListener('change', updateBulkUI);
});

window.confirmBulkDelete = function() {
    if(confirm('Tem certeza que deseja remover os apps selecionados da loja?')) {
        const formData = new FormData(document.getElementById('bulkDeleteForm'));
        formData.append('bulk_delete', '1');
        
        fetch('apps.php', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if(data.success) location.reload();
            else alert('Erro ao excluir em massa.');
        })
        .catch(err => {
            console.error(err);
            alert('Erro de conexão.');
        });
    }
};

</script>

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