<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    try {

        $dbPath = realpath(dirname(__FILE__) . '/..') . '/api/.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 title, description, plataform, url_image FROM config");
        $configs = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if (empty($configs)) {
            $configs = array(
                array(
                    "plataform" => "SUA MELHOR OPÇÃO",
                    "title" => "Teste",
                    "description" => "SUPORTE (41) 9721-1993",
                    "url_image" => "http://bgs.brstorelauncher.xyz/3770effdb419532d478fa099ce704dab.jpg"
                )
            );
        }

        $json_response = json_encode($configs);

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

        http_response_code(200);

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