<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\Csrf;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\ImageUpload;
use KeyLair\PageStyle;
use KeyLair\Settings;
use KeyLair\AuditLog;

Auth::requireLogin();
$admin = Auth::user();
$isDemo = $admin['role'] === 'demo';
$uploadDir = ROOT_PATH . '/public/uploads/branding';

$flash = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Auth::requireEditAccess();
    Csrf::requireValid();
    $action = $_POST['form_action'] ?? '';

    if ($action === 'set_theme') {
        $theme = $_POST['theme'] ?? '';
        if (Settings::setTheme($theme)) {
            AuditLog::log($admin['id'], 'theme_changed', $theme);
            $flash = ['type' => 'success', 'message' => I18n::t('design.flash.theme_updated')];
        } else {
            $flash = ['type' => 'error', 'message' => I18n::t('design.flash.theme_unknown')];
        }
    } elseif ($action === 'upload_background') {
        $result = ImageUpload::save($_FILES['background_image'] ?? [], $uploadDir);
        if ($result['ok']) {
            $old = Settings::backgroundImagePath();
            Settings::setBackgroundImage('/uploads/branding/' . $result['filename']);
            if ($old) {
                @unlink(ROOT_PATH . '/public' . $old);
            }
            AuditLog::log($admin['id'], 'background_image_uploaded', null);
            $flash = ['type' => 'success', 'message' => I18n::t('design.flash.background_uploaded')];
        } else {
            $flash = ['type' => 'error', 'message' => sprintf(I18n::t('design.flash.background_image_error'), $result['error'])];
        }
    } elseif ($action === 'remove_background') {
        $old = Settings::backgroundImagePath();
        Settings::clearBackgroundImage();
        if ($old) {
            @unlink(ROOT_PATH . '/public' . $old);
        }
        AuditLog::log($admin['id'], 'background_image_removed', null);
        $flash = ['type' => 'success', 'message' => I18n::t('design.flash.background_removed')];
    } else {
        $key = $_POST['key'] ?? '';

        if (!array_key_exists($key, PageStyle::CUSTOMIZABLE_PAGES)) {
            http_response_code(400);
            die(I18n::t('design.unknown_page'));
        }

        if ($action === 'upload') {
            if (empty($_FILES['css_file']) || $_FILES['css_file']['error'] !== UPLOAD_ERR_OK) {
                $flash = ['type' => 'error', 'message' => I18n::t('design.flash.css_file_required')];
            } else {
                $content = file_get_contents($_FILES['css_file']['tmp_name']);
                $result = PageStyle::saveDraft($key, $content);
                if ($result['ok']) {
                    AuditLog::log($admin['id'], 'page_style_draft_uploaded', $key);
                    $flash = ['type' => 'success', 'message' => I18n::t('design.flash.draft_uploaded')];
                } else {
                    $flash = ['type' => 'error', 'message' => $result['error']];
                }
            }
        } elseif ($action === 'publish') {
            if (PageStyle::publish($key)) {
                AuditLog::log($admin['id'], 'page_style_published', $key);
                $flash = ['type' => 'success', 'message' => I18n::t('design.flash.published')];
            } else {
                $flash = ['type' => 'error', 'message' => I18n::t('design.flash.no_draft_to_publish')];
            }
        } elseif ($action === 'discard') {
            PageStyle::discardDraft($key);
            AuditLog::log($admin['id'], 'page_style_draft_discarded', $key);
            $flash = ['type' => 'success', 'message' => I18n::t('design.flash.draft_discarded')];
        } elseif ($action === 'reset') {
            PageStyle::resetToDefault($key);
            AuditLog::log($admin['id'], 'page_style_reset', $key);
            $flash = ['type' => 'success', 'message' => I18n::t('design.flash.reset_to_default')];
        }
    }
}

$pageTitle = I18n::t('design.page_title');
$activeNav = 'design';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar">
  <h1><?= Helpers::e(I18n::t('design.page_title')) ?></h1>
</div>

<?php if ($flash): ?>
  <div class="panel" style="border-color:<?= $flash['type'] === 'success' ? 'var(--signal-dim)' : 'var(--danger)' ?>; margin-bottom:16px;">
    <span style="font-size:13px; color:<?= $flash['type'] === 'success' ? 'var(--signal)' : 'var(--danger)' ?>;"><?= Helpers::e($flash['message']) ?></span>
  </div>
<?php endif; ?>

<?php $currentTheme = Settings::theme(); $isCustomTheme = $currentTheme === 'custom'; ?>

