<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $dbPath = realpath(dirname(__FILE__)) . '/.apps.db';
        if (!file_exists($dbPath)) {
            throw new Exception("Database file not found at $dbPath");
        }
        $db = new PDO('sqlite:' . $dbPath);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $db->query("SELECT * FROM apks");
        $apks = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Troque pela sua url atual para a launcher poder mostra os ícones
        $baseUrl = 'https://linkdopainel/public/iconeapp/';
        foreach ($apks as &$apk) {
            $apk['iconeapp'] = $baseUrl . $apk['fileimage'];
        }

        header('Content-Type: application/json');
        $json_response = json_encode($apks, JSON_PRETTY_PRINT);

        header('Content-Length: ' . strlen($json_response));

        http_response_code(200);

        echo $json_response;
    } catch (PDOException $e) {
        echo json_encode(["error" => $e->getMessage()]);
    } catch (Exception $e) {
        echo json_encode(["error" => $e->getMessage()]);
    }
} else {
    
    header('Content-Type: application/json');
    http_response_code(405);
    echo json_encode(["error" => "Method Not Allowed"]);
}
?>