<?php

declare(strict_types=1);

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

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

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

        // APO-194 Card 4 — files mutations funnel through MyronFilesActionService.
        // Admin form uses multipart $_FILES; API uses JSON-content envelope. Both
        // produce identical file rows + identical bytes-on-disk; verifier asserts
        // the byte-equal property.
        $filesService = myronFilesActionService();
        $callerCtx = myronActionCallerContextForUser($currentUser);

        if ($action === 'upload-file') {
            $file = $filesService->uploadFromMultipart(
                $_FILES['upload_file'] ?? [],
                $_POST,
                $callerCtx,
                true
            );
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.files', ['manage' => (string) $file['id']]),
                'File uploaded successfully.',
                'success'
            );
        }

        if ($action === 'update-file') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            $filesService->updateMetadata($fileId, $_POST, $callerCtx);
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.files', ['manage' => $fileId]),
                'File details saved.',
                'success'
            );
        }

        if ($action === 'replace-file') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            $filesService->replaceFromMultipart($fileId, $_FILES['replacement_file'] ?? [], $_POST, $callerCtx);
            myronRedirectWithFlash(
                myronBuildAdminUrl('content.files', ['manage' => $fileId]),
                'File replaced. Existing references now use the new asset bytes.',
                'success'
            );
        }

        if ($action === 'delete-file') {
            $fileId = trim((string) ($_POST['file_id'] ?? ''));
            $filesService->delete($fileId, $callerCtx);
            myronRedirectWithFlash(myronBuildAdminUrl('content.files'), 'File deleted.', 'success');
        }

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

$files = $repository->listFiles();
$managedFile = $manageId !== '' ? $repository->getFileById($manageId) : null;
if ($manageId !== '' && !is_array($managedFile)) {
    $missingManageMessage = 'The selected file could not be found.';
}