<div class="panel" style="margin-bottom:16px;">
  <p class="panel-title"><?= Helpers::e(I18n::t('design.theme_panel_title')) ?></p>
  <p style="color:var(--text-muted); font-size:13px; max-width:640px; margin:0 0 14px;">
    <?= I18n::t('design.theme_panel_hint') ?>
  </p>
  <div style="display:flex; flex-direction:column; gap:8px;">
    <?php foreach (['default' => 'design.theme_default', 'light' => 'design.theme_light', 'steam' => 'design.theme_steam', 'custom' => 'design.theme_custom'] as $themeKey => $themeLabelKey): ?>
      <div style="display:flex; align-items:center; gap:8px;">
        <?php if (Auth::canEdit()): ?>
        <form method="post" class="theme-row-form" style="margin:0;">
          <?= Csrf::field() ?>
          <input type="hidden" name="form_action" value="set_theme">
          <input type="hidden" name="theme" value="<?= $themeKey ?>">
          <button type="submit" class="btn theme-row-btn <?= $currentTheme === $themeKey ? 'btn-primary' : 'btn-ghost' ?>" style="width:90px;" <?= $currentTheme === $themeKey ? 'disabled' : '' ?>><?= Helpers::e(I18n::t($themeLabelKey)) ?></button>
        </form>
        <?php else: ?>
          <span class="btn theme-row-btn btn-ghost" style="width:90px; text-align:center; <?= $currentTheme === $themeKey ? 'color:var(--signal); border-color:var(--signal-dim);' : '' ?>"><?= Helpers::e(I18n::t($themeLabelKey)) ?></span>
        <?php endif; ?>
        <a class="btn theme-row-preview btn-ghost" style="text-decoration:none; font-size:12px;" href="preview.php?key=product-page&amp;theme=<?= $themeKey ?>" target="_blank" rel="noopener"><?= Helpers::e(I18n::t('design.preview_link')) ?></a>
      </div>
    <?php endforeach; ?>
  </div>
</div>

<div class="panel" style="margin-bottom:16px; <?= $isCustomTheme ? '' : 'opacity:0.45;' ?>">
  <p class="panel-title"><?= Helpers::e(I18n::t('design.background_panel_title')) ?> <?= $isCustomTheme ? '' : Helpers::e(I18n::t('design.background_custom_only')) ?></p>
  <p style="color:var(--text-muted); font-size:13px; max-width:640px; margin:0 0 14px;">
    <?= I18n::t('design.background_panel_hint') ?>
  </p>
  <?php $backgroundImage = Settings::backgroundImagePath(); ?>
  <div style="display:flex; flex-direction:column; gap:12px; <?= $isCustomTheme ? '' : 'pointer-events:none;' ?>">
    <?php if ($backgroundImage): ?>
      <div style="width:160px; aspect-ratio:16/9; border-radius:10px; overflow:hidden; border:1px solid var(--line);">
        <img src="<?= Helpers::e($backgroundImage) ?>" alt="" style="width:100%;height:100%;object-fit:cover;">
      </div>
    <?php endif; ?>
    <?php if (Auth::canEdit() || $isDemo): ?>
      <?php $bgUploadFormId = 'bg-upload-form'; $bgRemoveFormId = 'bg-remove-form'; ?>
      <!-- display:contents on a <form> (tried first, to make Choose-file/
           Preview/Upload real flex siblings without nesting the link
           inside markup meant for a form) turns out not to reliably pass
           flex-grow through to an inline child like an <a> in every
           browser -- it kept the link's own display computing to inline
           instead of the blockified flex-item behavior the spec calls
           for, so it never actually grew to share the row 50/50 the way
           its CSS said it should. Each form now renders invisibly, just
           holding its hidden fields, with its real visible controls
           living as plain flex-container children referencing it via
           the form="..." attribute instead -- same technique as the
           Users page Manage panel elsewhere on this site. -->
      <form id="<?= $bgUploadFormId ?>" method="post" enctype="multipart/form-data" style="display:none;" <?= $isCustomTheme ? '' : 'inert' ?>>
        <?= Csrf::field() ?>
        <input type="hidden" name="form_action" value="upload_background">
      </form>
      <?php if ($backgroundImage): ?>
      <form id="<?= $bgRemoveFormId ?>" method="post" style="display:none;" <?= $isCustomTheme ? '' : 'inert' ?> onsubmit="return confirm(<?= json_encode(I18n::t('design.remove_background_confirm'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
        <?= Csrf::field() ?>
        <input type="hidden" name="form_action" value="remove_background">
      </form>
      <?php endif; ?>
      <!-- The fieldset IS the flex container here (not display:contents
           inside a separate flex div) -- display:contents on a fieldset
           turns out to have the same "doesn't reliably blockify an <a>
           child for flex sizing" issue as it did on the <form> above. -->
      <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0; display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
        <label class="btn btn-ghost bg-upload-choose" style="cursor:pointer; display:inline-flex; align-items:center; gap:8px; margin:0;">
          <span><?= Helpers::e(I18n::t('design.choose_file')) ?></span>
          <span id="bg-image-name" style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('design.no_file_chosen')) ?></span>
          <input type="file" name="background_image" form="<?= $bgUploadFormId ?>" accept="image/jpeg,image/png,image/webp" style="display:none;" <?= $isCustomTheme ? '' : 'disabled' ?> onchange="document.getElementById('bg-image-name').textContent = this.files[0]?.name || <?= json_encode(I18n::t('design.no_file_chosen'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;">
        </label>
        <a class="btn btn-ghost page-style-preview" style="text-decoration:none;" href="preview.php?key=product-page&amp;theme=custom" target="_blank" rel="noopener"><?= Helpers::e(I18n::t('design.preview_link')) ?></a>
        <button type="submit" form="<?= $bgUploadFormId ?>" class="btn btn-primary bg-upload-btn" <?= $isCustomTheme ? '' : 'disabled' ?>><?= $backgroundImage ? Helpers::e(I18n::t('design.replace_button')) : Helpers::e(I18n::t('design.upload_button')) ?></button>
        <?php if ($backgroundImage): ?>
          <button type="submit" form="<?= $bgRemoveFormId ?>" class="btn btn-ghost bg-remove-btn" style="color:var(--danger);" <?= $isCustomTheme ? '' : 'disabled' ?>><?= Helpers::e(I18n::t('design.remove_button')) ?></button>
        <?php endif; ?>
      </fieldset>
    <?php endif; ?>
  </div>
