<?php

declare(strict_types=1);

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

$files = myronFileRepository();
$templates = myronDocumentTemplateRepository();
$csrfToken = myronCsrfToken();
$manageId = trim((string) ($_GET['manage'] ?? ''));

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $currentUser = myronRequireDesignAccess(true);
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));

        // APO-194 Card 3 — document template mutations funnel through
        // MyronDocumentTemplateActionService. Upload combines: file upload
        // (admin uses multipart $_FILES; API uses Files JSON-content envelope
        // from Card 4) → createFromFile via the service.
        $docService = myronDocumentTemplateActionService();
        $callerCtx = myronActionCallerContextForUser($currentUser);

        if ($action === 'upload-document-template') {
            $file = $files->uploadFile(
                $_FILES['upload_file'] ?? [],
                (string) $currentUser['id'],
                array_merge($_POST, ['asset_class' => 'document']),
                true
            );
            $template = $docService->createFromFile((string) $file['id'], $_POST, $callerCtx);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templateStudioDocumentTemplates', ['manage' => (string) $template['id']]),
                'Document template uploaded.',
                'success'
            );
        }

        if ($action === 'update-document-template') {
            $templateId = trim((string) ($_POST['template_id'] ?? ''));
            $docService->update($templateId, $_POST, $callerCtx);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templateStudioDocumentTemplates', ['manage' => $templateId]),
                'Document template details saved.',
                'success'
            );
        }

        if ($action === 'deactivate-document-template') {
            $templateId = trim((string) ($_POST['template_id'] ?? ''));
            $docService->deactivate($templateId, $callerCtx);
            myronRedirectWithFlash(
                myronBuildAdminUrl('design.templateStudioDocumentTemplates'),
                'Document template deactivated.',
                'success'
            );
        }

        throw new RuntimeException('Unknown document template action.');
    } catch (Throwable $exception) {
        $query = [];
        if ($manageId !== '') {
            $query['manage'] = $manageId;
        }
        myronRedirectWithFlash(myronBuildAdminUrl('design.templateStudioDocumentTemplates', $query), $exception->getMessage(), 'error');
    }
}

$currentUser = myronRequireDesignAccess();
$canManage = myronUserCanManageDesign($currentUser);
$uploadPolicy = $files->uploadPolicyForMediaClass('document');
$templateRows = $templates->listTemplates(false);
$managedTemplate = $manageId !== '' ? $templates->getTemplateById($manageId) : null;

