<?php

declare(strict_types=1);

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

$currentUser = myronRequireAdministrationAccess();
$csrfToken = myronCsrfToken();
$repository = myronExtensionScopeGrantRepository();
$scopes = MyronApiScopes::ALL_BASE;

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $vendor = trim((string) ($_POST['vendor'] ?? ''));
        if (!preg_match('/^[a-z][a-z0-9_]*$/', $vendor)) {
            throw new InvalidArgumentException('Vendor must be snake_case.');
        }

        $grantedScopes = [];
        foreach ((array) ($_POST['required_scopes'] ?? []) as $scope) {
            $grantedScopes[] = (string) $scope;
        }

        $repository->register(
            $vendor,
            trim((string) ($_POST['name'] ?? '')),
            trim((string) ($_POST['version'] ?? '')),
            $grantedScopes
        );
        myronRedirectWithFlash(myronBuildAdminUrl('extensions.register', ['vendor' => $vendor]), 'Extension registered.', 'success');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('extensions.register'), $exception->getMessage(), 'error');
    }
}

$statusVendor = trim((string) ($_GET['vendor'] ?? ''));
$statuses = myronExtensionLoader()->statuses();
$status = $statusVendor !== '' && isset($statuses[$statusVendor]) ? $statuses[$statusVendor] : null;

myronRenderAdminShellStart($currentUser, [
    'title' => 'Register Extension',
    'titleContext' => 'Extensions',
    'activeItem' => 'extensions-register',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Extensions', 'href' => myronBuildAdminUrl('extensions.register')],
      ['label' => 'Register Extension'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Register Extension</h1>
  </div>
  <p class="mc-workspace__subtitle">Grant scopes for a locally installed extension.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <h2 class="sg-section__title">Extension Grant</h2>
      <form class="sg-form-grid" method="post" action="<?= myronEscape(myronBuildAdminUrl('extensions.register')) ?>">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <label class="sg-field"><span class="sg-field__label">Vendor</span>
          <input class="sg-field__control" type="text" name="vendor" pattern="[a-z][a-z0-9_]*" placeholder="myron_sample" required>
        </label>
        <label class="sg-field"><span class="sg-field__label">Name</span>
          <input class="sg-field__control" type="text" name="name" required>
        </label>
        <label class="sg-field"><span class="sg-field__label">Version</span>
          <input class="sg-field__control" type="text" name="version" placeholder="0.1.0" required>
        </label>
        <fieldset class="sg-field">
          <legend class="sg-field__label">Granted Scopes</legend>
          <?php foreach ($scopes as $scope): ?>
          <label><input type="checkbox" name="required_scopes[]" value="<?= myronEscape($scope) ?>"> <?= myronEscape($scope) ?></label>
          <?php endforeach; ?>
        </fieldset>
        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Register Extension</button>
        </div>
      </form>
    </section>

    <?php if (is_array($status)): ?>
    <section class="sg-section sg-section--callout">
      <h2 class="sg-section__title">Load Status</h2>
      <dl class="sg-define-list">
        <dt>Vendor</dt><dd><code><?= myronEscape((string) $status['vendor']) ?></code></dd>
        <dt>Directory</dt><dd><?= !empty($status['directoryExists']) ? 'Found' : 'Missing' ?></dd>
        <dt>Manifest</dt><dd><?= !empty($status['manifestFound']) ? 'Found' : 'Missing' ?></dd>
        <dt>State</dt><dd><?= !empty($status['loaded']) ? 'Loaded' : 'Not loaded' ?></dd>
        <?php if ((string) ($status['lastError'] ?? '') !== ''): ?><dt>Last error</dt><dd><?= myronEscape((string) $status['lastError']) ?></dd><?php endif; ?>
      </dl>
    </section>
    <?php endif; ?>

    <section class="sg-section">
      <h2 class="sg-section__title">Marketplace Browse</h2>
      <p>Install signed third-party Extension packages before registering scope grants.</p>
      <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('extensions.marketplace')) ?>">Browse Marketplace</a>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
