<?php

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


require_once __DIR__ . "/db.php";

/* ---- STYLE JSON ---- */
$stylePath = __DIR__ . "/config/style.json";
$style = file_exists($stylePath) ? json_decode(file_get_contents($stylePath), true) : [];

/* ---- ALERT JSON ---- */
$alertPath = __DIR__ . "/config/alert.json";
$alert = file_exists($alertPath) ? json_decode(file_get_contents($alertPath), true) : ["enabled" => false];

/* ---- WHATSAPP JSON ---- */
$wppPath = __DIR__ . "/config/whatsapp.json";
$wpp = file_exists($wppPath) ? json_decode(file_get_contents($wppPath), true) : [
    "modelo" => "📱 *Baixe agora:* {TITULO}\n🔑 Código APK: {CODIGO}"
];

/* ---- APPS ---- */
$stmt = $db->prepare("SELECT * FROM apps ORDER BY id DESC");
$stmt->execute();
$apps = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* BASE URL (com /shop se existir) */
$scriptDir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
if ($scriptDir === '/' || $scriptDir === '\\') $scriptDir = '';
$baseURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")
         . "://" . $_SERVER["HTTP_HOST"] . $scriptDir;
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $style["titulo_loja"] ?? "Loja de Aplicativos" ?></title>

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

<style>
:root{
    /* fundo */
    --body-background: <?= $style["cor_fundo_pagina"] ?? "#040010" ?>;
    --header-text: <?= $style["cor_titulo_pagina"] ?? "#ffffff" ?>;

    /* cards */
    --card-background: <?= $style["cor_card_fundo"] ?? "#231c26" ?>;
    --card-shadow: <?= $style["cor_card_sombra"] ?? "#00000050" ?>;
    --card-title: <?= $style["cor_card_titulo"] ?? "#ffffff" ?>;
    --card-desc: <?= $style["cor_card_descricao"] ?? "#ffffff" ?>;

    /* caixa código */
    --codigo-bg: <?= $style["cor_codigo_fundo"] ?? "#1f2937" ?>;
    --codigo-text: <?= $style["cor_codigo_texto"] ?? "#ffffff" ?>;
    --codigo-strong: <?= $style["cor_codigo_strong"] ?? "#ff0000" ?>;

    /* botões */
    --btn-text: <?= $style["btn_texto"] ?? "#ffffff" ?>;
    --btn-download-bg: <?= $style["btn_download_bg"] ?? "#ff0000" ?>;
    --btn-download-hover: <?= $style["btn_download_hover"] ?? "#c22727" ?>;

    --btn-share-bg: <?= $style["btn_share_bg"] ?? "#2bc241" ?>;
    --btn-share-hover: <?= $style["btn_share_hover"] ?? "#2e8b46" ?>;

    --btn-copy-bg: <?= $style["btn_copiar_bg"] ?? "#0000ff" ?>;
    --btn-copy-hover: <?= $style["btn_copiar_hover"] ?? "#25008c" ?>;

    /* SWEETALERT – PEGANDO CORES DO PERSONALIZAR */
    --sweetalert-confirm-button: <?= $style["alert_confirmar"] ?? "#2563eb" ?>;
    --sweetalert-telegram-button: <?= $style["alert_entrar_canal"] ?? "#10b981" ?>;
    --sweetalert-telegram-cancel-button: <?= $style["alert_fechar"] ?? "#ef4444" ?>;
    --sweetalert-background: <?= $style["alert_fundo"] ?? "#1f2937" ?>;
    --sweetalert-text: <?= $style["alert_texto"] ?? "#ffffff" ?>;
}



body{
    font-family: Arial;
    background: var(--body-background);
    margin:0;
    padding:0;
}

.container-main{
    max-width:1200px;
    margin:auto;
    padding:12px;
    display:grid;
    gap:14px;
}
@media(min-width:600px){
    .container-main{ grid-template-columns:repeat(2,1fr); }
}
@media(min-width:1024px){
    .container-main{ grid-template-columns:repeat(3,1fr); }
}

