<?php

declare(strict_types=1);

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

$currentUser = myronRequireAdministrationAccess();
$service = myronModuleLicenseManagerService();
$auditRepository = myronLicenseAuditRepository();
$catalogClient = new MyronMarketplaceCatalogClient();
$csrfToken = myronCsrfToken();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        if (!myronUserHoldsScope($currentUser, MyronApiScopes::ADMINISTRATION_WRITE)) {
            throw new RuntimeException('Your current access does not permit Module license redemption.');
        }

        $action = trim((string) ($_POST['action'] ?? ''));
        if ($action === 'redeem-key') {
            $result = $service->redeemKey((string) ($_POST['license_key'] ?? ''), (string) ($currentUser['id'] ?? ''));
            myronRedirectWithFlash(
                myronBuildAdminUrl('administration.licenseManager', ['tab' => 'installed']),
                $result['operatorMessage'],
                ($result['outcome'] ?? '') === 'activated' ? 'success' : 'error'
            );
        }
        if ($action === 'install-module-package') {
            $result = $service->installPackageForSku((string) ($_POST['sku_id'] ?? ''), (string) ($currentUser['id'] ?? ''));
            myronRedirectWithFlash(
                myronBuildAdminUrl('administration.licenseManager', ['tab' => 'installed']),
                $result['operatorMessage'],
                in_array((string) ($result['outcome'] ?? ''), ['installed', 'upgraded', 'already_current'], true) ? 'success' : 'error'
            );
        }
        if ($action === 'redeem-marketplace-token') {
            $result = $service->redeemActivationToken((string) ($_POST['activation_token'] ?? ''), (string) ($currentUser['id'] ?? ''));
            myronRedirectWithFlash(
                myronBuildAdminUrl('administration.licenseManager', ['tab' => 'installed']),
                $result['operatorMessage'],
                ($result['outcome'] ?? '') === 'activated' ? 'success' : 'error'
            );
        }

        throw new RuntimeException('Unknown Modules action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('administration.licenseManager', ['tab' => 'redeem']), $exception->getMessage(), 'error');
    }
}

$moduleState = $service->listModules();
$modules = is_array($moduleState['modules'] ?? null) ? $moduleState['modules'] : [];
$redemptionEvents = $auditRepository->listRecentByEventPrefix('module_redeem.', 10);
$activationToken = trim((string) ($_GET['activation_token'] ?? $_GET['marketplace_activation_token'] ?? ''));
$requestedTab = strtolower(trim((string) ($_GET['tab'] ?? '')));
$tabs = [
    'browse' => 'Browse',
    'installed' => 'Installed',
    'redeem' => 'Redeem',
];
$activeTab = array_key_exists($requestedTab, $tabs) ? $requestedTab : ($modules === [] ? 'browse' : 'installed');
if ($activationToken !== '') {
    $activeTab = 'redeem';
}
$coreVersion = ltrim(MyronReleaseMetadata::VERSION, 'vV');
$catalogState = $catalogClient->list([
    'compatibility' => $coreVersion,
    'type' => 'module-bundle',
]);
$catalogItems = is_array($catalogState['items'] ?? null) ? $catalogState['items'] : [];
$returnUrl = myronBuildAbsoluteAdminUrl('administration.licenseManager');
$moduleStatusPillClass = static function (string $status): string {
    return in_array(strtolower(trim($status)), ['active', 'installed', 'ok'], true) ? 'sg-pill sg-pill--active' : 'sg-pill sg-pill--secondary';
};
$moduleRenewalLabel = static function (mixed $value): string {
    $label = trim((string) $value);
    return $label !== '' ? $label : 'No renewal';
};

