<?php

declare(strict_types=1);

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

$currentUser = myronRequireContentAccess();
$repository = myronContentRepository();
$qualityReportService = myronQualityReportService();
$csrfToken = myronCsrfToken();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $currentUser = myronRequireContentAccess(true);
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        $role = trim((string) ($_POST['role'] ?? ''));
        $caller = myronActionCallerContextForUser($currentUser);
        if ($action === 'assign-page-role') {
            myronPagesActionService()->assignRole($role, trim((string) ($_POST['page_id'] ?? '')), $caller);
            myronRedirectWithFlash(myronBuildAdminUrl('content.pages'), ucfirst($role) . ' page assigned.', 'success');
        }
        if ($action === 'clear-page-role') {
            myronPagesActionService()->clearRole($role, trim((string) ($_POST['page_id'] ?? '')), $caller);
            myronRedirectWithFlash(myronBuildAdminUrl('content.pages'), ucfirst($role) . ' page role cleared.', 'success');
        }
        throw new RuntimeException('Unknown page-role action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('content.pages'), $exception->getMessage(), 'error');
    }
}

$pages = $repository->listPagesForManager();
$pageRoleAssignments = myronPageRoleService()->assignments();

myronRenderAdminShellStart($currentUser, [
    'title' => 'Pages',
    'titleContext' => 'Content',
    'activeItem' => 'pages',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Pages'],
  ]); ?>
  <div class="mc-workspace__title-row mc-workspace__title-row--actions">
    <h1 class="mc-workspace__title">Pages</h1>
    <div class="mc-workspace__actions">
      <?php if (myronUserCanManageContent($currentUser) && myronUserCanAccessAdministration($currentUser)): ?>
      <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('administration.menus')) ?>">Manage Menus</a>
      <?php endif; ?>
      <?php if (myronUserCanManageContent($currentUser)): ?>
      <a class="sg-button sg-button--primary" href="<?= myronEscape(myronBuildAdminUrl('content.pageEditor', ['mode' => 'create'])) ?>">New Page</a>
      <?php endif; ?>
    </div>
  </div>
  <p class="mc-workspace__subtitle">Manage your site pages.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if (myronUserCanManageContent($currentUser)): ?>
    <section class="sg-section" aria-labelledby="page-role-heading">
      <h2 id="page-role-heading">Public page roles</h2>
      <p>Assign authored pages to the Home, Search, and Not-found request roles. Assigning a held role moves it without changing the page path or publication state.</p>
      <div class="mc-page-grid" role="group" aria-label="Public page roles">
        <?php foreach (MyronPageRoleService::ROLES as $role): ?>
        <?php $assignedPageId = (string) ($pageRoleAssignments[$role] ?? ''); ?>
        <form method="post" class="mc-page-grid__row">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="role" value="<?= myronEscape($role) ?>">
          <span class="mc-page-grid__cell"><strong><?= myronEscape(ucfirst($role)) ?></strong></span>
          <label class="mc-page-grid__cell">
            <span class="sg-sr-only">Page for <?= myronEscape($role) ?> role</span>
            <select class="sg-input" name="page_id" required>
              <option value="">Select a page</option>
              <?php foreach ($pages as $rolePage): ?>
              <option value="<?= myronEscape((string) $rolePage['id']) ?>" <?= $assignedPageId === (string) $rolePage['id'] ? 'selected' : '' ?>><?= myronEscape((string) $rolePage['title']) ?> (<?= myronEscape((string) $rolePage['path']) ?>)</option>
              <?php endforeach; ?>
            </select>
          </label>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions">
            <button class="sg-button sg-button--primary" type="submit" name="action" value="assign-page-role">Assign</button>
            <?php if ($assignedPageId !== ''): ?>
            <button class="sg-button sg-button--secondary" type="submit" name="action" value="clear-page-role" formnovalidate>Clear</button>
            <?php endif; ?>
          </span>
        </form>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endif; ?>
    <section class="sg-section">
      <div class="mc-page-grid mc-page-grid--pages" role="table" aria-label="Page manager" data-mc-sortable-grid>
        <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
          <span role="columnheader" data-mc-sort-key="page"><button class="mc-page-grid__sort" type="button">Page</button></span>
          <span role="columnheader">Markup</span>
          <span role="columnheader">Markdown</span>
          <span role="columnheader" data-mc-sort-key="path"><button class="mc-page-grid__sort" type="button">Path</button></span>
          <span role="columnheader" data-mc-sort-key="template"><button class="mc-page-grid__sort" type="button">Template</button></span>
          <span role="columnheader" data-mc-sort-key="version" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Version</button></span>
          <span role="columnheader" data-mc-sort-key="quality"><button class="mc-page-grid__sort" type="button">Quality</button></span>
          <span role="columnheader" data-mc-sort-key="state"><button class="mc-page-grid__sort" type="button">State</button></span>
          <span role="columnheader">Actions</span>
        </div>

        <?php foreach ($pages as $page): ?>
        <?php
          $depth = max(0, (int) ($page['depth'] ?? 0));
          $version = (int) ($page['manager_version_number'] ?? 0);
          $liveAvailable = (string) ($page['publication_state'] ?? '') === 'published';
          $markupDownloadable = $liveAvailable && $repository->isPageMarkupDownloadable($page);
          $markupDownloadUrl = rtrim(myronAdminBasePath(), '/') . '/api/v1/content/pages/' . rawurlencode((string) $page['id']) . '/markup';
          $markdownDownloadable = $markupDownloadable;
          $markdownDownloadUrl = rtrim(myronAdminBasePath(), '/') . '/api/v1/content/pages/' . rawurlencode((string) $page['id']) . '/markdown';
          $qualityReport = $qualityReportService->reportForPage((string) $page['id']);
          $qualityStatus = (string) ($qualityReport['status'] ?? 'ready');
          $depthClass = 'mc-page-grid__cell--depth-' . (string) min($depth, 6);
        ?>
        <div
          class="mc-page-grid__row"
          role="row"
          data-mc-filter-row
          data-sort-page="<?= myronEscape((string) $page['title']) ?>"
          data-sort-path="<?= myronEscape((string) $page['path']) ?>"
          data-sort-template="<?= myronEscape((string) $page['template_name']) ?>"
          data-sort-version="<?= myronEscape((string) $version) ?>"
          data-sort-quality="<?= myronEscape($qualityStatus) ?>"
          data-sort-state="<?= myronEscape((string) $page['publication_state']) ?>"
        >
          <span class="mc-page-grid__cell mc-page-grid__cell--name <?= myronEscape($depthClass) ?>" role="cell">
            <span class="mc-page-grid__name"><?= myronEscape((string) $page['title']) ?></span>
            <?php foreach ((array) ($page['roles'] ?? []) as $role): ?>
            <span class="sg-pill sg-pill--active"><?= myronEscape((string) $role) ?></span>
            <?php endforeach; ?>
          </span>
          <span class="mc-page-grid__cell mc-page-grid__cell--markup" role="cell">
            <?php if ($markupDownloadable): ?>
            <a class="mc-pages-list__markup-download" href="<?= myronEscape($markupDownloadUrl) ?>" aria-label="Download HTML markup" title="Download HTML markup">&#8595;</a>
            <?php else: ?>
            <button class="mc-pages-list__markup-download" type="button" disabled aria-label="Download HTML markup" title="Markup unavailable">&#8595;</button>
            <?php endif; ?>
          </span>
          <span class="mc-page-grid__cell mc-page-grid__cell--markdown" role="cell">
            <?php if ($markdownDownloadable): ?>
            <a class="mc-pages-list__markup-download" href="<?= myronEscape($markdownDownloadUrl) ?>" aria-label="Download Markdown" title="Download Markdown">&#8595;</a>
            <?php else: ?>
            <button class="mc-pages-list__markup-download" type="button" disabled aria-label="Download Markdown" title="Markdown unavailable">&#8595;</button>
            <?php endif; ?>
          </span>
          <span class="mc-page-grid__cell" role="cell"><code><?= myronEscape((string) $page['path']) ?></code></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) $page['template_name']) ?></span>
          <span class="mc-page-grid__cell" role="cell"><?= $version > 0 ? 'v' . myronEscape((string) $version) : '—' ?></span>
          <span class="mc-page-grid__cell" role="cell">
            <span class="sg-pill <?= $qualityStatus === 'block' ? '' : 'sg-pill--active' ?>"><?= myronEscape($qualityStatus) ?></span>
          </span>
          <span class="mc-page-grid__cell" role="cell">
            <span class="sg-pill <?= $liveAvailable ? 'sg-pill--active' : '' ?>"><?= myronEscape((string) $page['publication_state']) ?></span>
          </span>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
            <?php if (myronUserCanManageContent($currentUser)): ?>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('content.pageEditor')) ?>?page=<?= rawurlencode((string) $page['id']) ?>">Edit</a>
            <?php endif; ?>
            <?php if ($liveAvailable): ?>
            <a class="sg-button sg-button--primary" href="<?= myronEscape((string) $page['preview_url']) ?>" target="_blank" rel="noreferrer">View Live</a>
            <?php elseif (myronUserCanManageContent($currentUser)): ?>
            <span class="mc-page-grid__muted">Not live</span>
            <?php endif; ?>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
