<?php
// salvar_apps.php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['name']) && !empty($_POST['package']) && isset($_FILES['icon_file']) && isset($_FILES['apk_file'])) {
        try {
            // Caminhos onde salvar os arquivos
            $uploadsDirIcons = __DIR__ . '/uploads/icons/';
            $uploadsDirApks = __DIR__ . '/uploads/apks/';

            // Cria as pastas se não existirem
            if (!is_dir($uploadsDirIcons)) mkdir($uploadsDirIcons, 0777, true);
            if (!is_dir($uploadsDirApks)) mkdir($uploadsDirApks, 0777, true);

            // Trata o upload do ícone
            $iconName = uniqid('icon_') . '_' . basename($_FILES['icon_file']['name']);
            $iconPath = $uploadsDirIcons . $iconName;
            move_uploaded_file($_FILES['icon_file']['tmp_name'], $iconPath);

            // Trata o upload do APK
            $apkName = uniqid('apk_') . '_' . basename($_FILES['apk_file']['name']);
            $apkPath = $uploadsDirApks . $apkName;
            move_uploaded_file($_FILES['apk_file']['tmp_name'], $apkPath);

            // URLs públicas para acessar depois
            $baseURL = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
            $iconUrl = $baseURL . "/uploads/icons/" . $iconName;
            $apkUrl = $baseURL . "/uploads/apks/" . $apkName;

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

            $db->exec("
                CREATE TABLE IF NOT EXISTS apps (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    package TEXT NOT NULL,
                    apk_url TEXT NOT NULL,
                    icon_url TEXT NOT NULL
                )
            ");

            $stmt = $db->prepare("INSERT INTO apps (name, package, apk_url, icon_url) VALUES (:name, :package, :apk_url, :icon_url)");
            $stmt->execute([
                ':name' => $_POST['name'],
                ':package' => $_POST['package'],
                ':apk_url' => $apkUrl,
                ':icon_url' => $iconUrl
            ]);

            header('Location: painel.php?sucesso=1');
            exit;

        } catch (PDOException $e) {
            echo "Erro ao salvar: " . $e->getMessage();
        }
    } else {
        echo "Preencha todos os campos e envie os arquivos!";
    }
}
?>
