<?php

declare(strict_types=1);

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

$currentUser = myronRequireContentAccess();
$repository = myronContentRepository();
$csrfToken = myronCsrfToken();
$manageId = trim((string) ($_GET['manage'] ?? ''));

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $currentUser = myronRequireContentAccess(true);
    $postedCategoryId = trim((string) ($_POST['category_id'] ?? ''));

    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));

        if ($action === 'create-category') {
            $categoryId = $repository->createPageCategory(
                trim((string) ($_POST['title'] ?? '')),
                trim((string) ($_POST['slug'] ?? '')),
                trim((string) ($_POST['description'] ?? ''))
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.categories', ['manage' => $categoryId]),
                'Category created.',
                'success'
            );
        }

        if ($action === 'update-category') {
            $repository->updatePageCategory(
                $postedCategoryId,
                trim((string) ($_POST['title'] ?? '')),
                trim((string) ($_POST['slug'] ?? '')),
                trim((string) ($_POST['description'] ?? '')),
                isset($_POST['is_active']) && (string) $_POST['is_active'] === '1'
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.categories', ['manage' => $postedCategoryId]),
                'Category saved.',
                'success'
            );
        }

        if ($action === 'archive-category') {
            $repository->setPageCategoryActive($postedCategoryId, false);
            myronRedirectWithFlash(myronBuildAdminUrl('content.categories'), 'Category archived.', 'success');
        }

        if ($action === 'reactivate-category') {
            $repository->setPageCategoryActive($postedCategoryId, true);
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.categories', ['manage' => $postedCategoryId]),
                'Category reactivated.',
                'success'
            );
        }

        throw new RuntimeException('Unknown category manager action.');
    } catch (Throwable $exception) {
        $query = $postedCategoryId !== '' ? ['manage' => $postedCategoryId] : [];
        myronRedirectWithFlash(myronBuildAdminUrl('content.categories', $query), $exception->getMessage(), 'error');
    }
}

$canManageContent = myronUserCanManageContent($currentUser);
$categories = $repository->listPageCategoriesWithUsage(false);
$managedCategory = $manageId !== '' ? $repository->getPageCategory($manageId) : null;