.header{
    grid-column:1/-1;
    text-align:center;
}
.header img{
    max-width:240px;
    max-height:90px;
}
.header h2{
    color: var(--header-text);
    margin-top:6px;
}

.app-card{
    background: var(--card-background);
    border-radius:16px;
    padding:18px;
    box-shadow:0 0 10px var(--card-shadow);
}
.app-card img{
    width: 100%;
    height: 300px; /* define altura fixa */
    object-fit: cover; /* recorta e mantém proporção sem deformar */
    border-radius: 12px;
    margin-bottom: 12px;
}


.app-title{
    font-size:20px;
    font-weight:700;
    text-align:center;
    color: var(--card-title);
}
.app-desc{
    color: var(--card-desc);
    text-align:center;
    font-size:15px;
    margin-bottom:14px;
}

.codes-box{
    background: var(--codigo-bg);
    padding:10px;
    border-radius:12px;
    margin-bottom:14px;
}
.codes-box p{ color: var(--codigo-text); }
.codes-box strong{ color: var(--codigo-strong); }
.codigo-white{ color:white; font-weight:bold; }

.btn{
    display:flex;
    justify-content:center;
    align-items:center;
    gap:8px;
    width:94%;
    padding:12px;
    border-radius:8px;
    color: var(--btn-text);
    cursor:pointer;
    font-weight:bold;
    margin-bottom:10px;
    text-decoration:none;
}

.btn-download{ background: var(--btn-download-bg); }
.btn-download:hover{ background: var(--btn-download-hover); }

.btn-share{ background: var(--btn-share-bg); }
.btn-share:hover{ background: var(--btn-share-hover); }

.btn-copy{ background: var(--btn-copy-bg); }
.btn-copy:hover{ background: var(--btn-copy-hover); }

.btn-row{ display:flex; gap:10px; }
.btn-row .btn{ width:50%; }

/* FORÇA O SWEETALERT A FICAR SÓLIDO */
.swal2-popup {
    background: #ffffff !important;
    backdrop-filter: none !important;
    -webkit-backdrop-filter: none !important;
}

/* FUNDO DO MODAL 100% OPACO */
.swal2-container {
    background: rgba(0,0,0,0.55) !important;
}

</style>
</head>
<body>

<div class="container-main">

    <div class="header">
        <img src="<?= $style['logo'] ?? 'logo_loja/logo.png' ?>">
        <h2><?= $style["titulo_loja"] ?? "Loja de Aplicativos" ?></h2>
    </div>

    <?php foreach ($apps as $app): ?>
    <div class="app-card">

        <img src="apps/<?= $app['id'] ?>/<?= $app['imagem'] ?>">

        <div class="app-title"><?= $app["nome"] ?></div>
        <div class="app-desc"><?= $app["descricao"] ?></div>

        <?php if ($app["codigo_downloader"] || $app["codigo_ntdown"]): ?>
        <div class="codes-box">

            <?php if ($app["codigo_downloader"]): ?>
                <p><strong style= "color:red";>📑 Código Downloader:</strong> <span class="codigo-white"><?= $app["codigo_downloader"] ?></span></p>
            <?php endif; ?>

            <?php if ($app["codigo_ntdown"]): ?>
                <!--<p><strong>📑 Código Downloader:</strong> <span class="codigo-white"><?= $app["codigo_ntdown"] ?></span></p>
            <?php endif; ?>

        </div>
        <?php endif; ?>

        <?php
        /* LINK DO APK */
        if (!empty($app['url_apk'])) {
            $apkLink = $app['url_apk'];
        } elseif (!empty($app['arquivo_apk'])) {
            $apkLink = $baseURL . "/apps/{$app['id']}/{$app['arquivo_apk']}";
        } else {
            $apkLink = "#";
        }

        /* WHATSAPP */