myronRenderAdminShellStart($currentUser, [
    'title' => 'Document Templates',
    'titleContext' => 'Template Studio',
    'activeItem' => 'template-studio-document-templates',
    'headScripts' => [myronBuildAssetUrl('runtime/js/files.js')],
    'utilityPrimary' => $canManage ? [
        'href' => '#document-template-upload',
        'label' => 'Upload template',
        'title' => 'Upload template',
        'icon' => 'plus-lg',
    ] : [],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Design', 'href' => myronBuildAdminUrl('design.primitives')],
      ['label' => 'Template Studio', 'href' => myronBuildAdminUrl('design.templateStudio')],
      ['label' => 'Document Templates'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Document Templates</h1>
  </div>
  <p class="mc-workspace__subtitle">Upload and manage reusable document templates available to content operators.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <div class="mc-files-layout<?= is_array($managedTemplate) ? ' mc-files-layout--sheet-open' : '' ?>">
      <section class="sg-section" data-myron-design-document-templates>
        <?php if ($canManage): ?>
        <?= MyronAssetUploadView::renderCompact([
            'id' => 'document-template-upload',
            'csrfToken' => $csrfToken,
            'actionValue' => 'upload-document-template',
            'assetClass' => 'document',
            'titleLabel' => 'Template Title',
            'fileLabel' => 'Add Document Template',
            'submitLabel' => 'Upload Template',
            'accept' => $files->acceptAttributeForMediaClass('document'),
            'policyHint' => 'Maximum upload size on this server: ' . (string) $uploadPolicy['effectiveLabel'] . '. MyronCMS document policy limit: ' . (string) $uploadPolicy['policyLabel'] . '.',
        ]) ?>
        <?php endif; ?>

        <div class="sg-section__header">
          <h2 class="sg-section__title">Available Templates</h2>
          <p class="sg-section__subtitle"><?= myronEscape((string) count($templateRows)) ?> uploaded templates</p>
        </div>

        <div class="mc-page-grid mc-page-grid--files" role="table" aria-label="Document Templates">
          <div class="mc-page-grid__row mc-page-grid__row--head" role="row">
            <span role="columnheader">Template</span>
            <span role="columnheader">Type</span>
            <span role="columnheader">Status</span>
            <span role="columnheader">Updated</span>
            <span role="columnheader">Actions</span>
          </div>
          <?php if ($templateRows === []): ?>
          <div class="mc-page-grid__row" role="row">
            <span class="mc-page-grid__cell" role="cell">No document templates have been uploaded 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 ($templateRows as $template): ?>
          <div class="mc-page-grid__row" role="row">
            <span class="mc-page-grid__cell mc-page-grid__cell--name" role="cell">
              <span class="mc-page-grid__name"><?= myronEscape((string) ($template['title'] ?? 'Document template')) ?></span>
              <span class="mc-page-grid__subtle"><?= myronEscape((string) ($template['description'] ?? '')) ?></span>
            </span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape(strtoupper((string) ($template['file_extension'] ?? ''))) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= ((bool) ($template['is_active'] ?? false)) ? 'Active' : 'Inactive' ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape(myronFormatAdminTimestamp((string) ($template['updated_at'] ?? ''))) ?></span>
            <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
              <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('design.templateStudioDocumentTemplates', ['manage' => (string) $template['id']])) ?>">Manage</a>
              <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape((string) ($template['file_url'] ?? '')) ?>">Copy URL</button>
              <a class="sg-button" href="<?= myronEscape((string) ($template['download_url'] ?? '')) ?>">Download</a>
            </span>
          </div>
          <?php endforeach; ?>
        </div>
      </section>

      <?php if (is_array($managedTemplate)): ?>
      <aside class="mc-side-sheet" aria-label="Manage document template">
        <div class="mc-side-sheet__header">
          <div>
            <h2 class="mc-side-sheet__title">Manage Template</h2>
            <div class="mc-side-sheet__meta">
              <span><?= myronEscape((string) ($managedTemplate['original_filename'] ?? 'Document template')) ?></span>
              <span><?= myronEscape((string) ($managedTemplate['mime_type'] ?? '')) ?> · <?= myronEscape((string) ($managedTemplate['file_size_label'] ?? '')) ?></span>
            </div>
          </div>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('design.templateStudioDocumentTemplates')) ?>">Close</a>
        </div>

        <form method="post" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="update-document-template">
          <input type="hidden" name="template_id" value="<?= myronEscape((string) $managedTemplate['id']) ?>">
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Template Title</span>
            <input class="sg-field__control" type="text" name="title" required maxlength="255" value="<?= myronEscape((string) ($managedTemplate['title'] ?? '')) ?>">
          </label>
          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Description</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="4"><?= myronEscape((string) ($managedTemplate['description'] ?? '')) ?></textarea>
          </label>
          <div class="sg-card__actions">
            <button class="sg-button sg-button--primary" type="submit">Save Details</button>
            <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape((string) ($managedTemplate['file_url'] ?? '')) ?>">Copy URL</button>
            <a class="sg-button" href="<?= myronEscape((string) ($managedTemplate['download_url'] ?? '')) ?>">Download</a>
          </div>
        </form>

        <?php if ((bool) ($managedTemplate['is_active'] ?? false)): ?>
        <form method="post" class="sg-card__actions">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="deactivate-document-template">
          <input type="hidden" name="template_id" value="<?= myronEscape((string) $managedTemplate['id']) ?>">
          <button class="sg-button sg-button--danger" type="submit">Deactivate Template</button>
        </form>
        <?php endif; ?>
      </aside>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
