<?php

declare(strict_types=1);

class AdminUpdateController
{
    public static function routes(): void
    {
        Router::get('/admin/updates', [self::class, 'index']);
        Router::post('/admin/updates/check', [self::class, 'check']);
        Router::post('/admin/updates/apply', [self::class, 'apply']);
        Router::post('/admin/updates/theme-diff', [self::class, 'themeDiff']);
        Router::post('/admin/updates/theme-diff-demo', [self::class, 'themeDiffDemo']);
        Router::get('/admin/updates/log', [self::class, 'log']);
        Router::post('/admin/updates/rollback', [self::class, 'rollback']);
        Router::get('/admin/updates/backups', [self::class, 'backups']);
    }

    public static function index(): void
    {
        Auth::requireSuperAdmin();

        $updates = UpdateManager::getAvailableUpdates();

        Router::render('admin/updates', [
            'pageTitle' => 'Updates',
            'activeMenu' => 'updates',
            'contentTemplate' => '_updates',
            'updates' => $updates,
            'currentVersion' => APP_VERSION,
        ]);
    }

    public static function check(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
            exit;
        }
        header('Content-Type: application/json');

        $updates = UpdateManager::refresh();
        $count = 0;
        if (!empty($updates['cms'])) $count++;
        $count += count($updates['plugins'] ?? []);
        $count += count($updates['themes'] ?? []);

        echo json_encode([
            'success' => true,
            'updates' => $updates,
            'count' => $count,
        ]);
        exit;
    }

    public static function apply(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
            exit;
        }
        header('Content-Type: application/json');

        $input = json_decode(file_get_contents('php://input') ?: '{}', true);
        $type = trim($input['type'] ?? '');
        $slug = trim($input['slug'] ?? '');
        $version = trim($input['version'] ?? '');
        $checksum = trim($input['checksum'] ?? '');
        $isFree = !empty($input['is_free']);

        if ($type === '' || $version === '') {
            echo json_encode(['success' => false, 'error' => 'Missing type or version']);
            exit;
        }

        if ($type !== 'cms' && ($slug === '' || !preg_match('/^[a-zA-Z0-9_-]+$/', $slug))) {
            echo json_encode(['success' => false, 'error' => 'Invalid slug']);
            exit;
        }

        if (!preg_match('/^[a-zA-Z0-9._-]+$/', $version)) {
            echo json_encode(['success' => false, 'error' => 'Invalid version format']);
            exit;
        }

        $result = match ($type) {
            'cms' => UpdateManager::updateCore($version, $checksum),
            'plugin' => UpdateManager::updatePlugin($slug, $version, $checksum, $isFree),
            'theme' => UpdateManager::updateTheme($slug, $version, $checksum, $isFree),
            default => ['success' => false, 'error' => 'Invalid update type'],
        };

        echo json_encode($result);
        exit;
    }

    public static function themeDiff(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
            exit;
        }
        header('Content-Type: application/json');

        $input = json_decode(file_get_contents('php://input') ?: '{}', true);
        $slug = trim($input['slug'] ?? '');
        $version = trim($input['version'] ?? '');
        $checksum = trim($input['checksum'] ?? '');
        $isFree = !empty($input['is_free']);

        if ($slug === '' || $version === '') {
            echo json_encode(['success' => false, 'error' => 'Missing slug or version']);
            exit;
        }

        $result = UpdateManager::getThemeDiff($slug, $version, $checksum, $isFree);
        echo json_encode($result);
        exit;
    }

    public static function themeDiffDemo(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
            exit;
        }
        header('Content-Type: application/json');

        $input = json_decode(file_get_contents('php://input') ?: '{}', true);
        $slug = trim($input['slug'] ?? 'simply');

        if (!preg_match('/^[a-zA-Z0-9_-]+$/', $slug)) {
            echo json_encode(['success' => false, 'error' => 'Invalid slug']);
            exit;
        }

        $result = UpdateManager::getThemeDiffDemo($slug);
        echo json_encode($result);
        exit;
    }

    public static function log(): void
    {
        Auth::requireSuperAdmin();
        header('Content-Type: application/json');

        echo json_encode(['success' => true, 'log' => UpdateManager::getUpdateLog(50)]);
        exit;
    }

    public static function backups(): void
    {
        Auth::requireSuperAdmin();
        header('Content-Type: application/json');

        $type = trim($_GET['type'] ?? '');
        echo json_encode(['success' => true, 'backups' => UpdateManager::listBackups($type)]);
        exit;
    }

    public static function rollback(): void
    {
        Auth::requireSuperAdmin();
        if (!Router::verifyCsrf()) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
            exit;
        }
        header('Content-Type: application/json');

        $input = json_decode(file_get_contents('php://input') ?: '{}', true);
        $type = trim($input['type'] ?? '');
        $slug = trim($input['slug'] ?? '');
        $backupName = trim($input['backup_name'] ?? '');

        if ($type === '' || $slug === '' || $backupName === '') {
            echo json_encode(['success' => false, 'error' => 'Missing required fields']);
            exit;
        }

        if (!preg_match('/^[a-zA-Z0-9_-]+$/', $slug) || !preg_match('/^[a-zA-Z0-9_.-]+$/', $backupName)) {
            echo json_encode(['success' => false, 'error' => 'Invalid parameters']);
            exit;
        }

        $result = UpdateManager::rollback($type, $slug, $backupName);
        echo json_encode($result);
        exit;
    }
}