myronRenderAdminShellStart($currentUser, [
    'title' => 'Files',
    'titleContext' => 'Content',
    'activeItem' => 'files',
    'headScripts' => [myronBuildAssetUrl('runtime/js/files.js')],
    'utilityPrimary' => [
        'href' => '#file-upload',
        'label' => 'Upload file',
        'title' => 'Upload file',
        'icon' => 'plus-lg',
    ],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Content', 'href' => myronBuildAdminUrl('content.pages')],
      ['label' => 'Files'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Files</h1>
  </div>
  <p class="mc-workspace__subtitle">Upload and manage the files your site can use.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if ($missingManageMessage !== ''): ?>
    <div class="sg-status sg-status--error" role="status">
      <?= myronEscape($missingManageMessage) ?>
    </div>
    <?php endif; ?>

    <div class="mc-files-layout<?= is_array($managedFile) ? ' mc-files-layout--sheet-open' : '' ?>">
      <section class="sg-section">
        <form id="file-upload" method="post" enctype="multipart/form-data" class="sg-form-grid mc-files-upload">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="upload-file">

          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Add File</span>
            <input class="sg-field__control" type="file" name="upload_file" required accept=".jpg,.jpeg,.png,.gif,.webp,.svg,.pdf,.txt,.csv,.zip">
            <span class="sg-field__hint">Allowed in this slice: images, PDF, TXT, CSV, and ZIP files up to 15 MB.</span>
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Alt Text</span>
            <input class="sg-field__control" type="text" name="alt_text" required maxlength="500">
          </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" required rows="3"></textarea>
          </label>

          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Caption</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="caption" required rows="3"></textarea>
          </label>

          <div class="sg-card__actions">
            <button class="sg-button sg-button--primary" type="submit">Upload File</button>
          </div>
        </form>

        <div class="mc-page-grid mc-page-grid--files" role="table" aria-label="Files 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="filename"><button class="mc-page-grid__sort" type="button">Filename</button></span>
            <span role="columnheader" data-mc-sort-key="type"><button class="mc-page-grid__sort" type="button">Type</button></span>
            <span role="columnheader" data-mc-sort-key="uploaded-by"><button class="mc-page-grid__sort" type="button">Uploaded By</button></span>
            <span role="columnheader" data-mc-sort-key="uploaded"><button class="mc-page-grid__sort" type="button">Uploaded</button></span>
            <span role="columnheader" data-mc-sort-key="size" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Size</button></span>
            <span role="columnheader" data-mc-sort-key="dimensions" data-mc-sort-type="number"><button class="mc-page-grid__sort" type="button">Dimensions</button></span>
            <span role="columnheader">Actions</span>
          </div>

          <?php if ($files === []): ?>
          <div
            class="mc-page-grid__row"
            role="row"
            data-mc-filter-row
            data-sort-filename="<?= myronEscape((string) $file['original_filename'] . ' ' . (string) ($file['title'] ?? '')) ?>"
            data-sort-type="<?= myronEscape((string) $file['file_extension']) ?>"
            data-sort-uploaded-by="<?= myronEscape((string) $file['uploaded_by_display_name']) ?>"
            data-sort-uploaded="<?= myronEscape((string) $file['created_at']) ?>"
            data-sort-size="<?= myronEscape((string) ($file['file_size_bytes'] ?? 0)) ?>"
            data-sort-dimensions="<?= myronEscape((string) (((int) ($file['image_width'] ?? 0)) * ((int) ($file['image_height'] ?? 0)))) ?>"
          >
            <span class="mc-page-grid__cell" role="cell">No files 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>
            <span class="mc-page-grid__cell" role="cell">—</span>
            <span class="mc-page-grid__cell" role="cell">—</span>
          </div>
          <?php endif; ?>

          <?php foreach ($files as $file): ?>
          <?php
            $isManaged = (string) $file['id'] === $manageId;
          ?>
          <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__meta-stack">
                <span class="mc-page-grid__name"><?= myronEscape((string) $file['original_filename']) ?></span>
                <span class="mc-page-grid__subtle"><?= myronEscape((string) ($file['title'] ?? '')) ?></span>
              </span>
            </span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape(strtoupper((string) $file['file_extension'])) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) $file['uploaded_by_display_name']) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape(myronFormatAdminTimestamp((string) $file['created_at'])) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) $file['file_size_label']) ?></span>
            <span class="mc-page-grid__cell" role="cell"><?= myronEscape((string) $file['dimensions_label']) ?></span>
            <span class="mc-page-grid__cell mc-page-grid__cell--actions" role="cell">
              <a class="sg-button <?= $isManaged ? 'sg-button--primary' : 'sg-button--secondary' ?>" href="<?= myronEscape(myronBuildAdminUrl('content.files')) ?>?manage=<?= rawurlencode((string) $file['id']) ?>">Manage</a>
              <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) $file['file_url']) ?>" target="_blank" rel="noreferrer">Preview</a>
              <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape((string) $file['file_url']) ?>">Copy URL</button>
            </span>
          </div>
          <?php endforeach; ?>
        </div>
      </section>

      <?php if (is_array($managedFile)): ?>
      <?php $managedFileUrl = (string) (($managedFile['revisioned_file_url'] ?? '') ?: ($managedFile['file_url'] ?? '')); ?>
      <aside class="mc-side-sheet" aria-label="Manage file">
        <div class="mc-side-sheet__header">
          <div>
            <h2 class="mc-side-sheet__title">Manage File</h2>
            <div class="mc-side-sheet__meta">
              <span><?= myronEscape((string) $managedFile['original_filename']) ?></span>
              <span><?= myronEscape((string) $managedFile['mime_type']) ?> · <?= myronEscape((string) $managedFile['file_size_label']) ?></span>
            </div>
          </div>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('content.files')) ?>">Close</a>
        </div>

        <div class="mc-side-sheet__preview">
          <?php if (($managedFile['is_image'] ?? false) === true): ?>
          <img class="mc-side-sheet__preview-image" src="<?= myronEscape($managedFileUrl) ?>" alt="<?= myronEscape((string) ($managedFile['alt_text'] ?? $managedFile['title'] ?? '')) ?>">
          <?php elseif (($managedFile['is_pdf'] ?? false) === true): ?>
          <iframe class="mc-side-sheet__preview-frame" src="<?= myronEscape($managedFileUrl) ?>" title="File preview"></iframe>
          <?php else: ?>
          <div class="mc-side-sheet__preview-generic">
            <div>
              <strong>Preview unavailable</strong>
              <div class="mc-page-grid__subtle">Open or download the file to inspect it.</div>
            </div>
          </div>
          <?php endif; ?>
        </div>

        <form method="post" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="update-file">
          <input type="hidden" name="file_id" value="<?= myronEscape((string) $managedFile['id']) ?>">

          <label class="sg-field">
            <span class="sg-field__label">File Title</span>
            <input class="sg-field__control" type="text" name="title" value="<?= myronEscape((string) ($managedFile['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="3"><?= myronEscape((string) ($managedFile['description'] ?? '')) ?></textarea>
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Alt Text</span>
            <input class="sg-field__control" type="text" name="alt_text" value="<?= myronEscape((string) ($managedFile['alt_text'] ?? '')) ?>">
          </label>

          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Caption</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="caption" rows="3"><?= myronEscape((string) ($managedFile['caption'] ?? '')) ?></textarea>
          </label>

          <div class="mc-side-sheet__url-row">
            <input class="sg-field__control mc-side-sheet__url-control" type="text" value="<?= myronEscape($managedFileUrl) ?>" readonly>
            <button class="sg-button" type="button" data-mc-copy-url="<?= myronEscape($managedFileUrl) ?>">Copy URL</button>
          </div>

          <div class="mc-side-sheet__actions">
            <button class="sg-button sg-button--primary" type="submit">Save File Details</button>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape($managedFileUrl) ?>" target="_blank" rel="noreferrer">Preview</a>
            <a class="sg-button sg-button--secondary" href="<?= myronEscape((string) $managedFile['download_url']) ?>">Download</a>
          </div>
        </form>

        <?= MyronAssetReplacementView::render([
            'csrfToken' => $csrfToken,
            'fileId' => (string) $managedFile['id'],
            'accept' => $repository->acceptAttributeForMediaClass((string) ($managedFile['media_class'] ?? 'document')),
            'label' => 'Replace File',
            'buttonLabel' => 'Replace File',
        ]) ?>

        <form method="post" class="mc-side-sheet__danger" onsubmit="return window.confirm('Delete this file from storage?');">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="delete-file">
          <input type="hidden" name="file_id" value="<?= myronEscape((string) $managedFile['id']) ?>">
          <button class="sg-button sg-button--danger" type="submit">Delete File</button>
        </form>
      </aside>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
