<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

require 'libs/php-apk-parser/vendor/autoload.php';

$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

// Configurações de upload
$uploadDir = __DIR__ . '/uploads/';
$iconDir = $uploadDir . 'icons/';
$apkDir = $uploadDir . 'apks/';

// Get the base path including any subdirectories where the script is located
$basePath = dirname($_SERVER['SCRIPT_NAME']);
// Construct the full base URL including the potential subfolder
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $basePath;

// Criar diretórios se não existirem
if (!file_exists($iconDir)) mkdir($iconDir, 0777, true);
if (!file_exists($apkDir)) mkdir($apkDir, 0777, true);

$dbPath = __DIR__ . '/api/max.db';
$db = new PDO('sqlite:' . $dbPath);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Função para extrair o nome do pacote do APK
function getApkPackageName($filePath) {
    try {
        $apk = new \ApkParser\Parser($filePath);
        $manifest = $apk->getManifest();
        return $manifest->getPackageName();
    } catch (Exception $e) {
        error_log("Erro ao extrair pacote do APK: " . $e->getMessage());
        return null;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');

    try {
        $action = $_POST['action'] ?? null;
        $id = isset($_POST['id']) ? (int)$_POST['id'] : null;
        $name = isset($_POST['name']) ? trim($_POST['name']) : null;
        $active = isset($_POST['active']) ? (int)$_POST['active'] : 0;

        // Processar uploads
        $apkUrl = null;
        $iconUrl = null;
        $package = null;

        if ($action === 'add' || $action === 'edit') {
            // Processar upload do APK
            if (isset($_FILES['apk_file']) && $_FILES['apk_file']['error'] === UPLOAD_ERR_OK) {
                $apkExt = pathinfo($_FILES['apk_file']['name'], PATHINFO_EXTENSION);
                $apkFilename = uniqid('apk_') . '.' . $apkExt;
                $apkPath = $apkDir . $apkFilename;

                if (move_uploaded_file($_FILES['apk_file']['tmp_name'], $apkPath)) {
                    $apkUrl = $baseUrl . '/uploads/apks/' . $apkFilename;
                    
                    // Extrair o nome do pacote do APK
                    $package = getApkPackageName($apkPath);
                    if (!$package) {
                        throw new Exception('Não foi possível extrair o nome do pacote do APK');
                    }
                } else {
                    throw new Exception('Falha no upload do arquivo APK');
                }
            } elseif ($action === 'edit') {
                // Manter o APK existente se não for enviado um novo
                $stmt = $db->prepare("SELECT apk_url, package FROM apps WHERE id = ?");
                $stmt->execute([$id]);
                $appData = $stmt->fetch(PDO::FETCH_ASSOC);
                $existingUrl = $appData['apk_url'];
                $package = $appData['package'];

                if ($existingUrl && !preg_match('/^http(s)?:\/\//', $existingUrl) && strpos($existingUrl, $basePath . '/uploads') === false) {
                    $apkUrl = $baseUrl . '/' . ltrim($existingUrl, '/');
                } else {
                    $apkUrl = $existingUrl;
                }
            }

            // Processar upload do ícone
            if (isset($_FILES['icon_file']) && $_FILES['icon_file']['error'] === UPLOAD_ERR_OK) {
                $iconExt = pathinfo($_FILES['icon_file']['name'], PATHINFO_EXTENSION);
                $iconFilename = uniqid('icon_') . '.' . $iconExt;
                $iconPath = $iconDir . $iconFilename;

                if (move_uploaded_file($_FILES['icon_file']['tmp_name'], $iconPath)) {
                    $iconUrl = $baseUrl . '/uploads/icons/' . $iconFilename;
                } else {
                    throw new Exception('Falha no upload do arquivo de ícone');
                }
            } elseif ($action === 'edit') {
                // Manter o ícone existente se não for enviado um novo
                $stmt = $db->prepare("SELECT icon_url FROM apps WHERE id = ?");
                $stmt->execute([$id]);
                $existingUrl = $stmt->fetchColumn();

                if ($existingUrl && !preg_match('/^http(s)?:\/\//', $existingUrl) && strpos($existingUrl, $basePath . '/uploads') === false) {
                    $iconUrl = $baseUrl . '/' . ltrim($existingUrl, '/');
                } else {
                    $iconUrl = $existingUrl;
                }
            }

            if ($action === 'add') {
                if (!$apkUrl || !$iconUrl || !$package) {
                    throw new Exception('Arquivos APK e Ícone são obrigatórios para novos apps');
                }

                $stmt = $db->prepare("INSERT INTO apps (name, package, apk_url, icon_url, active) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name, $package, $apkUrl, $iconUrl, $active]);
                echo json_encode(['status' => 'success', 'message' => '✅ App adicionado com sucesso!']);
                exit;
            } elseif ($action === 'edit') {
                $stmt = $db->prepare("UPDATE apps SET name = ?, package = COALESCE(?, package), apk_url = COALESCE(?, apk_url), icon_url = COALESCE(?, icon_url), active = ? WHERE id = ?");
                $stmt->execute([$name, $package, $apkUrl, $iconUrl, $active, $id]);
                echo json_encode(['status' => 'success', 'message' => '🔄 App atualizado com sucesso!']);
                exit;
            }
        } elseif ($action === 'delete') {
            // Obter URLs antes de deletar para remover os arquivos
            $stmt = $db->prepare("SELECT apk_url, icon_url FROM apps WHERE id = ?");
            $stmt->execute([$id]);
            $app = $stmt->fetch(PDO::FETCH_ASSOC);

            // Deletar do banco de dados
            $stmt = $db->prepare("DELETE FROM apps WHERE id = ?");
            $stmt->execute([$id]);

            // Deletar arquivos (usando caminho relativo)
            if ($app['apk_url']) {
                $relativePath = str_replace($baseUrl, '', $app['apk_url']);
                $filePath = __DIR__ . '/' . ltrim($relativePath, '/');
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }
            if ($app['icon_url']) {
                $relativePath = str_replace($baseUrl, '', $app['icon_url']);
                $filePath = __DIR__ . '/' . ltrim($relativePath, '/');
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }

            echo json_encode(['status' => 'success', 'message' => '🗑️ App deletado com sucesso!']);
            exit;
        } elseif ($action === 'toggle') {
            // Obter o status atual
            $stmt = $db->prepare("SELECT active FROM apps WHERE id = ?");
            $stmt->execute([$id]);
            $currentStatus = (int)$stmt->fetchColumn();

            // Inverter o status
            $newStatus = $currentStatus ? 0 : 1;

            // Atualizar com o novo status
            $stmt = $db->prepare("UPDATE apps SET active = ? WHERE id = ?");
            $stmt->execute([$newStatus, $id]);

            if ($stmt->rowCount() > 0) {
                echo json_encode([
                    'status' => 'success',
                    'message' => '🔄 Status do app alterado com sucesso!',
                    'newStatus' => $newStatus
                ]);
            } else {
                throw new Exception('Nenhum registro foi atualizado');
            }
            exit;
        }

        echo json_encode(['status' => 'error', 'message' => 'Ação desconhecida']);
        exit;

    } catch (Exception $e) {
        http_response_code(500);
        error_log("Erro no processamento: " . $e->getMessage());
        echo json_encode(['status' => 'error', 'message' => '❌ Erro: ' . $e->getMessage()]);
        exit;
    }
}

$apps = $db->query("SELECT * FROM apps ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

$page_title = "📱 Gerenciamento de Apps";

$page_content = '
<div class="card">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="search_apps" class="form-control form-control-solid w-250px ps-12" placeholder="🔍 Pesquisar Apps" />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-primary" onclick="openAddModal()">➕ Adicionar App</button>
            </div>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="apps_table">
            <thead>
                <tr class="text-start text-gray-500 fw-bold fs-7 text-uppercase gs-0">
                    <th class="min-w-50px">🖼️ Ícone</th>
                    <th class="min-w-150px">📛 Nome</th>
                    <th class="min-w-150px">📦 Pacote</th>
                    <th class="min-w-100px">🔘 Status</th>
                    <th class="min-w-100px">🛠️ Ações</th>
                </tr>
            </thead>
            <tbody id="apps_table_body" class="fw-semibold text-gray-600">
';

foreach ($apps as $app) {
    $statusClass = $app['active'] ? 'badge-light-success' : 'badge-light-danger';
    $statusText = $app['active'] ? '✅ Ativo' : '⛔ Inativo';

    // Garantir que a URL do ícone tenha o domínio completo
    $iconUrl = $app['icon_url'];
    if ($iconUrl && !preg_match('/^http(s)?:\/\//', $iconUrl)) {
        $iconUrl = $baseUrl . '/' . ltrim($iconUrl, '/');
    }

    $page_content .= "<tr data-id='{$app['id']}'>
        <td><img src='{$iconUrl}' alt='{$app['name']}' style='width: 40px; height: 40px; object-fit: contain;' onerror=\"this.src='{$static_url}media/icons/duotune/general/gen006.svg'\"></td>
        <td>{$app['name']}</td>
        <td>
            <div class='d-flex align-items-center'>
                <span class='me-2'>{$app['package']}</span>
                <button class='btn btn-sm btn-icon btn-light-primary' onclick=\"copyToClipboard('{$app['package']}')\">
                    <i class='ki-outline ki-copy fs-2'></i>
                </button>
            </div>
        </td>
        <td>
            <div class='d-flex align-items-center'>
                <div class='form-check form-switch form-check-custom form-check-solid me-3'>
                    <input class='form-check-input status-toggle' type='checkbox' data-id='{$app['id']}' " . ($app['active'] ? 'checked' : '') . "/>
                </div>
                <span class='badge {$statusClass}'>{$statusText}</span>
            </div>
        </td>
        <td>
            <button class='btn btn-sm btn-light-primary' onclick=\"editApp({$app['id']}, '{$app['name']}', {$app['active']})\">✏️ Editar</button>
            <button class='btn btn-sm btn-light-danger' onclick=\"deleteApp({$app['id']}, '{$app['name']}')\">🗑️ Excluir</button>
        </td>
    </tr>";
}

$page_content .= '
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="app_modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-650px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title" class="fw-bold">➕ Adicionar App</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="app_form" enctype="multipart/form-data">
                    <input type="hidden" id="app_id">
                    <div class="mb-7">
                        <label for="app_name" class="fs-6 fw-semibold mb-2">📛 Nome do App</label>
                        <input type="text" class="form-control" id="app_name" placeholder="Digite o nome do app" required>
                    </div>
                    <div class="mb-7">
                        <label class="fs-6 fw-semibold mb-2">📦 Nome do Pacote</label>
                        <div class="alert alert-info">
                            <i class="ki-outline ki-information fs-3 me-2"></i>
                            O nome do pacote será extraído automaticamente do arquivo APK
                        </div>
                    </div>
                    <div class="mb-7">
                        <label for="apk_file" class="fs-6 fw-semibold mb-2">📲 Arquivo APK</label>
                        <input type="file" class="form-control" id="apk_file" accept=".apk" required>
                        <div class="form-text">Tamanho máximo: 120MB</div>
                        <div id="current_apk" class="mt-2"></div>
                    </div>
                    <div class="mb-7">
                        <label for="icon_file" class="fs-6 fw-semibold mb-2">🖼️ Ícone do App</label>
                        <input type="file" class="form-control" id="icon_file" accept="image/*" required>
                        <div class="form-text">Tamanho recomendado: 512x512 pixels</div>
                        <div id="current_icon" class="mt-2"></div>
                    </div>
                    <div class="mb-7">
                        <div class="form-check form-switch form-check-custom form-check-solid">
                            <input class="form-check-input" type="checkbox" id="app_active" value="1" checked>
                            <label class="form-check-label" for="app_active">🔘 Ativar App</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">❌ Cancelar</button>
                <button type="button" class="btn btn-primary" onclick="saveApp()">💾 Salvar</button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let appsTable = $('#apps_table').DataTable({
        searching: true,
        paging: true,
        ordering: true,
        info: true,
        responsive: false,
        language: {
            url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/pt-BR.json'
        }
    });

    document.getElementById("search_apps").addEventListener("input", function() {
        appsTable.search(this.value).draw();
    });

    // Delegação de eventos para os toggles de status
    document.getElementById('apps_table').addEventListener('change', function(e) {
        if (e.target.classList.contains('status-toggle')) {
            const id = e.target.getAttribute('data-id');
            const isChecked = e.target.checked;
            toggleStatus(id, isChecked, e.target);
        }
    });

    window.copyToClipboard = function(text) {
        navigator.clipboard.writeText(text).then(() => {
            Swal.fire({
                icon: 'success',
                title: '📋 Copiado!',
                text: 'Nome do pacote copiado para a área de transferência',
                timer: 1000,
                showConfirmButton: false
            });
        });
    };

    window.openAddModal = function() {
        document.getElementById('modal_title').textContent = '➕ Adicionar App';
        document.getElementById('app_id').value = '';
        document.getElementById('app_name').value = '';
        document.getElementById('apk_file').required = true;
        document.getElementById('icon_file').required = true;
        document.getElementById('apk_file').value = '';
        document.getElementById('icon_file').value = '';
        document.getElementById('app_active').checked = true;
        document.getElementById('current_apk').innerHTML = '';
        document.getElementById('current_icon').innerHTML = '';
        $('#app_modal').modal('show');
    };

    window.editApp = function(id, name, active) {
        document.getElementById('modal_title').textContent = '✏️ Editar App';
        document.getElementById('app_id').value = id;
        document.getElementById('app_name').value = name;
        document.getElementById('app_active').checked = Boolean(active);
        document.getElementById('apk_file').required = false;
        document.getElementById('icon_file').required = false;
        document.getElementById('apk_file').value = '';
        document.getElementById('icon_file').value = '';

        // Mostrar arquivos atuais
        fetch('get_app_details.php?id=' + id)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Erro ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                if (!data) throw new Error('Resposta vazia do servidor');

                if (data.apk_url) {
                    const apkName = data.apk_url.split('/').pop();
                    document.getElementById('current_apk').innerHTML =
                        `<div class="alert alert-info p-2">
                            <i class="ki-outline ki-file fs-3 me-2"></i>
                            APK atual: ${apkName}
                        </div>`;
                }

                if (data.icon_url) {
                    document.getElementById('current_icon').innerHTML =
                        `<div class="alert alert-info p-2">
                            <img src="${data.icon_url}" alt="Ícone atual" style="width: 30px; height: 30px; object-fit: contain;" class="me-2">
                            Ícone atual
                        </div>`;
                }
            })
            .catch(error => {
                console.error('Erro ao carregar detalhes:', error);
                document.getElementById('current_apk').innerHTML =
                    `<div class="alert alert-danger p-2">
                        ❌ Falha ao carregar detalhes do APK
                    </div>`;
                document.getElementById('current_icon').innerHTML =
                    `<div class="alert alert-danger p-2">
                        ❌ Falha ao carregar detalhes do ícone
                    </div>`;
            });

        $('#app_modal').modal('show');
    };

    window.saveApp = function() {
        const id = document.getElementById('app_id').value;
        const name = document.getElementById('app_name').value.trim();
        const active = document.getElementById('app_active').checked ? 1 : 0;
        const apkFile = document.getElementById('apk_file').files[0];
        const iconFile = document.getElementById('icon_file').files[0];

        // Validar campos obrigatórios
        if (!name) {
            Swal.fire({
                icon: 'error',
                title: '❌ Erro',
                text: 'Nome do app é obrigatório!',
            });
            return;
        }

        // Para adição, ambos os arquivos são obrigatórios
        if (!id && (!apkFile || !iconFile)) {
            Swal.fire({
                icon: 'error',
                title: '❌ Erro',
                text: 'Arquivos APK e Ícone são obrigatórios para novos apps!',
            });
            return;
        }

        // Configurar o botão de loading
        const saveBtn = document.querySelector('#app_modal .btn-primary');
        const originalText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Salvando...';
        saveBtn.disabled = true;

        // Criar FormData
        const formData = new FormData();
        formData.append('action', id ? 'edit' : 'add');
        if (id) formData.append('id', id);
        formData.append('name', name);
        formData.append('active', active);
        if (apkFile) formData.append('apk_file', apkFile);
        if (iconFile) formData.append('icon_file', iconFile);

        // Enviar requisição
        fetch(window.location.href, {
            method: 'POST',
            body: formData,
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`Erro HTTP! Status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (!data) {
                throw new Error('Resposta vazia do servidor');
            }

            if (data.status === 'success') {
                Swal.fire({
                    icon: 'success',
                    title: '✅ Sucesso!',
                    text: data.message,
                }).then(() => {
                    $('#app_modal').modal('hide');
                    location.reload();
                });
            } else {
                throw new Error(data.message || 'Erro desconhecido');
            }
        })
        .catch(error => {
            console.error('Erro:', error);
            Swal.fire({
                icon: 'error',
                title: '❌ Erro',
                text: error.message || 'Falha ao salvar. Verifique o console para detalhes.',
            });
        })
        .finally(() => {
            saveBtn.disabled = false;
            saveBtn.innerHTML = originalText;
        });
    };

    window.deleteApp = function(id, name) {
        Swal.fire({
            title: '⚠️ Tem certeza?',
            text: `Você está prestes a excluir o app: ${name}. Isso também removerá os arquivos APK e ícone.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: '🗑️ Sim, excluir!',
            cancelButtonText: '❌ Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'delete',
                        id: id,
                    }),
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`Erro HTTP! Status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: '🗑️ Excluído!',
                            text: data.message,
                        }).then(() => location.reload());
                    } else {
                        throw new Error(data.message || 'Erro ao excluir');
                    }
                })
                .catch(error => {
                    console.error('Erro:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '❌ Erro',
                        text: error.message || 'Falha ao excluir. Verifique o console para detalhes.',
                    });
                });
            }
        });
    };

    window.toggleStatus = function(id, isChecked, checkbox) {
        const row = checkbox.closest('tr');
        const statusBadge = row.querySelector('.badge');

        // Desabilitar o checkbox durante a requisição
        checkbox.disabled = true;

        fetch(window.location.href, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'toggle',
                id: id,
            }),
        })
        .then(response => {
            if (!response.ok) throw new Error(`Erro HTTP! Status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            if (data.status !== 'success') {
                throw new Error(data.message || 'Falha ao alterar status');
            }

            // Atualizar visualização apenas após sucesso no servidor
            if (isChecked) {
                statusBadge.className = 'badge badge-light-success';
                statusBadge.textContent = '✅ Ativo';
            } else {
                statusBadge.className = 'badge badge-light-danger';
                statusBadge.textContent = '⛔ Inativo';
            }
        })
        .catch(error => {
            console.error('Erro:', error);
            // Reverter o estado do checkbox em caso de erro
            checkbox.checked = !isChecked;
            Swal.fire({
                icon: 'error',
                title: '❌ Erro',
                text: error.message || 'Falha ao alterar status',
            });
        })
        .finally(() => {
            checkbox.disabled = false;
        });
    };
});
</script>