<?php

declare(strict_types=1);

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

$currentUser = myronRequireAdministrationAccess();
$licenseRepository = myronLicenseRepository();
$auditRepository = myronLicenseAuditRepository();
$csrfToken = myronCsrfToken();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        if ($action === 'refresh-license') {
            if (!isset($_POST['license_plan'])) {
                $_POST['license_plan'] = $licenseRepository->currentSnapshot()->plan;
            }
            myronLicenseActivationService()->refreshFromInput(
                $_POST,
                myronAppUrl(),
                (string) ($currentUser['id'] ?? '')
            );
            myronRedirectWithFlash(myronBuildAdminUrl('administration.license'), 'License entitlement refreshed.', 'success');
        }
        if ($action === 'remove-license') {
            myronLicenseActivationService()->removeCurrentLicense(
                myronAppUrl(),
                (string) ($currentUser['id'] ?? ''),
                (string) ($_POST['confirm_remove_license_phrase'] ?? '')
            );
            myronRedirectWithFlash(myronBuildAdminUrl('administration.license'), 'License removed. Licensed features are no longer available on this site.', 'success');
        }

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

$state = $licenseRepository->current();
$snapshot = $licenseRepository->currentSnapshot();
$remediationState = $licenseRepository->currentRemediationState();
$auditEvents = $auditRepository->listRecent(10);
$paidModuleSurfaceAvailable = false;
if (function_exists('myronModulePresent')) {
    foreach (['commerce', 'funnels', 'lms', 'quizzes', 'content/vcards', 'content/personal_pages', 'devops'] as $moduleName) {
        if (myronModulePresent($moduleName)) {
            $paidModuleSurfaceAvailable = true;
            break;
        }
    }
}

