<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';

fate_admin_require_login();

if (!fate_plugins_feature_available()) {
    header('Location: index.php', true, 302);
    exit;
}

$error = null;
$saved = isset($_GET['saved']) && $_GET['saved'] === '1';
$registrySaved = isset($_GET['registry_saved']) && $_GET['registry_saved'] === '1';
$rows = fate_plugins_admin_rows();
$discovered = fate_plugins_discover_candidates();

$editId = isset($_GET['edit']) && is_string($_GET['edit']) ? strtolower(trim($_GET['edit'])) : '';
$registerPrefill = isset($_GET['register']) && is_string($_GET['register']) ? $_GET['register'] : '';
$showAddForm = isset($_GET['add']) && $_GET['add'] === '1';

$formMode = 'add';
$formValues = fate_plugins_registry_form_defaults();

if ($editId !== '') {
    $editEntry = fate_plugins_registry_entry_for_edit($editId);
    if ($editEntry === null) {
        header('Location: plugins.php', true, 302);
        exit;
    }
    $formMode = 'edit';
    $formValues = $editEntry;
    $showAddForm = true;
} elseif ($registerPrefill !== '') {
    foreach ($discovered as $candidate) {
        if ($candidate['suggested_id'] === $registerPrefill) {
            $formValues = fate_plugins_registry_form_defaults([
                'plugin_id' => $candidate['suggested_id'],
                'label' => $candidate['suggested_label'],
                'install_path' => $candidate['install_path_rel'],
                'public_href' => (string) ($candidate['suggested_public_href'] ?? ''),
                'admin_href' => (string) ($candidate['suggested_admin_href'] ?? ''),
            ]);
            $showAddForm = true;
            break;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $error = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $formKind = isset($_POST['form_kind']) && is_string($_POST['form_kind']) ? $_POST['form_kind'] : 'toggles';
        if ($formKind === 'registry') {
            $result = fate_plugins_save_registry_post($_POST);
            if (!$result['ok']) {
                $error = $result['error'] ?? '儲存失敗';
                $registryAction = isset($_POST['registry_action']) && is_string($_POST['registry_action']) ? $_POST['registry_action'] : 'add';
                if ($registryAction === 'edit') {
                    $formMode = 'edit';
                    $formValues = fate_plugins_registry_form_defaults([
                        'plugin_id' => $_POST['plugin_id'] ?? '',
                        'label' => $_POST['label'] ?? '',
                        'description' => $_POST['description'] ?? '',
                        'install_path' => $_POST['install_path'] ?? '',
                        'public_href' => $_POST['public_href'] ?? '',
                        'admin_href' => $_POST['admin_href'] ?? '',
                        'default_enabled' => !empty($_POST['default_enabled']),
                    ]);
                    $showAddForm = true;
                } else {
                    $formMode = 'add';
                    $formValues = fate_plugins_registry_form_defaults([
                        'plugin_id' => $_POST['plugin_id'] ?? '',
                        'label' => $_POST['label'] ?? '',
                        'description' => $_POST['description'] ?? '',
                        'install_path' => $_POST['install_path'] ?? '',
                        'public_href' => $_POST['public_href'] ?? '',
                        'admin_href' => $_POST['admin_href'] ?? '',
                        'default_enabled' => !empty($_POST['default_enabled']),
                    ]);
                    $showAddForm = true;
                }
            } else {
                header('Location: ' . ($result['redirect'] ?? 'plugins.php?registry_saved=1'), true, 302);
                exit;
            }
        } else {
            $result = fate_plugins_save_admin_post($_POST);
            if (!$result['ok']) {
                $error = $result['error'] ?? '儲存失敗';
            } else {
                header('Location: plugins.php?saved=1', true, 302);
                exit;
            }
        }
    }
    $rows = fate_plugins_admin_rows();
    $discovered = fate_plugins_discover_candidates();
}

$csrf = fate_admin_csrf_token();
$totalCount = count($rows);
$installedCount = count(array_filter($rows, static fn (array $r): bool => $r['installed']));
$enabledCount = count(array_filter($rows, static fn (array $r): bool => $r['enabled']));

fate_admin_layout_start(['page' => '外掛管理', 'active' => 'plugins', 'body_class' => 'admin-body--plugins']);
?>
        <header class="page-header">
            <h1 class="page-title">外掛管理</h1>
            <p class="sub">在此啟用或停用外掛，也可透過表單新增自訂外掛，無需手動編輯程式碼或 JSON 檔。</p>
        </header>

        <?php if ($saved): ?>
            <div class="msg ok">外掛開關已儲存。</div>
        <?php endif; ?>
        <?php if ($registrySaved): ?>
            <div class="msg ok">外掛清單已更新。</div>
        <?php endif; ?>
        <?php if ($error !== null): ?>
            <div class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <div class="plugin-summary card">
            <p class="plugin-summary__line">
                已登記 <strong><?= $totalCount ?></strong> 個外掛
                ｜已部署 <strong><?= $installedCount ?></strong>
                ｜啟用中 <strong><?= $enabledCount ?></strong>
            </p>
        </div>

        <?php if ($discovered !== []): ?>
            <section class="card plugin-discover">
                <h2 class="h2" style="margin-top:0;">偵測到未登記的外掛</h2>
                <p class="sub" style="margin-top:0;">下列模組已上傳至站台，但尚未加入管理清單。點「一鍵加入」即可帶入表單。</p>
                <ul class="plugin-discover__list">
                    <?php foreach ($discovered as $candidate): ?>
                        <li class="plugin-discover__item">
                            <div>
                                <strong><?= htmlspecialchars($candidate['suggested_label'], ENT_QUOTES, 'UTF-8') ?></strong>
                                <span class="plugin-discover__path"><code><?= htmlspecialchars($candidate['install_path_rel'], ENT_QUOTES, 'UTF-8') ?></code></span>
                            </div>
                            <a class="btn btn--primary btn--sm" href="plugins.php?register=<?= rawurlencode($candidate['suggested_id']) ?>#plugin-registry-form">一鍵加入</a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </section>
        <?php endif; ?>

        <?php if ($totalCount === 0): ?>
            <div class="card">
                <p class="sub" style="margin:0;">目前尚無外掛。請使用下方「新增外掛」表單登記模組。</p>
            </div>
        <?php else: ?>
        <form method="post" action="plugins.php" class="plugin-form">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="form_kind" value="toggles">

            <ul class="plugin-list">
                <?php foreach ($rows as $row): ?>
                    <li class="plugin-card card<?= $row['installed'] ? '' : ' plugin-card--missing' ?>">
                        <div class="plugin-card__main">
                            <div class="plugin-card__head">
                                <h2 class="plugin-card__title"><?= htmlspecialchars($row['label'], ENT_QUOTES, 'UTF-8') ?></h2>
                                <code class="plugin-card__id"><?= htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8') ?></code>
                                <?php if ($row['is_builtin']): ?>
                                    <span class="plugin-badge plugin-badge--builtin">內建</span>
                                <?php endif; ?>
                            </div>
                            <?php if ($row['description'] !== ''): ?>
                                <p class="plugin-card__desc"><?= htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8') ?></p>
                            <?php endif; ?>
                            <div class="plugin-card__meta">
                                <?php if ($row['installed']): ?>
                                    <span class="plugin-badge plugin-badge--ok">已部署</span>
                                    <?php if ($row['enabled']): ?>
                                        <span class="plugin-badge plugin-badge--on">啟用中</span>
                                    <?php else: ?>
                                        <span class="plugin-badge plugin-badge--off">已停用</span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="plugin-badge plugin-badge--missing">未部署</span>
                                <?php endif; ?>
                            </div>
                            <p class="plugin-card__path">檢查檔案：<code><?= htmlspecialchars($row['install_path_rel'], ENT_QUOTES, 'UTF-8') ?></code></p>
                        </div>
                        <div class="plugin-card__side">
                            <?php if ($row['installed']): ?>
                                <label class="plugin-toggle checkbox-label">
                                    <input type="checkbox" name="plugin_enabled[<?= htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8') ?>]" value="1"<?= $row['enabled'] ? ' checked' : '' ?>>
                                    <span>啟用此外掛</span>
                                </label>
                                <div class="plugin-card__links">
                                    <?php if ($row['public_href'] !== null && $row['public_href'] !== ''): ?>
                                        <a class="btn btn--ghost btn--sm" href="<?= htmlspecialchars($row['public_href'], ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer">前台頁面</a>
                                    <?php endif; ?>
                                    <?php if ($row['admin_href'] !== null && $row['admin_href'] !== ''): ?>
                                        <a class="btn btn--ghost btn--sm" href="<?= htmlspecialchars($row['admin_href'], ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer">外掛管理</a>
                                    <?php endif; ?>
                                    <?php if (!$row['is_builtin']): ?>
                                        <a class="btn btn--ghost btn--sm" href="plugins.php?edit=<?= rawurlencode($row['id']) ?>#plugin-registry-form">編輯設定</a>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <p class="plugin-card__hint">請確認已上傳 <code><?= htmlspecialchars($row['install_path_rel'], ENT_QUOTES, 'UTF-8') ?></code>，部署完成後此處會出現開關。</p>
                            <?php endif; ?>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ul>

            <div class="plugin-form__foot">
                <button type="submit" class="btn btn--primary">儲存開關設定</button>
            </div>
        </form>
        <?php endif; ?>

        <section class="card plugin-registry" id="plugin-registry-form">
            <div class="plugin-registry__head">
                <h2 class="h2" style="margin:0;"><?= $formMode === 'edit' ? '編輯外掛設定' : '新增外掛' ?></h2>
                <?php if (!$showAddForm && $formMode === 'add'): ?>
                    <a class="btn btn--ghost btn--sm" href="plugins.php?add=1#plugin-registry-form">展開表單</a>
                <?php elseif ($formMode === 'add'): ?>
                    <a class="btn btn--ghost btn--sm" href="plugins.php">收合</a>
                <?php else: ?>
                    <a class="btn btn--ghost btn--sm" href="plugins.php?add=1#plugin-registry-form">改為新增</a>
                <?php endif; ?>
            </div>

            <?php if ($showAddForm || $formMode === 'edit'): ?>
                <p class="sub">填寫下列欄位即可將外掛加入管理清單。識別碼儲存後不可修改；路徑請相對於站台根目錄（例如 <code>plugins/my_tool/bootstrap.php</code>）。</p>

                <form method="post" action="plugins.php#plugin-registry-form" class="plugin-registry-form">
                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="form_kind" value="registry">
                    <input type="hidden" name="registry_action" value="<?= $formMode === 'edit' ? 'edit' : 'add' ?>">

                    <div class="field-grid">
                        <label class="field">
                            <span class="field-label">識別碼 <em>*</em></span>
                            <input type="text" name="plugin_id" value="<?= htmlspecialchars((string) $formValues['plugin_id'], ENT_QUOTES, 'UTF-8') ?>" pattern="[a-z][a-z0-9_]{1,31}" maxlength="32" required<?= $formMode === 'edit' ? ' readonly' : '' ?> placeholder="例如 my_plugin">
                            <span class="field-hint">小寫英文開頭，2–32 字，建立後不可改。</span>
                        </label>
                        <label class="field">
                            <span class="field-label">顯示名稱 <em>*</em></span>
                            <input type="text" name="label" value="<?= htmlspecialchars((string) $formValues['label'], ENT_QUOTES, 'UTF-8') ?>" maxlength="40" required placeholder="例如 我的工具">
                        </label>
                        <label class="field field--full">
                            <span class="field-label">說明</span>
                            <textarea name="description" rows="2" maxlength="400" placeholder="簡述此外掛的用途（選填）"><?= htmlspecialchars((string) $formValues['description'], ENT_QUOTES, 'UTF-8') ?></textarea>
                        </label>
                        <label class="field field--full">
                            <span class="field-label">安裝檢查檔案 <em>*</em></span>
                            <input type="text" name="install_path" value="<?= htmlspecialchars((string) $formValues['install_path'], ENT_QUOTES, 'UTF-8') ?>" required placeholder="forum/bootstrap.php">
                            <span class="field-hint">系統會檢查此 .php 是否存在，以判斷「已部署／未部署」。</span>
                        </label>
                        <label class="field">
                            <span class="field-label">前台連結</span>
                            <input type="text" name="public_href" value="<?= htmlspecialchars((string) $formValues['public_href'], ENT_QUOTES, 'UTF-8') ?>" placeholder="../forum/index.php">
                        </label>
                        <label class="field">
                            <span class="field-label">管理連結</span>
                            <input type="text" name="admin_href" value="<?= htmlspecialchars((string) $formValues['admin_href'], ENT_QUOTES, 'UTF-8') ?>" placeholder="../forum/admin/index.php">
                        </label>
                        <label class="field field--check">
                            <input type="checkbox" name="default_enabled" value="1"<?= !empty($formValues['default_enabled']) ? ' checked' : '' ?>>
                            <span>新增後預設啟用</span>
                        </label>
                    </div>

                    <div class="field-actions">
                        <button type="submit" class="btn btn--primary"><?= $formMode === 'edit' ? '儲存設定' : '加入外掛清單' ?></button>
                        <?php if ($formMode === 'edit'): ?>
                            <a class="btn btn--ghost" href="plugins.php">取消</a>
                        <?php endif; ?>
                    </div>
                </form>

                <?php if ($formMode === 'edit'): ?>
                    <form method="post" action="plugins.php" class="plugin-registry-delete" onsubmit="return confirm('確定要從清單移除此自訂外掛？（不會刪除檔案）');">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="form_kind" value="registry">
                        <input type="hidden" name="registry_action" value="delete">
                        <input type="hidden" name="plugin_id" value="<?= htmlspecialchars((string) $formValues['plugin_id'], ENT_QUOTES, 'UTF-8') ?>">
                        <button type="submit" class="btn btn--danger btn--sm">移除外掛登記</button>
                    </form>
                <?php endif; ?>
            <?php else: ?>
                <p class="sub" style="margin:0;">已上傳外掛模組？點「展開表單」填寫名稱與路徑即可，無須編輯 <code>includes/fate_plugins.php</code>。</p>
            <?php endif; ?>
        </section>

        <div class="card plugin-help">
            <h2 class="h2" style="margin-top:0;">使用說明</h2>
            <ol class="plugin-help__steps">
                <li>將外掛資料夾上傳至站台（內建討論區為 <code>forum/</code>；自訂外掛建議放在 <code>plugins/名稱/</code> 並含 <code>bootstrap.php</code>）。</li>
                <li>若出現「偵測到未登記的外掛」，可直接一鍵加入；否則用下方表單手動填寫。</li>
                <li>確認狀態為「已部署」後，勾選「啟用此外掛」並儲存。</li>
            </ol>
            <p class="sub" style="margin-bottom:0;">開關狀態儲存於 <code>data/fate_plugins.json</code>；自訂外掛清單儲存於 <code>data/fate_plugins_registry.json</code>（皆可由本頁操作，無需手動改檔）。</p>
        </div>
<?php
fate_admin_layout_end();