myronRenderAdminShellStart($currentUser, [
    'title' => 'Modules',
    'titleContext' => 'Administration',
    'activeItem' => 'license-manager',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'System', 'href' => myronBuildAdminUrl('administration.siteSetup')],
      ['label' => 'Modules'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Modules</h1>
  </div>
  <p class="mc-workspace__subtitle">Core runs without paid Modules. Use this surface only when you want to add, redeem, or review first-party Module entitlements.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <div class="myron-tabs">
        <div class="myron-tab-list" role="tablist" aria-label="Modules views">
          <?php foreach ($tabs as $tabKey => $tabLabel): ?>
          <?php $isActive = $tabKey === $activeTab; ?>
          <a
            class="myron-tab"
            id="modules-tab-<?= myronEscape($tabKey) ?>"
            href="<?= myronEscape(myronBuildAdminUrl('administration.licenseManager', ['tab' => $tabKey]) . '#modules-panel-' . $tabKey) ?>"
            role="tab"
            aria-selected="<?= $isActive ? 'true' : 'false' ?>"
            aria-controls="modules-panel-<?= myronEscape($tabKey) ?>"
            tabindex="<?= $isActive ? '0' : '-1' ?>"
          ><?= myronEscape($tabLabel) ?></a>
          <?php endforeach; ?>
        </div>

        <section
          class="myron-tab-panel"
          id="modules-panel-browse"
          role="tabpanel"
          aria-labelledby="modules-tab-browse"
          <?= $activeTab === 'browse' ? '' : ' hidden' ?>
        >
          <div class="sg-section__header">
            <div>
              <h2 class="sg-section__title">Browse Marketplace Modules</h2>
              <p class="sg-section__subtitle">Catalog results are read-only discovery. Activation remains governed by the license service.</p>
            </div>
          </div>

          <?php if (($catalogState['ok'] ?? false) !== true): ?>
          <div class="sg-empty-state">
            <p class="sg-empty-state__title">Marketplace catalog is temporarily unavailable.</p>
            <p class="sg-empty-state__text">Your Core site is still usable. Installed Modules and manual redemption remain available; try Browse again later or redeem a purchased key from the Redeem tab.</p>
          </div>
          <?php elseif ($catalogItems === []): ?>
          <div class="sg-empty-state">
            <p class="sg-empty-state__title">No compatible Modules are listed yet.</p>
            <p class="sg-empty-state__text">This Core install has no paid Modules to show from the catalog. If you already have a key, use Redeem.</p>
          </div>
          <?php else: ?>
          <div class="sg-card-grid">
            <?php foreach ($catalogItems as $item): ?>
            <?php
              $skuId = (string) ($item['skuId'] ?? '');
              $monthly = is_array($item['prices']['monthly'] ?? null) ? $item['prices']['monthly'] : [];
              $annual = is_array($item['prices']['annual'] ?? null) ? $item['prices']['annual'] : [];
              $amountCents = (int) ($monthly['amountCents'] ?? 0);
              $priceLabel = $amountCents > 0 ? '$' . number_format($amountCents / 100, 2) . '/mo' : 'Marketplace pricing';
              $buyUrl = $catalogClient->checkoutUrl($skuId, $returnUrl, 'monthly');
              $capabilities = is_array($item['capabilities'] ?? null) ? array_slice($item['capabilities'], 0, 4) : [];
            ?>
            <article class="sg-card">
              <div class="sg-card__body">
                <p class="sg-card__eyebrow"><?= myronEscape((string) ($item['category'] ?? 'Module')) ?></p>
                <h3 class="sg-card__title"><?= myronEscape((string) ($item['displayName'] ?? $skuId)) ?></h3>
                <p class="sg-card__text"><?= myronEscape((string) ($item['summary'] ?? '')) ?></p>
                <p class="sg-card__meta"><?= myronEscape($priceLabel) ?><?= $annual !== [] ? ' - Annual available' : '' ?></p>
                <?php if ($capabilities !== []): ?>
                <ul class="sg-list">
                  <?php foreach ($capabilities as $capability): ?>
                  <li><?= myronEscape((string) $capability) ?></li>
                  <?php endforeach; ?>
                </ul>
                <?php endif; ?>
              </div>
              <div class="sg-card__actions">
                <?php if ($buyUrl !== ''): ?>
                <a class="sg-button sg-button--primary" href="<?= myronEscape($buyUrl) ?>">Buy</a>
                <?php else: ?>
                <span class="sg-button sg-button--secondary" aria-disabled="true">Unavailable</span>
                <?php endif; ?>
              </div>
            </article>
            <?php endforeach; ?>
          </div>
          <?php endif; ?>
        </section>

        <section
          class="myron-tab-panel"
          id="modules-panel-installed"
          role="tabpanel"
          aria-labelledby="modules-tab-installed"
          <?= $activeTab === 'installed' ? '' : ' hidden' ?>
        >
          <h2 class="sg-section__title">Installed Modules</h2>
          <?php if ($modules === []): ?>
          <div class="sg-empty-state">
            <p class="sg-empty-state__title">You don't have any paid Modules installed yet.</p>
            <p class="sg-empty-state__text">This is the expected bare-Core state. Paid Module workspaces appear after a Module license is redeemed and its signed package is installed.</p>
          </div>
          <?php else: ?>
          <div class="myron-data-table-wrapper mc-license-manager-table-wrap" data-license-manager-installed-table>
            <table class="myron-data-table mc-license-manager-table" aria-label="Installed Module entitlements">
              <colgroup>
                <col class="mc-license-manager-table__col-module">
                <col class="mc-license-manager-table__col-package">
                <col class="mc-license-manager-table__col-entitlement">
                <col class="mc-license-manager-table__col-package-state">
                <col class="mc-license-manager-table__col-renews">
                <col class="mc-license-manager-table__col-actions">
              </colgroup>
              <thead>
                <tr>
                  <th scope="col" class="mc-license-manager-table__module-cell">Module</th>
                  <th scope="col" class="mc-license-manager-table__package-cell">Package</th>
                  <th scope="col" class="mc-license-manager-table__status-cell">Entitlement</th>
                  <th scope="col" class="mc-license-manager-table__status-cell">Package State</th>
                  <th scope="col" class="mc-license-manager-table__renews-cell">Renews</th>
                  <th scope="col" class="mc-license-manager-table__actions">Actions</th>
                </tr>
              </thead>
              <tbody>
              <?php foreach ($modules as $module): ?>
              <?php
                $moduleName = (string) ($module['displayName'] ?? $module['slug'] ?? 'Module');
                $moduleSlug = (string) ($module['slug'] ?? '');
                $skuId = (string) ($module['skuId'] ?? '');
                $packageName = (string) ($module['package'] ?? $skuId);
                $entitlementStatus = (string) ($module['status'] ?? '');
                $packageStatus = (string) ($module['packageStatus'] ?? 'pending');
                $packageStatusLabel = $packageStatus === 'update_available' ? 'Update available' : $packageStatus;
                $installedVersion = (string) ($module['installedVersion'] ?? '');
                $latestVersion = (string) ($module['latestVersion'] ?? '');
                $updateAvailable = !empty($module['updateAvailable']);
              ?>
              <tr>
                <td class="mc-license-manager-table__module-cell">
                  <span class="mc-license-manager-table__primary"><?= myronEscape($moduleName) ?></span>
                  <?php if ($moduleSlug !== ''): ?>
                  <span class="mc-license-manager-table__secondary"><?= myronEscape($moduleSlug) ?></span>
                  <?php endif; ?>
                </td>
                <td class="mc-license-manager-table__package-cell">
                  <code class="mc-license-manager-table__code"><?= myronEscape($packageName) ?></code>
                  <?php if ($installedVersion !== ''): ?><span class="mc-license-manager-table__secondary">Installed <?= myronEscape($installedVersion) ?></span><?php endif; ?>
                  <?php if ($latestVersion !== ''): ?><span class="mc-license-manager-table__secondary">Latest <?= myronEscape($latestVersion) ?></span><?php endif; ?>
                </td>
                <td class="mc-license-manager-table__status-cell"><span class="<?= myronEscape($moduleStatusPillClass($entitlementStatus)) ?>"><?= myronEscape($entitlementStatus !== '' ? $entitlementStatus : 'unknown') ?></span></td>
                <td class="mc-license-manager-table__status-cell"><span class="<?= myronEscape($moduleStatusPillClass($packageStatus)) ?>"><?= myronEscape($packageStatusLabel) ?></span></td>
                <td class="mc-license-manager-table__muted mc-license-manager-table__renews-cell"><?= myronEscape($moduleRenewalLabel($module['renewsAt'] ?? '')) ?></td>
                <td class="mc-license-manager-table__actions">
                  <?php if ($packageStatus !== 'installed' || $updateAvailable): ?>
                  <form method="post" class="sg-inline-form">
                    <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
                    <input type="hidden" name="action" value="install-module-package">
                    <input type="hidden" name="sku_id" value="<?= myronEscape($skuId) ?>">
                    <button class="sg-button sg-button--secondary" type="submit"><?= $updateAvailable ? 'Update Package' : 'Install Package' ?></button>
                  </form>
                  <?php else: ?>
                  <span class="mc-license-manager-table__action-state">Installed</span>
                  <?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          <?php endif; ?>

          <h2 class="sg-section__title">Recent Redemption Events</h2>
          <div class="myron-data-table-wrapper mc-license-manager-table-wrap" data-license-manager-redemption-events-table>
            <table class="myron-data-table mc-license-manager-events-table" aria-label="Recent Module redemption events">
              <colgroup>
                <col class="mc-license-manager-events-table__col-when">
                <col class="mc-license-manager-events-table__col-key">
                <col class="mc-license-manager-events-table__col-outcome">
                <col class="mc-license-manager-events-table__col-reason">
              </colgroup>
              <thead><tr><th scope="col">When</th><th scope="col">Key</th><th scope="col">Outcome</th><th scope="col">Reason</th></tr></thead>
              <tbody>
              <?php foreach ($redemptionEvents as $event): ?>
              <?php
                $detail = json_decode((string) ($event['detail_json'] ?? '{}'), true);
                $keyMask = (string) (is_array($detail) ? ($detail['keyMask'] ?? $detail['keyPrefix'] ?? '') : '');
                $eventOutcome = (string) ($event['outcome'] ?? '');
              ?>
              <tr>
                <td class="mc-license-manager-table__muted"><?= myronEscape((string) ($event['created_at'] ?? '')) ?></td>
                <td><code class="mc-license-manager-table__code"><?= myronEscape($keyMask !== '' ? $keyMask : 'not recorded') ?></code></td>
                <td><span class="<?= myronEscape($moduleStatusPillClass($eventOutcome)) ?>"><?= myronEscape($eventOutcome !== '' ? $eventOutcome : 'unknown') ?></span></td>
                <td class="mc-license-manager-table__reason"><?= myronEscape((string) ($event['reason_code'] ?? '')) ?></td>
              </tr>
              <?php endforeach; ?>
              <?php if ($redemptionEvents === []): ?>
              <tr><td colspan="4" class="mc-license-manager-table__empty">No redemption attempts on record.</td></tr>
              <?php endif; ?>
              </tbody>
            </table>
          </div>
        </section>

        <section
          class="myron-tab-panel"
          id="modules-panel-redeem"
          role="tabpanel"
          aria-labelledby="modules-tab-redeem"
          <?= $activeTab === 'redeem' ? '' : ' hidden' ?>
        >
          <h2 class="sg-section__title">Redeem a Module License</h2>
          <?php if ($activationToken !== ''): ?>
          <form method="post" class="sg-form-grid" autocomplete="off">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="action" value="redeem-marketplace-token">
            <input type="hidden" name="activation_token" value="<?= myronEscape($activationToken) ?>">
            <div class="sg-field sg-field--full">
              <span class="sg-field__label">Marketplace Activation</span>
              <span class="sg-field__hint">A marketplace activation handoff is ready. Confirm to redeem it on this site.</span>
            </div>
            <div class="sg-card__actions">
              <button class="sg-button sg-button--primary" type="submit">Confirm Activation</button>
            </div>
          </form>
          <?php endif; ?>
          <form method="post" class="sg-form-grid" autocomplete="off">
            <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
            <input type="hidden" name="action" value="redeem-key">

            <label class="sg-field sg-field--full">
              <span class="sg-field__label">License Key</span>
              <input class="sg-field__control" type="password" name="license_key" required value="" autocomplete="off" placeholder="xxxx-xxxx-xxxx-xxxx-xxxx">
              <span class="sg-field__hint">Already purchased? Paste your license key here. Third-party extension keys are not redeemed here; use the <a href="<?= myronEscape(myronBuildAdminUrl('extensions.register')) ?>">Extensions admin</a>.</span>
            </label>

            <div class="sg-card__actions">
              <button class="sg-button sg-button--primary" type="submit">Redeem</button>
            </div>
          </form>
          <p class="sg-section__subtitle">Core does not require a license. Redeem paid Module licenses here when you want to add module work surfaces to this installation.</p>
        </section>
      </div>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
