<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

if (!admin_is_authenticated()) {
    admin_redirect('/admin/?route=login');
}

$errors = [];
$notice = '';

$requestedAction = strtolower(trim((string) ($_GET['action'] ?? '')));
$requestedPlugin = admin_resolve_plugin_slug((string) ($_GET['plugin'] ?? ''));

if (in_array($requestedAction, ['activate', 'deactivate'], true) && $requestedPlugin !== '') {
    $config = cms_get_config(CMS_ROOT);
    $configPath = cms_config_path(CMS_ROOT);
    $activePlugins = $config['active_plugins'] ?? [];
    if (!is_array($activePlugins)) {
        $activePlugins = [];
    }

    if ($requestedAction === 'activate') {
        if (!in_array($requestedPlugin, $activePlugins, true)) {
            $activePlugins[] = $requestedPlugin;
        }
    } else {
        $activePlugins = array_values(array_filter($activePlugins, static fn(string $slug): bool => $slug !== $requestedPlugin));
    }

    $config['active_plugins'] = array_values(array_unique($activePlugins));

    $configWritable = is_file($configPath) ? is_writable($configPath) : is_writable(dirname($configPath));

    if (!$configWritable) {
        $errors[] = 'Config file is not writable.';
    } elseif (!cms_save_config($config, CMS_ROOT)) {
        $errors[] = 'Plugin state could not be saved.';
    } else {
        cms_set_plugin_status($requestedPlugin, $requestedAction === 'activate');
        error_log('[CMS Plugin Manager] ' . $requestedPlugin . ' => ' . $requestedAction);
        header('Location: plugins.php');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfToken = (string) ($_POST['csrf_token'] ?? '');
    if (!admin_verify_csrf($csrfToken)) {
        $errors[] = 'Security token mismatch. Please refresh and try again.';
    } else {
        $action = strtolower(trim((string) ($_POST['plugin_manager_action'] ?? '')));

        if ($action === 'create') {
            $pluginName = trim((string) ($_POST['plugin_name'] ?? ''));
            $pluginSlug = trim((string) ($_POST['plugin_slug'] ?? ''));
            $activateNow = !empty($_POST['activate_now']);
            $result = admin_create_plugin($pluginName, $pluginSlug, $activateNow);
            if ($result['ok']) {
                $notice = (string) $result['message'];
            } else {
                $errors[] = (string) $result['message'];
            }
        }
    }
}

$config = cms_get_config(CMS_ROOT);
$state = admin_refresh_state();
$pluginRegistry = $state['pluginRegistry'];
$availableThemes = $state['availableThemes'];
$registeredBlocks = $state['registeredBlocks'];
$activePlugins = $config['active_plugins'] ?? [];
if (!is_array($activePlugins)) {
    $activePlugins = [];
}

$siteTitle = admin_site_title($config);
$activeTheme = admin_active_theme($config);
$pluginCount = count($pluginRegistry);
$activePluginCount = count($activePlugins);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo admin_escape($siteTitle); ?> Plugins</title>
    <?php echo admin_shared_styles(); ?>
</head>
<body>
    <div class="app">
        <?php admin_render_sidebar('plugins'); ?>
        <main class="content">
            <div class="page-header"><div><h1 class="page-title">Plugin Manager</h1><div class="page-subtitle">Activate, edit, and create plugins from a cleaner mobile-first manager.</div></div></div>
            <?php if ($notice !== ''): ?><div class="message success"><?php echo admin_escape($notice); ?></div><?php endif; ?>
            <?php foreach ($errors as $error): ?><div class="message error"><?php echo admin_escape($error); ?></div><?php endforeach; ?>

            <div class="panel">
                <div class="grid">
                    <div class="stat-card">
                        <div class="stat-label">Installed Plugins</div>
                        <div class="stat-value"><?php echo (string) $pluginCount; ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">Active Plugins</div>
                        <div class="stat-value"><?php echo (string) $activePluginCount; ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">Active Theme</div>
                        <div class="stat-value"><?php echo admin_escape($activeTheme); ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">Registered Blocks</div>
                        <div class="stat-value"><?php echo (string) count($registeredBlocks); ?></div>
                    </div>
                </div>
            </div>

            <div class="panel">
                <div class="grid">
                    <?php foreach ($pluginRegistry as $plugin): ?>
                        <?php $isActive = in_array((string) $plugin['slug'], $activePlugins, true); ?>
                        <article class="stat-card plugin-card" data-plugin="<?php echo admin_escape((string) $plugin['slug']); ?>">
                            <div class="stat-label plugin-status"><?php echo $isActive ? 'Active' : 'Inactive'; ?></div>
                            <div class="stat-value" style="font-size:22px;"><?php echo admin_escape((string) $plugin['name']); ?></div>
                            <p style="margin:10px 0 0; color:var(--muted);"><?php echo admin_escape((string) $plugin['description']); ?></p>
                            <p style="margin:8px 0 0; color:var(--muted); font-size:13px;">Slug: <?php echo admin_escape((string) ($plugin['declared_slug'] ?? $plugin['slug'])); ?></p>
                            <p style="margin:6px 0 0; color:var(--muted); font-size:13px;">Version: <?php echo admin_escape((string) $plugin['version']); ?></p>
                            <?php if (!empty($plugin['error'])): ?><div class="message error" style="margin-top:12px;"><?php echo admin_escape((string) $plugin['error']); ?></div><?php endif; ?>
                            <div class="inline-actions">
                                <a class="btn" href="/admin/plugins.php?action=<?php echo $isActive ? 'deactivate' : 'activate'; ?>&plugin=<?php echo rawurlencode((string) $plugin['slug']); ?>"><?php echo $isActive ? 'Deactivate' : 'Activate'; ?></a>
                                <a class="btn secondary" href="/admin/plugin-editor.php?plugin=<?php echo rawurlencode((string) $plugin['slug']); ?>">Edit</a>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="panel">
                <h2 style="margin-top:0;">Add New Plugin</h2>
                <form method="post" action="/admin/plugins.php">
                    <input type="hidden" name="csrf_token" value="<?php echo admin_escape(admin_csrf_token()); ?>">
                    <input type="hidden" name="plugin_manager_action" value="create">
                    <div class="form-row">
                        <label for="plugin_name">Plugin Name</label>
                        <input id="plugin_name" name="plugin_name" type="text" required>
                    </div>
                    <div class="form-row">
                        <label for="plugin_slug">Plugin Slug</label>
                        <input id="plugin_slug" name="plugin_slug" type="text" required>
                    </div>
                    <label style="display:flex; gap:10px; align-items:center; margin:0 0 16px;">
                        <input type="checkbox" name="activate_now" value="1" checked>
                        Activate immediately
                    </label>
                    <button class="btn" type="submit">Create Plugin</button>
                </form>
            </div>
        </main>
    </div>
</body>
</html>
