<?php

//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/xx ------------------>
//<-------------DEVELOPER: ----------------->
//<----------------------------------------------------------->


session_start();

if (!isset($_SESSION['user'])) {
    header("Location: adm/login.php");
    exit;
}

require_once __DIR__ . '/db.php';

$apps = $db->query("
    SELECT apps.*, codigo_apk.codigo 
    FROM apps
    LEFT JOIN codigo_apk ON codigo_apk.app_id = apps.id
    ORDER BY apps.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="pt-ES">
<head>
<meta charset="UTF-8">
<title>Gerenciar APKs</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
body{
    background:#0f172a;
    color:white;
    margin:0;
    padding:0;
}

h2{
    text-align:center;
    margin-top:20px;
    border:1px solid rgba(255,255,255,0.20);
}

p {
    color: red;
    font-size:20px;
}

.container{
    width:95%;
    max-width:900px;
    margin:20px auto;
}

.btn-add{
    display:inline-block;
    padding:12px 18px;
    background:#2563eb;
    color:white;
    text-decoration:none;
    border-radius:10px;
    margin-bottom:20px;
    font-weight:bold;
    transition:.2s;
}
.btn-add:hover{ background:#1d4ed8; }

.apk-list{
    display:flex;
    flex-direction:column;
    gap:15px;
}

.apk-item{
    background:#111827;
    border:1px solid #1f2937;
    padding:15px;
    border-radius:12px;
    display:grid;
    grid-template-columns: 80px 1fr 70px;
    gap:15px;
    align-items:center;
}

.apk-item img{
    width:70px;
    height:70px;
    border-radius:12px;
    object-fit:cover;
    background:#333;
}

.apk-info strong{ font-size:16px; }
.apk-info small{ font-size:13px; color:#9ca3af; }

.btn-downloader{
    padding:8px 12px;
    font-size:12px;
    background: linear-gradient(135deg, #f0923a, #f57905);
    color:black;
    border:none;
    border-radius:6px;
    cursor:pointer;
    font-weight:bold;
}
.btn-downloader:hover{
    background: linear-gradient(135deg, #c8511c, #8a3a14);
}

.apk-middle{
    display:flex;
    flex-direction:column;
    gap:6px;
}

.apk-actions{
    display:flex;
    flex-direction:column;
    gap:10px;
}

.apk-actions a{
    width:45px;
    height:45px;
    display:flex;
    justify-content:center;
    align-items:center;
    border-radius:10px;
    color:white;
    font-size:20px;
}

.apk-actions .edit{ background:#3b82f6; }
.apk-actions .edit:hover{ background:#2563eb; }

.apk-actions .delete{ background:#dc2626; }
.apk-actions .delete:hover{ background:#b91c1c; }

/* ===================== MOBILE ===================== */
@media(max-width:600px){
    .apk-item{
        grid-template-columns: 80px 1fr 55px;
        padding:12px;
        gap:10px;
    }

    .apk-item img{
        width:65px;
        height:65px;
        border-radius:10px;
    }

    .apk-info strong{
        font-size:14px;
    }

    .apk-info small{
        font-size:12px;
    }

    .apk-actions{
        gap:8px;
    }

    .apk-actions a{
        width:40px !important;
        height:40px !important;
        font-size:18px;
    }
}
</style>

</head>
<body>

<?php include __DIR__ . '/includes/header.php'; ?>

<h2>Gerenciamento de APKs 📲
<br> 
<p>
Copie a URL APK curta<br>
Clique em Downloader e gere seu código<br>
Va em editar e salve seu codigo downloader ⬇️</p>
</h2>

<div class="container">

    <a href="add_apk.php" class="btn-add">
        <i class="fa-solid fa-plus"></i> Adicionar Aplicativo
    </a>
    
    <div class="apk-list">

        <?php if (empty($apps)): ?>
            <p>Nenhum aplicativo cadastrado.</p>
        <?php endif; ?>

        <?php foreach ($apps as $apk): ?>

            <?php
            $imgPath = "apps/{$apk['id']}/icone.png";
            $thumb = (!empty($apk['imagem']) && filter_var($apk['imagem'], FILTER_VALIDATE_URL))
                     ? $apk['imagem']
                     : (file_exists($imgPath) ? $imgPath : "logo/default.png");

            // BASE URL ABSOLUTA
            $baseURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")
                       . "://"
                       . $_SERVER['HTTP_HOST']
                       . dirname($_SERVER['SCRIPT_NAME']);

            $baseURL = rtrim($baseURL, "/");

            // URL COMPLETA DO APK
            $apkUrlFinal = "";
            $apkUrlCurta = "";

            if (!empty($apk['url_apk'])) {
                $apkUrlFinal = $apk['url_apk'];
                $apkUrlCurta = $apk['url_apk']; // se já for URL, mostra ela mesma
            } elseif (!empty($apk['arquivo_apk'])) {
                $apkUrlCurta = "apps/{$apk['id']}/" . $apk['arquivo_apk'];
                $apkUrlFinal = $baseURL . "/" . $apkUrlCurta;
            }
            ?>

            <div class="apk-item" id="apk-<?= $apk['id'] ?>">

                <!-- COLUNA 1 -->
                <div class="apk-info" style="display:flex; flex-direction:column; gap:5px;">
                    <img src="<?= $thumb . '?nocache=' . microtime(true) ?>">
                    <strong><?= $apk['nome']; ?></strong>
                    <small>ID: <?= $apk['id']; ?></small>
                </div>

                <!-- COLUNA 2 -->
                <div class="apk-middle">

                    <button class="btn-downloader" onclick="abrirDownloader(<?= $apk['id'] ?>)">
                        DOWNLOADER
                    </button>

                    <?php if (!empty($apk['codigo'])): ?>
                        <div style="font-size:13px; color:#7dd3fc;">
                            Código APK: <b><?= $apk['codigo'] ?></b>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($apkUrlCurta)): ?>
                        <div style="font-size:13px; color:#fcd34d; display:flex; align-items:center; gap:8px; margin-top:4px;">
                            URL APK:
                            <b><?= $apkUrlCurta ?></b>

                            <button onclick="copiarTexto('<?= $apkUrlFinal ?>')" 
                                style="background:#1e3a8a; border:none; color:white; padding:5px 8px; border-radius:6px; cursor:pointer;">
                                <i class="fa-regular fa-copy"></i>
                            </button>
                        </div>
                    <?php endif; ?>

                </div>

                <!-- COLUNA 3 -->
                <div class="apk-actions">

                    <a class="edit" href="editar_apk.php?id=<?= $apk['id']; ?>">
                        <i class="fa-solid fa-pen"></i>
                    </a>

                    <a class="delete" onclick="deleteApk(<?= $apk['id']; ?>)">
                        <i class="fa-solid fa-trash"></i>
                    </a>

                </div>

            </div>
        <?php endforeach; ?>

    </div>
</div>

<!-- CONTAINER DO DOWNLOADER -->
<div id="downloaderFrame" 
     style="display:none; position:fixed; top:10%; left:50%; transform:translateX(-50%);
            width:90%; height:80%; background:#000; border:2px solid #1f2937; 
            border-radius:12px; box-shadow:0 0 25px #000; z-index:99999;">
    
    <div style="padding:10px; text-align:right;">
        <button onclick="fecharDownloader()" 
                style="background:#dc2626; padding:6px 12px; border:none; 
                       border-radius:6px; color:white; cursor:pointer;">
            Fechar
        </button>
    </div>

    <iframe id="frameURL" src="" style="width:100%; height:90%; border:none;"></iframe>
</div>

<script>
function copiarTexto(txt){
    navigator.clipboard.writeText(txt);
    Swal.fire("Copiado!", "URL completa copiada.", "success");
}

function deleteApk(id){

    Swal.fire({
        title: "Excluir?",
        text: "Isso apagará também a pasta apps/"+id+"!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#d33",
        cancelButtonColor: "#3085d6",
        confirmButtonText: "Sim, excluir"
    }).then((result) => {

        if(result.isConfirmed){

            fetch("delete_apk.php?id=" + id)
            .then(r => r.json())
            .then(res => {

                if(res.ok){

                    Swal.fire({
                        icon: "success",
                        title: "Excluído!",
                        text: "O aplicativo foi removido.",
                        timer: 1200,
                        showConfirmButton: false
                    });

                    const item = document.querySelector("#apk-"+id);
                    item.style.transition = "0.4s";
                    item.style.opacity = "0";

                    setTimeout(()=> item.remove(), 400);

                } else {
                    Swal.fire("Erro", res.message, "error");
                }
            });
        }
    });
}

function abrirDownloader(id){
    document.getElementById("frameURL").src = "https://go.aftvnews.com/";
    document.getElementById("downloaderFrame").style.display = "block";
}

function fecharDownloader(){
    document.getElementById("downloaderFrame").style.display = "none";
    document.getElementById("frameURL").src = "";
}
</script>

</body>
</html>
