<?php
declare(strict_types=1);

require_once __DIR__ . '/app/Helpers/bootstrap.php';

$user = require_login();
if (($user['role'] ?? '') !== 'main_admin') {
    http_response_code(403);
    exit(t('uninstall.error_access'));
}

$confirmationPhrase = 'DELETE TRIPTALE';
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();

    $password = (string)($_POST['password'] ?? '');
    $phrase = trim((string)($_POST['confirmation_phrase'] ?? ''));
    $confirmed = (string)($_POST['confirmed'] ?? '') === '1';

    try {
        $statement = db()->prepare('SELECT password_hash FROM ' . table('users') . ' WHERE id=:id AND role=\'main_admin\' AND status=\'active\' AND deleted_at IS NULL');
        $statement->execute([':id' => (int)$user['id']]);
        $passwordHash = (string)($statement->fetchColumn() ?: '');
    } catch (Throwable $exception) {
        $passwordHash = '';
    }

    if ($passwordHash === '' || !password_verify($password, $passwordHash)) {
        $error = t('uninstall.error_password');
    } elseif (!hash_equals($confirmationPhrase, $phrase) || !$confirmed) {
        $error = t('uninstall.error_confirmation');
    } else {
        $root = realpath(__DIR__);
        $markers = ['app/Helpers/bootstrap.php', 'config/config.php', 'database/install-manifest.php'];
        $validRoot = is_string($root) && $root !== '';
        foreach ($markers as $marker) {
            if (!$validRoot || !is_file($root . DIRECTORY_SEPARATOR . $marker)) {
                $validRoot = false;
                break;
            }
        }

        $prefix = (string)(app_config()['database']['prefix'] ?? '');
        if (!$validRoot) {
            $error = t('uninstall.error_markers');
        } elseif (!preg_match('/^[A-Za-z][A-Za-z0-9_]{1,30}$/', $prefix)) {
            $error = t('uninstall.error_prefix');
        } else {
            try {
                $tables = [];
                foreach (db()->query('SHOW TABLES')->fetchAll(PDO::FETCH_NUM) as $row) {
                    $tableName = (string)($row[0] ?? '');
                    if (str_starts_with($tableName, $prefix)) {
                        $tables[] = $tableName;
                    }
                }
                if (!in_array($prefix . 'users', $tables, true)) {
                    throw new RuntimeException('TripTale table marker missing.');
                }
                $quotedTables = array_map(static fn(string $name): string => '`' . str_replace('`', '``', $name) . '`', $tables);
                db()->exec('SET FOREIGN_KEY_CHECKS=0');
                try {
                    db()->exec('DROP TABLE IF EXISTS ' . implode(', ', $quotedTables));
                } finally {
                    try { db()->exec('SET FOREIGN_KEY_CHECKS=1'); } catch (Throwable $ignored) {}
                }
            } catch (Throwable $exception) {
                $error = t('uninstall.error_database');
            }

            if ($error === null) {
                $completedTitle = t('uninstall.completed_title');
                $completedText = t('uninstall.completed');
                $failedFiles = [];
                try {
                    $iterator = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::CHILD_FIRST
                    );
                    foreach ($iterator as $entry) {
                        $path = $entry->getPathname();
                        $removed = ($entry->isLink() || $entry->isFile()) ? @unlink($path) : @rmdir($path);
                        if (!$removed && file_exists($path)) {
                            $failedFiles[] = $path;
                        }
                    }
                } catch (Throwable $exception) {
                    $failedFiles[] = $root;
                }

                while (ob_get_level() > 0) {
                    ob_end_clean();
                }
                $message = $failedFiles === [] ? $completedText : t('uninstall.completed_files_warning');
                ?><!doctype html><html lang="<?= htmlspecialchars(language(), ENT_QUOTES, 'UTF-8') ?>"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= htmlspecialchars($completedTitle, ENT_QUOTES, 'UTF-8') ?></title><style>body{font-family:system-ui,sans-serif;margin:0;padding:32px;background:#f4f6f8;color:#17202a}main{max-width:640px;margin:8vh auto;padding:28px;background:#fff;border-radius:14px;box-shadow:0 4px 18px #0001}h1{margin-top:0}</style></head><body><main><h1><?= htmlspecialchars($completedTitle, ENT_QUOTES, 'UTF-8') ?></h1><p><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></p></main></body></html><?php
                exit;
            }
        }
    }
}
?>
<!doctype html><html lang="<?= htmlspecialchars(language(), ENT_QUOTES, 'UTF-8') ?>"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= htmlspecialchars(t('uninstall.title'), ENT_QUOTES, 'UTF-8') ?> · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:680px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}.button,button{display:inline-block;padding:10px 13px;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer}.back{background:#e3ebee;color:#126e82}.danger{margin:20px 0;padding:18px;border:2px solid #9d2d2d;border-radius:10px;background:#fff4f2}.danger h2{margin-top:0;color:#8b2424}label{display:block;margin-top:18px;font-weight:700}input[type="password"],input[type="text"]{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.check{display:flex;align-items:flex-start;gap:9px}.check input{margin-top:3px}.delete-installation{margin-top:22px;background:#9d2d2d;color:#fff}.hint{color:#59636d}.error{padding:12px;border-radius:8px;background:#ffe6e3;color:#8b2424}@media(max-width:600px){body{padding:12px}main{padding:16px}.delete-installation{width:100%}}</style></head><body><main><a class="button back" href="/settings.php"><?= htmlspecialchars(t('settings.back_to_settings'), ENT_QUOTES, 'UTF-8') ?></a><h1><?= htmlspecialchars(t('uninstall.title'), ENT_QUOTES, 'UTF-8') ?></h1><p class="hint"><?= htmlspecialchars(t('uninstall.intro'), ENT_QUOTES, 'UTF-8') ?></p><section class="danger"><h2><?= htmlspecialchars(t('uninstall.warning_title'), ENT_QUOTES, 'UTF-8') ?></h2><p><?= htmlspecialchars(t('uninstall.warning'), ENT_QUOTES, 'UTF-8') ?></p><p><?= htmlspecialchars(t('uninstall.folder_warning'), ENT_QUOTES, 'UTF-8') ?></p></section><?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><form method="post" onsubmit="return confirm(<?= htmlspecialchars(json_encode(t('uninstall.confirm_dialog'), JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') ?>)"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><label><?= htmlspecialchars(t('uninstall.password'), ENT_QUOTES, 'UTF-8') ?><input type="password" name="password" autocomplete="current-password" required></label><label><?= htmlspecialchars(str_replace('{phrase}', $confirmationPhrase, t('uninstall.phrase')), ENT_QUOTES, 'UTF-8') ?><input type="text" name="confirmation_phrase" autocomplete="off" required></label><label class="check"><input type="checkbox" name="confirmed" value="1" required><span><?= htmlspecialchars(t('uninstall.confirmation'), ENT_QUOTES, 'UTF-8') ?></span></label><button class="delete-installation delete" type="submit"><?= htmlspecialchars(t('uninstall.submit'), ENT_QUOTES, 'UTF-8') ?></button></form></main></body></html>
