<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';

$currentUser = myronRequireAdministrationAccess();
$csrfToken = myronCsrfToken();
$repository = myronExtensionScopeGrantRepository();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $vendor = trim((string) ($_POST['vendor'] ?? ''));
        $operation = trim((string) ($_POST['operation'] ?? ''));

        if ($operation === 'enable-extension') {
            $repository->setEnabled($vendor, true);
            myronRedirectWithFlash(myronBuildAdminUrl('extensions.installed'), 'Extension enabled.', 'success');
        }
        if ($operation === 'disable-extension') {
            $repository->setEnabled($vendor, false);
            myronRedirectWithFlash(myronBuildAdminUrl('extensions.installed'), 'Extension disabled.', 'success');
        }
        if ($operation === 'revoke-scope') {
            $repository->revokeScope($vendor, trim((string) ($_POST['scope'] ?? '')));
            myronRedirectWithFlash(myronBuildAdminUrl('extensions.installed'), 'Extension scope revoked.', 'success');
        }

        throw new RuntimeException('Unknown extension action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('extensions.installed'), $exception->getMessage(), 'error');
    }
}

$extensions = myronExtensionLoader()->statuses();

myronRenderAdminShellStart($currentUser, [
    'title' => 'Installed Extensions',
    'titleContext' => 'Extensions',
    'activeItem' => 'extensions-installed',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Extensions', 'href' => myronBuildAdminUrl('extensions.register')],
      ['label' => 'Installed Extensions'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Installed Extensions</h1>
  </div>
  <p class="mc-workspace__subtitle">Review registered extensions, granted scopes, and load health.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <h2 class="sg-section__title">Extensions</h2>
      <table class="mc-page-grid">
        <thead><tr><th>Vendor</th><th>Name</th><th>Status</th><th>Scopes</th><th>Load health</th><th>Actions</th></tr></thead>
        <tbody>
        <?php foreach ($extensions as $extension): ?>
        <?php $vendor = (string) ($extension['vendor'] ?? ''); $scopeList = (array) ($extension['grantedScopes'] ?? []); ?>
        <tr>
          <td><code><?= myronEscape($vendor) ?></code></td>
          <td><?= myronEscape((string) ($extension['name'] ?? '')) ?><br><small><?= myronEscape((string) ($extension['version'] ?? '')) ?></small></td>
          <td><span class="sg-pill <?= !empty($extension['enabled']) ? 'sg-pill--active' : '' ?>"><?= !empty($extension['enabled']) ? 'Enabled' : 'Disabled' ?></span></td>
          <td>
            <?php foreach ($scopeList as $scope): ?>
            <form method="post" action="<?= myronEscape(myronBuildAdminUrl('extensions.installed')) ?>" style="display:inline">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="operation" value="revoke-scope">
              <input type="hidden" name="vendor" value="<?= myronEscape($vendor) ?>">
              <input type="hidden" name="scope" value="<?= myronEscape((string) $scope) ?>">
              <button class="sg-button sg-button--secondary" type="submit"><?= myronEscape((string) $scope) ?> x</button>
            </form>
            <?php endforeach; ?>
            <?php if ($scopeList === []): ?>No scopes<?php endif; ?>
          </td>
          <td>
            <?php if (empty($extension['directoryExists'])): ?><span class="sg-pill">Directory missing</span><?php endif; ?>
            <?php if (!empty($extension['loaded'])): ?><span class="sg-pill sg-pill--active">Loaded</span><?php else: ?><span class="sg-pill">Not loaded</span><?php endif; ?>
            <?php if ((string) ($extension['lastError'] ?? '') !== ''): ?><br><small><?= myronEscape((string) $extension['lastError']) ?></small><?php endif; ?>
          </td>
          <td>
            <form method="post" action="<?= myronEscape(myronBuildAdminUrl('extensions.installed')) ?>">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="vendor" value="<?= myronEscape($vendor) ?>">
              <?php if (!empty($extension['enabled'])): ?>
              <button class="sg-button sg-button--danger" name="operation" value="disable-extension" type="submit">Disable</button>
              <?php else: ?>
              <button class="sg-button sg-button--primary" name="operation" value="enable-extension" type="submit">Enable</button>
              <?php endif; ?>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if ($extensions === []): ?><tr><td colspan="6">No extensions have been registered.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