myronRenderAdminShellStart($currentUser, [
    'title' => 'Categories',
    'titleContext' => 'Content',
    'activeItem' => 'content-categories',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Content Studio', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Categories'],
  ]); ?>
  <div class="mc-workspace__title-row mc-workspace__title-row--actions">
    <h1 class="mc-workspace__title">Categories</h1>
    <div class="mc-workspace__actions">
      <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('content.pages')) ?>">Back to Pages</a>
    </div>
  </div>
  <p class="mc-workspace__subtitle">Manage the categories available to blog and editorial pages.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if ($manageId !== '' && !is_array($managedCategory)): ?>
    <div class="sg-status sg-status--error" role="status">The selected category could not be found.</div>
    <?php endif; ?>

    <?php if ($canManageContent): ?>
    <section class="sg-section">
      <h2 class="sg-section__title">Create Category</h2>
      <form method="post" class="mc-admin-form">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="create-category">
        <section class="mc-admin-form__section" aria-label="Category details">
          <div class="mc-admin-form__grid">
            <label class="sg-field">
              <span class="sg-field__label">Title</span>
              <input class="sg-field__control" type="text" name="title" required maxlength="255">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Slug</span>
              <input class="sg-field__control" type="text" name="slug" maxlength="160">
              <span class="sg-field__hint">Leave blank to generate from the title.</span>
            </label>
            <label class="sg-field mc-admin-form__span-full">
              <span class="sg-field__label">Description</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="3" data-mc-richtext="true"></textarea>
            </label>
          </div>
        </section>
        <div class="mc-admin-form__actions">
          <button class="sg-button sg-button--primary" type="submit">Create Category</button>
        </div>
      </form>
    </section>
    <?php endif; ?>

    <section class="sg-section">
      <div class="mc-page-grid mc-page-grid--categories" role="table" aria-label="Category 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="title"><button class="mc-page-grid__sort" type="button">Category</button></span>
          <span role="columnheader" data-mc-sort-key="slug"><button class="mc-page-grid__sort" type="button">Slug</button></span>
          <span role="columnheader" data-mc-sort-key="pages" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Pages</button></span>
          <span role="columnheader" data-mc-sort-key="status"><button class="mc-page-grid__sort" type="button">Status</button></span>
          <span role="columnheader">Actions</span>
        </div>

        <?php if ($categories === []): ?>
        <div class="mc-page-grid__row" role="row">
          <span class="mc-page-grid__cell" role="cell">No categories have been created yet.</span>
          <span class="mc-page-grid__cell" role="cell">-</span>
          <span class="mc-page-grid__cell" role="cell">-</span>
          <span class="mc-page-grid__cell" role="cell">-</span>
          <span class="mc-page-grid__cell" role="cell">-</span>
        </div>
        <?php endif; ?>

        <?php foreach ($categories as $category): ?>
        <?php $isActive = (bool) ($category['is_active'] ?? false); ?>
        <div
          class="mc-page-grid__row"
          role="row"
          data-mc-filter-row
          data-sort-title="<?= myronEscape((string) $category['title']) ?>"
          data-sort-slug="<?= myronEscape((string) $category['slug']) ?>"
          data-sort-pages="<?= myronEscape((string) ($category['page_count'] ?? 0)) ?>"
          data-sort-status="<?= $isActive ? 'active' : 'archived' ?>"
        >
          <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
            <span class="mc-page-grid__name"><?= myronEscape((string) $category['title']) ?></span>
            <?php if (trim((string) ($category['description'] ?? '')) !== ''): ?>
            <span class="mc-page-grid__subtle"><?= myronEscape((string) $category['description']) ?></span>
            <?php endif; ?>
          </span>
          <span class="mc-page-grid__cell" role="cell"><code><?= myronEscape((string) $category['slug']) ?></code></span>
          <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) ($category['page_count'] ?? 0)) ?></span>
          <span class="mc-page-grid__cell" role="cell">
            <span class="sg-pill <?= $isActive ? 'sg-pill--active' : '' ?>"><?= $isActive ? 'Active' : 'Archived' ?></span>
          </span>
          <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
            <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('content.categories', ['manage' => (string) $category['id']])) ?>">Manage</a>
            <?php if ($canManageContent): ?>
            <form method="post" class="mc-page-grid__action-form">
              <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
              <input type="hidden" name="category_id" value="<?= myronEscape((string) $category['id']) ?>">
              <?php if ($isActive): ?>
              <button class="sg-button sg-button--secondary" type="submit" name="action" value="archive-category">Archive</button>
              <?php else: ?>
              <button class="sg-button sg-button--secondary" type="submit" name="action" value="reactivate-category">Reactivate</button>
              <?php endif; ?>
            </form>
            <?php endif; ?>
          </span>
        </div>
        <?php endforeach; ?>
      </div>
    </section>

    <?php if (is_array($managedCategory)): ?>
    <?php ob_start(); ?>
    <div class="mc-sidesheet-form">
      <?php if ($canManageContent): ?>
      <form method="post" class="mc-sidesheet-form">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="update-category">
        <input type="hidden" name="category_id" value="<?= myronEscape((string) $managedCategory['id']) ?>">
        <section class="mc-sidesheet-form__section" aria-label="Category details">
          <div class="mc-sidesheet-form__grid">
            <label class="sg-field">
              <span class="sg-field__label">Title</span>
              <input class="sg-field__control" type="text" name="title" required maxlength="255" value="<?= myronEscape((string) $managedCategory['title']) ?>">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Slug</span>
              <input class="sg-field__control" type="text" name="slug" required maxlength="160" value="<?= myronEscape((string) $managedCategory['slug']) ?>">
            </label>
            <label class="sg-field mc-sidesheet-form__span-full">
              <span class="sg-field__label">Description</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="3" data-mc-richtext="true"><?= myronEscape((string) $managedCategory['description']) ?></textarea>
            </label>
            <label class="sg-field sg-field--checkbox mc-sidesheet-form__span-full">
              <span class="sg-field__label">Status</span>
              <span class="sg-field__checkbox">
                <input type="checkbox" name="is_active" value="1"<?= ((bool) $managedCategory['is_active']) ? ' checked' : '' ?>>
                <span>Active in page editor category pickers</span>
              </span>
            </label>
          </div>
        </section>
        <div class="mc-admin-form__actions">
          <button class="sg-button sg-button--primary" type="submit">Save Category</button>
        </div>
      </form>
      <?php else: ?>
      <p class="sg-section__subtitle">You can view this category, but your current access cannot edit it.</p>
      <?php endif; ?>
    </div>
    <?php $manageBody = (string) ob_get_clean(); ?>
    <?php myronRenderAdminSidesheet('category-manage-sheet', 'Manage Category', $manageBody, [
        'description' => 'Edit category details and page-editor availability.',
        'size' => 'lg',
    ]); ?>
    <button type="button" hidden data-mc-sidesheet-open="category-manage-sheet" data-category-manage-autopen>Open managed category</button>
    <script>document.addEventListener('DOMContentLoaded', function () { var trigger = document.querySelector('[data-category-manage-autopen]'); if (trigger) { trigger.click(); } });</script>
    <?php endif; ?>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