</div>

<p style="color:var(--text-muted); font-size:13px; max-width:640px; margin:-8px 0 22px;">
  <?= I18n::t('design.per_page_intro') ?>
  <?php if (!$isCustomTheme): ?>
    <strong style="color:var(--key-gold);"><?= Helpers::e(I18n::t('design.custom_theme_required_notice')) ?></strong>
  <?php endif; ?>
</p>

<?php
  $pageStyleLabelKeys = [
      'claim-overview' => 'design.page_label.claim_overview',
      'product-page' => 'design.page_label.product_page',
  ];
?>
<?php foreach (PageStyle::CUSTOMIZABLE_PAGES as $key => $label): $status = PageStyle::status($key); $label = I18n::t($pageStyleLabelKeys[$key] ?? '') ?: $label; ?>
  <div class="panel" style="margin-bottom:14px; <?= $isCustomTheme ? '' : 'opacity:0.45; pointer-events:none;' ?>">
    <div style="display:flex; align-items:flex-start; justify-content:space-between; gap:16px; flex-wrap:wrap; margin-bottom:14px;">
      <?php
        // Split "Overview page (list of products for a claim link)" into
        // its main title and parenthetical -- on its own line below
        // instead of wrapping wherever it happens to run out of room
        // mid-sentence.
        $labelMain = $label;
        $labelDetail = null;
        if (preg_match('/^(.*?)\s*(\(.*\))$/', $label, $m)) {
            $labelMain = $m[1];
            $labelDetail = $m[2];
        }
      ?>
      <div>
        <p class="panel-title" style="margin-bottom:4px;">
          <?= Helpers::e($labelMain) ?>
          <?php if ($labelDetail !== null): ?>
            <span style="display:block; font-size:12px; font-weight:400; color:var(--text-faint); margin-top:2px;"><?= Helpers::e($labelDetail) ?></span>
          <?php endif; ?>
        </p>
        <p style="font-size:11.5px; color:var(--text-faint); font-family:var(--font-mono); margin:0;">/assets/css/<?= $key ?>.css</p>
      </div>
      <div style="display:flex; gap:6px; flex-wrap:wrap;">
        <?php if ($status['is_published_custom']): ?>
          <span class="status-pill"><?= Helpers::e(I18n::t('design.status_customized')) ?></span>
        <?php else: ?>
          <span class="status-pill" style="background:rgba(136,144,164,0.12); color:var(--text-muted);"><?= Helpers::e(I18n::t('design.status_default')) ?></span>
        <?php endif; ?>
        <?php if ($status['has_draft']): ?>
          <span class="status-pill" style="background:rgba(232,181,99,0.14); color:var(--key-gold);"><?= Helpers::e(I18n::t('design.status_draft_pending')) ?></span>
        <?php endif; ?>
      </div>
    </div>

    <div style="display:flex; flex-direction:column; gap:8px;">
      <div style="display:flex; gap:8px; flex-wrap:wrap;">
        <a class="btn btn-ghost design-download-link" style="text-decoration:none;" href="design_download.php?key=<?= $key ?>&amp;version=default"><?= Helpers::e(I18n::t('design.download_default_template')) ?></a>
        <a class="btn btn-ghost design-download-link" style="text-decoration:none;" href="design_download.php?key=<?= $key ?>&amp;version=active"><?= Helpers::e(I18n::t('design.download_active')) ?></a>
        <?php // Reserves the same width as the Upload button on the row below (always just "Upload" for a per-page card), so the two download links split only the Choose-file+Preview span instead of the full row including Upload's column. ?>
        <span class="design-download-spacer" aria-hidden="true"></span>
      </div>

      <?php if (Auth::canEdit() || $isDemo): ?>
      <?php if ($status['has_draft']): ?>
      <div style="display:flex; gap:8px; flex-wrap:wrap;">
        <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
        <form method="post" style="margin:0;">
          <?= Csrf::field() ?>
          <input type="hidden" name="key" value="<?= $key ?>">
          <input type="hidden" name="form_action" value="publish">
          <button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('design.publish_draft_button')) ?></button>
        </form>
        </fieldset>
        <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
        <form method="post" style="margin:0;">
          <?= Csrf::field() ?>
          <input type="hidden" name="key" value="<?= $key ?>">
          <input type="hidden" name="form_action" value="discard">
          <button type="submit" class="btn btn-ghost"><?= Helpers::e(I18n::t('design.discard_draft_button')) ?></button>
        </form>
        </fieldset>
      </div>
      <?php endif; ?>

      <?php if ($status['is_published_custom']): ?>
        <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">
        <form method="post" style="margin:0;" onsubmit="return confirm(<?= json_encode(I18n::t('design.reset_confirm_js'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>);">
          <?= Csrf::field() ?>
          <input type="hidden" name="key" value="<?= $key ?>">
          <input type="hidden" name="form_action" value="reset">
          <button type="submit" class="btn btn-ghost" style="color:var(--danger);"><?= Helpers::e(I18n::t('design.reset_to_default_button')) ?></button>
        </form>
        </fieldset>
      <?php endif; ?>

      <?php $pageStyleUploadFormId = "page-style-upload-form-{$key}"; ?>
      <!-- Same form="..." restructure as the background-image row above
           -- display:contents on this <form> (the previous approach)
           didn't reliably pass flex-grow through to the <a>, so Choose-
           file/Preview/Upload are now genuine flex-container children,
           with the actual upload <form> rendered invisibly alongside
           them holding just its hidden fields. -->
      <form id="<?= $pageStyleUploadFormId ?>" method="post" enctype="multipart/form-data" style="display:none;">
        <?= Csrf::field() ?>
        <input type="hidden" name="key" value="<?= $key ?>">
        <input type="hidden" name="form_action" value="upload">
      </form>
      <!-- Fieldset is the flex container directly here too -- see the
           background-image row's own comment above for why (not
           display:contents inside a separate flex div). -->
      <fieldset <?= $isDemo ? 'disabled' : '' ?> class="page-style-actions" style="border:0; margin:0; padding:0; display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
        <label class="btn btn-ghost page-style-choose" style="cursor:pointer; display:inline-flex; align-items:center; gap:8px; margin:0;">
          <span><?= Helpers::e(I18n::t('design.choose_file')) ?></span>
          <span id="css-file-<?= $key ?>" style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('design.no_file_chosen')) ?></span>
          <input type="file" name="css_file" form="<?= $pageStyleUploadFormId ?>" accept=".css,text/css" required style="display:none;" onchange="document.getElementById('css-file-<?= $key ?>').textContent = this.files[0]?.name || <?= json_encode(I18n::t('design.no_file_chosen'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;">
        </label>
        <a class="btn btn-ghost page-style-preview" style="text-decoration:none;" href="preview.php?key=<?= $key ?>" target="_blank" rel="noopener"><?= Helpers::e(I18n::t('design.preview_link')) ?></a>
        <button type="submit" form="<?= $pageStyleUploadFormId ?>" class="btn btn-primary page-style-upload-btn"><?= Helpers::e(I18n::t('design.upload_button')) ?></button>
      </fieldset>
      <?php else: ?>
      <a class="btn btn-ghost" style="text-decoration:none; align-self:flex-start;" href="preview.php?key=<?= $key ?>" target="_blank" rel="noopener"><?= Helpers::e(I18n::t('design.preview_link')) ?></a>
      <?php endif; ?>
    </div>
  </div>
<?php endforeach; ?>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>
