<?php
function getBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'];
    return $protocol . $domainName;
}

if (isset($_GET['id'])) {
    $appId = $_GET['id'];

    try {
        $db = new PDO('sqlite:./api/.apps.db');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $db->prepare("SELECT buylink, iconeapp FROM apks WHERE id = :id");
        $stmt->bindParam(':id', $appId);
        $stmt->execute();
        $app = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($app) {
            if ($app['buylink']) {
                $apkFilePath = $_SERVER['DOCUMENT_ROOT'] . str_replace(getBaseUrl(), '', $app['buylink']);
                if (file_exists($apkFilePath)) {
                    unlink($apkFilePath);
                }
            }

            if ($app['iconeapp']) {
                $iconFilePath = $_SERVER['DOCUMENT_ROOT'] . str_replace(getBaseUrl(), '', $app['iconeapp']);
                if (file_exists($iconFilePath)) {
                    unlink($iconFilePath);
                }
            }
            $stmt = $db->prepare("DELETE FROM apks WHERE id = :id");
            $stmt->bindParam(':id', $appId);
            $stmt->execute();
            header("Location: view_apps.php");
            exit();
        } else {
            echo "App not found.";
        }
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
} else {
    echo "No app ID provided.";
}
?>