<?php

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


session_start();

header("Content-Type: application/json");

if (!isset($_SESSION['user'])) {
    echo json_encode(["ok" => false, "message" => "Não logado"]);
    exit;
}

require_once __DIR__ . '/db.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    echo json_encode(["ok" => false, "message" => "ID inválido"]);
    exit;
}

try {
    // Verifica se existe
    $stmt = $db->prepare("SELECT id FROM apps WHERE id = ?");
    $stmt->execute([$id]);
    $app = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$app) {
        echo json_encode(["ok" => false, "message" => "Aplicativo não encontrado"]);
        exit;
    }

    // Apaga do banco
    $stmtDel = $db->prepare("DELETE FROM apps WHERE id = ?");
    $stmtDel->execute([$id]);

    // Apaga a pasta
    $dir = __DIR__ . "/apps/" . $id;

    if (is_dir($dir)) {

        $it = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($it as $file) {
            if ($file->isDir()) {
                @rmdir($file->getPathname());
            } else {
                @unlink($file->getPathname());
            }
        }

        @rmdir($dir);
    }

    echo json_encode(["ok" => true]);

} catch (Exception $e) {

    echo json_encode([
        "ok" => false,
        "message" => "Erro interno"
    ]);
}
