<?php
/**
 * @intranet-file base/plugin_builder/_templates/plugin_uninstaller.tpl.php
 * @intranet-file-version 2026.03.13.1
 * @intranet-file-date 2026-03-13
 * @intranet-file-owner CSIF Intranet
 */
declare(strict_types=1);

$PLUGIN_META_JSON = <<<'JSON'
__PLUGIN_META_JSON__
JSON;

$PLUGIN_META = json_decode($PLUGIN_META_JSON, true);
if (!is_array($PLUGIN_META)) {
    throw new RuntimeException("PLUGIN_META inválido");
}

function plugin_uninstall(PDO $pdo, array $ctx = []): array
{
    global $PLUGIN_META;

    $publicRoot = $ctx['public_root'] ?? realpath(__DIR__ . '/../../..');
    $pluginId = (string) $PLUGIN_META['app_id'];

    $appFolder = '';
    if (!empty($PLUGIN_META['app']['folder'])) {
        $appFolder = (string) $PLUGIN_META['app']['folder'];
    } elseif (preg_match('~^/apps/([^/]+)/~', (string) $PLUGIN_META['url'], $m)) {
        $appFolder = $m[1];
    }

    if ($appFolder !== '') {
        $linkPath = $publicRoot . '/apps/' . $appFolder;
        if (is_link($linkPath) || file_exists($linkPath)) {
            @unlink($linkPath);
        }
    }

    try {
        $st = $pdo->prepare("DELETE FROM intranet_apps WHERE app_id=?");
        $st->execute([$pluginId]);
    } catch (Throwable $e) {
    }

    try {
        $st = $pdo->prepare("DELETE FROM intranet_plugins WHERE id=?");
        $st->execute([$pluginId]);
    } catch (Throwable $e) {
    }

    return ['ok' => true, 'msg' => 'Plugin desinstalado'];
}

// Modo no interactivo desde el manager
if (isset($pdo_for_plugin) && $pdo_for_plugin instanceof PDO) {
    $ctx = $PLUGIN_UNINSTALL_CTX ?? [];
    plugin_uninstall($pdo_for_plugin, is_array($ctx) ? $ctx : []);
    return;
}

// Modo directo/manual
try {
    require_once dirname(__DIR__, 3) . '/common/db.php';
    $pdo = db();
    $res = plugin_uninstall($pdo, []);
    echo ($res['ok'] ? 'OK' : 'ERROR') . ' - ' . ($res['msg'] ?? '');
} catch (Throwable $e) {
    echo 'ERROR - ' . $e->getMessage();
}