/* BUSCAR CÓDIGO REAL DO APK (TABELA codigo_apk) */
$stmC = $db->prepare("SELECT codigo FROM codigo_apk WHERE app_id = ? ORDER BY id DESC LIMIT 1");
$stmC->execute([$app["id"]]);
$codigoAPKreal = $stmC->fetchColumn();

if ($codigoAPKreal) {
    $codigo = $codigoAPKreal; 
    $codigo_link = $baseURL . "/download.php?codigo=" . $codigo;
} else {
    $codigo = "Código indisponível";
    $codigo_link = "#";
}

/* MENSAGEM DO WHATSAPP */
$shareText = str_replace(
    ["{TITULO}", "{URL_APK}"],
    [$app["nome"], $apkLink],
    $wpp["modelo"]
);




        ?>

        <a class="btn btn-download"
           onclick="Descargar APK(<?= $app['id'] ?>,'<?= $apkLink ?>')">
           <i class="fa-solid fa-download"></i> Descargar APK
        </a>

        <div class="btn-row">
            <a class="btn btn-share"
               href="https://api.whatsapp.com/send?text=<?= urlencode($shareText) ?>"
               target="_blank">
               <i class="fa-brands fa-whatsapp"></i> Compartir
            </a>

            <button class="btn btn-copy" onclick='copiarTexto(`<?= $shareText ?>`)'>
                <i class="fa-solid fa-copy"></i> Copiar Dados
            </button>
        </div>

    </div>
    <?php endforeach; ?>

</div>

<script>
function copiarTexto(txt){
    navigator.clipboard.writeText(txt);
    Swal.fire("Copiado!", "Conteúdo copiado.", "success");
}

function baixarAPK(id, url){
    if(url === "#"){
        Swal.fire("Ops!", "APK não configurado.", "warning");
        return;
    }

    fetch("update_download_count.php?id=" + id)
        .then(() => {
            setTimeout(() => { 
                window.location = url; 
            }, 80); // delay para garantir que o fetch finalize
        });
}
</script>

<script>
document.addEventListener("DOMContentLoaded", () => {

    // PUXA O JSON DO ALERTA
    <?php
    $alertPath = __DIR__ . "/config/alert.json";
    $alert = file_exists($alertPath)
        ? json_decode(file_get_contents($alertPath), true)
        : ["enabled" => false];
    ?>

    const alertData = <?= json_encode($alert, JSON_UNESCAPED_UNICODE) ?>;

    if (!alertData.enabled) return;

    setTimeout(() => {
        Swal.fire({
            title: alertData.title,
            html: `<p style="font-size:16px;color:#333;margin-top:8px;">${alertData.text}</p>`,
            imageUrl: alertData.image_url,
            imageWidth: alertData.image_width,
            imageHeight: alertData.image_height,
            imageAlt: alertData.image_alt,

            showCloseButton: true,
            showCancelButton: true,

            cancelButtonText: alertData.cancel_text,
            confirmButtonText: alertData.confirm_text,

            confirmButtonColor: "var(--sweetalert-telegram-button)",
            cancelButtonColor: "var(--sweetalert-telegram-cancel-button)",

            background: "var(--sweetalert-background)",
            color: "var(--sweetalert-text)",

            padding: "20px 15px",
            width: 380,
            allowOutsideClick: true
        }).then(result => {
            if (result.isConfirmed) {
                window.open(alertData.link, "_blank");
            }
        });

    }, 400);
});
</script>

<script>
document.oncontextmenu = () => false;
document.body.oncut = document.body.oncopy = document.body.onpaste = () => false;

// tenta detectar devtools aberto
setInterval(function (){
   if (window.outerHeight - window.innerHeight > 200 ||
       window.outerWidth - window.innerWidth > 200) {
       window.location.href = "about:blank";
   }
}, 1000);
</script>
</body>
</html>