myronRenderAdminShellStart($currentUser, [
    'title' => 'License',
    'titleContext' => 'Administration',
    'activeItem' => 'license',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'System', 'href' => myronBuildAdminUrl('administration.siteSetup')],
      ['label' => 'License'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">License</h1>
  </div>
  <p class="mc-workspace__subtitle">Core is free and unlicensed. Paid Module redemption lives in <a href="<?= myronEscape(myronBuildAdminUrl('administration.licenseManager')) ?>">License Manager</a>.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <h2 class="sg-section__title">Current Entitlement</h2>
      <dl class="sg-define-list">
        <dt>License Type</dt><dd><?= $snapshot->status === MyronLicenseStatus::UNREGISTERED ? 'Unlicensed Core' : 'Paid Module license' ?></dd>
        <dt>Status</dt><dd><?= myronEscape($snapshot->status) ?></dd>
        <dt>License Key</dt><dd><?= myronEscape((string) ($state['license_mask'] ?? 'Not activated')) ?></dd>
        <?php if ($paidModuleSurfaceAvailable || trim((string) ($state['deployment_key_mask'] ?? '')) !== '' || $snapshot->deploymentGroup !== ''): ?>
        <dt>Deployment Key</dt><dd><?= myronEscape((string) (($state['deployment_key_mask'] ?? '') ?: 'Not required')) ?></dd>
        <dt>Deployment Group</dt><dd><?= myronEscape($snapshot->deploymentGroup !== '' ? $snapshot->deploymentGroup : 'None') ?></dd>
        <?php endif; ?>
        <dt>Environment</dt><dd><?= myronEscape($snapshot->environment) ?></dd>
        <dt>Last Validation</dt><dd><?= myronEscape($snapshot->lastValidatedAt ?? 'Never') ?></dd>
        <dt>Renewal</dt><dd><?= myronEscape($snapshot->renewsAt ?? 'Not scheduled') ?></dd>
        <dt>Grace Ends</dt><dd><?= myronEscape($snapshot->graceEndsAt ?? 'Not in grace') ?></dd>
      </dl>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">License Remediation</h2>
      <dl class="sg-define-list">
        <dt>State</dt><dd><?= myronEscape($remediationState->customerLabel()) ?></dd>
        <dt>Public Content</dt><dd><?= !empty($remediationState->toCustomerArray()['publicContentReadable']) ? 'Readable where safe' : 'Requires license attention' ?></dd>
        <dt>Package Actions</dt><dd><?= $remediationState->packageActionsAllowed() ? 'Available' : 'Limited until license attention is resolved' ?></dd>
      </dl>
      <p class="sg-section__subtitle"><?= myronEscape($remediationState->customerMessage()) ?></p>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Capabilities</h2>
      <table class="mc-page-grid">
        <thead><tr><th>Capability</th><th>Entitled</th></tr></thead>
        <tbody>
        <?php foreach (MyronEntitlementGate::operatorCapabilityMap() as $capability => $description): ?>
        <tr>
          <td><code><?= myronEscape($capability) ?></code><br><?= myronEscape($description) ?></td>
          <td><?= !empty($snapshot->capabilities[$capability]) ? 'Yes' : 'No' ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Refresh Module License</h2>
      <form method="post" class="sg-form-grid" autocomplete="off">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="refresh-license">
        <input type="hidden" name="license_plan" value="core">
        <input type="hidden" name="api_version" value="v2">

        <?php if ($paidModuleSurfaceAvailable): ?>
        <label class="sg-field">
          <span class="sg-field__label">Environment</span>
          <select class="sg-field__control" name="license_environment" required>
            <?php foreach (['localhost' => 'Localhost', 'development' => 'Development', 'staging' => 'Staging', 'production' => 'Production'] as $value => $label): ?>
            <option value="<?= myronEscape($value) ?>"<?= $snapshot->environment === $value ? ' selected' : '' ?>><?= myronEscape($label) ?></option>
            <?php endforeach; ?>
          </select>
        </label>

        <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">
          <span class="sg-field__hint">Use this page to refresh an already redeemed Module license. Redeem new Module licenses in License Manager.</span>
        </label>

        <label class="sg-field sg-field--full">
          <span class="sg-field__label">Downgrade Backup Confirmation</span>
          <span class="sg-field__hint">Required only when a changed entitlement removes package access. Customer data is preserved, but export or back up the site before package remediation.</span>
          <span><input type="checkbox" name="confirm_downgrade_backup" value="1"> Site data has been exported or backed up.</span>
        </label>
        <?php endif; ?>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Refresh Entitlement</button>
        </div>
      </form>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Recent License Events</h2>
      <table class="mc-page-grid">
        <thead><tr><th>When</th><th>Event</th><th>Outcome</th><th>Reason</th><th>Environment</th></tr></thead>
        <tbody>
        <?php foreach ($auditEvents as $event): ?>
        <tr>
          <td><?= myronEscape((string) ($event['created_at'] ?? '')) ?></td>
          <td><?= myronEscape((string) ($event['event_type'] ?? '')) ?></td>
          <td><?= myronEscape((string) ($event['outcome'] ?? '')) ?></td>
          <td><?= myronEscape((string) ($event['reason_code'] ?? '')) ?></td>
          <td><?= myronEscape((string) ($event['environment'] ?? '')) ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if ($auditEvents === []): ?>
        <tr><td colspan="5">No license audit events have been recorded.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </section>

    <form method="post" class="sg-section" autocomplete="off" data-license-remove-form>
      <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
      <input type="hidden" name="action" value="remove-license">
      <input type="hidden" name="confirm_remove_license_phrase" value="" data-license-remove-phrase>
      <button type="submit" hidden data-license-remove-submit>Submit License Removal</button>
      <div class="sg-card__actions">
        <button class="sg-button sg-button--danger" type="button" data-license-remove-open<?= $state === null ? ' disabled' : '' ?>>Remove License</button>
      </div>
    </form>
  </div>
</div>
<div class="myron-dialog-backdrop" hidden aria-hidden="true" data-license-remove-backdrop></div>
<div class="myron-dialog myron-dialog--confirmation" id="license-remove-dialog" role="dialog" aria-modal="true" aria-hidden="true" hidden tabindex="-1" data-license-remove-dialog aria-labelledby="license-remove-title">
  <div class="myron-dialog__header">
    <div>
      <h2 class="sg-section__title" id="license-remove-title">Remove License</h2>
      <p class="sg-section__subtitle">You are about to remove your license from this site. You will no longer have access to licensed features after removal completes.</p>
    </div>
    <button class="myron-dialog__close" type="button" aria-label="Close license removal confirmation" data-license-remove-close>&times;</button>
  </div>
  <div class="myron-dialog__body">
    <p class="sg-field__help" data-license-remove-modal-status>Confirmation unlocks after the countdown.</p>
    <label class="sg-field">
      <span class="sg-field__label">Type <code><?= myronEscape(MyronLicenseActivationService::REMOVE_CONFIRMATION_PHRASE) ?></code></span>
      <input class="sg-field__control" type="text" autocomplete="off" spellcheck="false" disabled data-license-remove-confirmation>
    </label>
  </div>
  <div class="myron-dialog__actions">
    <button class="sg-button sg-button--secondary" type="button" data-license-remove-close>Cancel</button>
    <button class="sg-button sg-button--danger" type="button" disabled data-license-remove-confirm>Remove License</button>
  </div>
</div>
<script>
(() => {
  const removeForm = document.querySelector('[data-license-remove-form]');
  const removeSubmit = document.querySelector('[data-license-remove-submit]');
  const removeOpen = document.querySelector('[data-license-remove-open]');
  const removePhrase = document.querySelector('[data-license-remove-phrase]');
  const removeDialog = document.querySelector('[data-license-remove-dialog]');
  const removeBackdrop = document.querySelector('[data-license-remove-backdrop]');
  const removeConfirm = document.querySelector('[data-license-remove-confirm]');
  const removeConfirmation = document.querySelector('[data-license-remove-confirmation]');
  const removeModalStatus = document.querySelector('[data-license-remove-modal-status]');
  const removeDelaySeconds = 5;
  const removeConfirmationPhrase = '<?= myronEscape(MyronLicenseActivationService::REMOVE_CONFIRMATION_PHRASE) ?>';
  let removeCountdown = null;

  const closeRemoveDialog = () => {
    window.clearInterval(removeCountdown);
    if (removeDialog) {
      removeDialog.hidden = true;
      removeDialog.setAttribute('aria-hidden', 'true');
    }
    if (removeBackdrop) {
      removeBackdrop.hidden = true;
      removeBackdrop.setAttribute('aria-hidden', 'true');
    }
  };

  const updateRemoveConfirm = () => {
    if (!removeConfirmation || !removeConfirm) {
      return;
    }
    removeConfirm.disabled = removeConfirmation.disabled
      || removeConfirmation.value.trim() !== removeConfirmationPhrase;
  };

  const openRemoveDialog = () => {
    if (!removeDialog || !removeBackdrop || !removeConfirmation || !removeConfirm || !removeModalStatus) {
      return;
    }
    window.clearInterval(removeCountdown);
    let remaining = removeDelaySeconds;
    removeDialog.hidden = false;
    removeDialog.setAttribute('aria-hidden', 'false');
    removeBackdrop.hidden = false;
    removeBackdrop.setAttribute('aria-hidden', 'false');
    removeConfirmation.value = '';
    removeConfirmation.disabled = true;
    removeConfirm.disabled = true;
    removeModalStatus.textContent = 'Confirmation unlocks in ' + String(remaining) + ' seconds.';
    removeDialog.focus();
    removeCountdown = window.setInterval(() => {
      remaining -= 1;
      if (remaining > 0) {
        removeModalStatus.textContent = 'Confirmation unlocks in ' + String(remaining) + ' seconds.';
        return;
      }
      window.clearInterval(removeCountdown);
      removeConfirmation.disabled = false;
      removeConfirmation.value = '';
      removeModalStatus.textContent = 'Type the exact phrase to remove this license.';
      removeConfirmation.focus();
      updateRemoveConfirm();
    }, 1000);
  };

  if (removeOpen) {
    removeOpen.addEventListener('click', openRemoveDialog);
  }
  document.querySelectorAll('[data-license-remove-close]').forEach((button) => {
    button.addEventListener('click', closeRemoveDialog);
  });
  if (removeBackdrop) {
    removeBackdrop.addEventListener('click', closeRemoveDialog);
  }
  if (removeConfirmation) {
    removeConfirmation.addEventListener('input', updateRemoveConfirm);
  }
  if (removeConfirm) {
    removeConfirm.addEventListener('click', () => {
      if (removeConfirm.disabled || !removeForm || !removePhrase) {
        return;
      }
      removePhrase.value = removeConfirmationPhrase;
      closeRemoveDialog();
      if (typeof removeForm.requestSubmit === 'function' && removeSubmit) {
        removeForm.requestSubmit(removeSubmit);
        return;
      }
      if (removeSubmit) {
        removeSubmit.click();
        return;
      }
      removeForm.submit();
    });
  }
})();
</script>
<?php myronRenderAdminShellEnd(); ?>
