<?php

declare(strict_types=1);

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

$currentUser = myronRequireAdministrationAccess();
$repository = myronSiteSettingsRepository();
$fileRepository = myronFileRepository();
$uploadHandler = myronAssetUploadRequestHandler();
$csrfToken = myronCsrfToken();

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

        if ($action === 'upload-asset-picker') {
            $assetClass = trim((string) ($_POST['asset_class'] ?? 'image'));
            if ($assetClass !== 'image') {
                throw new RuntimeException('Only image asset uploads are supported from Site Settings.');
            }
            $result = $uploadHandler->handle(
                $_FILES,
                $_POST,
                (string) $currentUser['id'],
                ['assetClass' => 'image', 'metadataRequired' => true]
            );
            if (myronRequestExpectsJson()) {
                if (($result['ok'] ?? false) !== true) {
                    myronJsonResponse([
                        'ok' => false,
                        'error' => (string) ($result['error'] ?? 'Upload failed.'),
                    ], (int) ($result['status'] ?? 422));
                }
                myronJsonResponse([
                    'ok' => true,
                    'asset' => $result['asset'] ?? [],
                ]);
            }
            if (($result['ok'] ?? false) !== true) {
                throw new RuntimeException((string) ($result['error'] ?? 'Upload failed.'));
            }
            myronRedirectWithFlash(myronBuildAdminUrl('administration.siteSettings'), 'Image asset uploaded.', 'success');
        }

        if ($action === 'save-site-settings') {
            $repository->saveSettings(
                $_POST,
                is_array($_FILES['site_favicon'] ?? null) ? $_FILES['site_favicon'] : null,
                (string) $currentUser['id']
            );
            myronRefreshSiteSettingsCache();
            $message = 'Site settings saved.';
            $ogValidation = myronOgImageValidator()->validateDimensions((string) ($_POST['seo_default_og_image'] ?? ''));
            if (trim((string) ($ogValidation['message'] ?? '')) !== '') {
                $message .= ' ' . (string) $ogValidation['message'];
            }
            myronRedirectWithFlash(myronBuildAdminUrl('administration.siteSettings'), $message, 'success');
        }

        throw new RuntimeException('Unknown site settings action.');
    } catch (Throwable $exception) {
        if (myronRequestExpectsJson()) {
            myronJsonResponse([
                'ok' => false,
                'error' => $exception->getMessage(),
            ], 422);
        }
        myronRedirectWithFlash(myronBuildAdminUrl('administration.siteSettings'), $exception->getMessage(), 'error');
    }
}

$settings = $repository->getSettings();
$languageOptions = myronSiteLanguageOptions();
$dateFormatOptions = myronSiteDateFormatOptions();
$timeFormatOptions = myronSiteTimeFormatOptions();
$timezone = trim((string) ($settings['timezone'] ?? 'UTC')) ?: 'UTC';
$previewDate = new DateTimeImmutable('2026-04-23 15:45:00', new DateTimeZone($timezone));
$availableImageFiles = array_values(array_filter(
    $fileRepository->listFiles(),
    static fn (array $file): bool => (bool) ($file['is_image'] ?? false)
));

myronRenderAdminShellStart($currentUser, [
    'title' => 'Site Settings',
    'titleContext' => 'Administration',
    'activeItem' => 'site-settings',
    'headScripts' => [myronBuildAssetUrl('runtime/js/asset-picker.js')],
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'System', 'href' => myronBuildAdminUrl('administration.siteSetup')],
      ['label' => 'Site Settings'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Site Settings</h1>
  </div>
  <p class="mc-workspace__subtitle">Manage the site identity, local formatting defaults, browser icon, and public navigation logo assets.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <form method="post" enctype="multipart/form-data" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="save-site-settings">

        <label class="sg-field sg-field--full">
          <span class="sg-field__label">Site Title</span>
          <input class="sg-field__control" type="text" name="site_title" required value="<?= myronEscape((string) ($settings['site_title'] ?? 'MyronCMS')) ?>">
          <span class="sg-field__help">Shown in the public site header and used alongside page titles in document metadata.</span>
        </label>

        <fieldset class="sg-fieldset sg-field--full">
          <legend>Public Site Mode</legend>
          <?php
            $currentPublicMode = (string) ($settings['public_mode'] ?? 'off');
            if (!in_array($currentPublicMode, ['off', 'coming_soon', 'maintenance'], true)) {
                $currentPublicMode = 'off';
            }
            $publicModeOptions = [
                'off' => ['Off — public site is visible normally', ''],
                'coming_soon' => ['Coming Soon', 'Public visitors see a centered "Coming Soon" page. Returns HTTP 200.'],
                'maintenance' => ['Maintenance Mode', 'Public visitors see a centered "Maintenance Mode" page. Returns HTTP 503.'],
            ];
          ?>
          <?php foreach ($publicModeOptions as $value => $copy): ?>
          <label class="sg-checkbox sg-checkbox--spaced">
            <input type="radio" name="public_mode" value="<?= myronEscape($value) ?>"<?= $currentPublicMode === $value ? ' checked' : '' ?>>
            <span><?= myronEscape($copy[0]) ?></span>
          </label>
          <?php if ($copy[1] !== ''): ?>
          <p class="sg-field__help"><?= myronEscape($copy[1]) ?></p>
          <?php endif; ?>
          <?php endforeach; ?>
          <p class="sg-field__help">When set to Coming Soon or Maintenance Mode, public visitors see a chrome-less placeholder. Logged-in admins continue to see the live site.</p>
        </fieldset>

        <fieldset class="sg-fieldset">
          <legend>Site Logo</legend>
          <div class="sg-form-grid mc-site-logo-grid">
            <?= MyronAssetPickerView::renderField([
                'id' => 'site-logo-light',
                'label' => 'Light Mode Logo',
                'name' => 'site_logo_light_url',
                'value' => (string) ($settings['site_logo_light_url'] ?? ''),
                'pickerId' => 'site-settings-logo-asset-picker',
            ]) . "\n" ?>
            <?= MyronAssetPickerView::renderField([
                'id' => 'site-logo-dark',
                'label' => 'Dark Mode Logo',
                'name' => 'site_logo_dark_url',
                'value' => (string) ($settings['site_logo_dark_url'] ?? ''),
                'pickerId' => 'site-settings-logo-asset-picker',
            ]) . "\n" ?>
            <label class="sg-field">
              <span class="sg-field__label">Logo Alt Text</span>
              <input class="sg-field__control" type="text" name="site_logo_alt" maxlength="160" value="<?= myronEscape((string) ($settings['site_logo_alt'] ?? '')) ?>">
            </label>
          </div>
        </fieldset>

        <div class="sg-field sg-field--full">
          <span class="sg-field__label">Site Favicon</span>
          <?php if (is_array($settings['favicon_file'] ?? null)): ?>
          <div class="sg-inline-note sg-inline-note--favicon">
            <?php if (myronSiteFaviconUrl() !== null): ?>
            <img class="sg-inline-note__favicon" src="<?= myronEscape((string) myronSiteFaviconUrl()) ?>" alt="" aria-hidden="true">
            <?php endif; ?>
            <span>Current favicon: <?= myronEscape((string) (($settings['favicon_file']['original_filename'] ?? '')) ?: 'Uploaded image') ?></span>
          </div>
          <?php endif; ?>
          <input class="sg-field__control" type="file" name="site_favicon" accept="image/png,image/jpeg,image/gif,image/webp,image/svg+xml">
          <div class="sg-form-grid">
            <label class="sg-field">
              <span class="sg-field__label">Upload Alt Text</span>
              <input class="sg-field__control" type="text" name="alt_text" maxlength="500">
            </label>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Upload Description</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="description" rows="3"></textarea>
            </label>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Upload Caption</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="caption" rows="3"></textarea>
            </label>
          </div>
          <label class="sg-checkbox sg-checkbox--spaced">
            <input type="checkbox" name="remove_favicon" value="1">
            <span>Remove current favicon</span>
          </label>
        </div>

        <label class="sg-field">
          <span class="sg-field__label">Site Language</span>
          <select class="sg-field__control" name="site_language">
            <?php foreach ($languageOptions as $value => $label): ?>
            <option value="<?= myronEscape($value) ?>"<?= (string) ($settings['site_language'] ?? 'en-US') === $value ? ' selected' : '' ?>><?= myronEscape($label) ?></option>
            <?php endforeach; ?>
          </select>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Time Zone</span>
          <select class="sg-field__control" name="timezone">
            <?php foreach (timezone_identifiers_list() as $option): ?>
            <option value="<?= myronEscape($option) ?>"<?= $timezone === $option ? ' selected' : '' ?>><?= myronEscape($option) ?></option>
            <?php endforeach; ?>
          </select>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Date Format</span>
          <select class="sg-field__control" name="date_format">
            <?php foreach ($dateFormatOptions as $value => $example): ?>
            <option value="<?= myronEscape($value) ?>"<?= (string) ($settings['date_format'] ?? 'F j, Y') === $value ? ' selected' : '' ?>><?= myronEscape($example) ?> (<?= myronEscape($value) ?>)</option>
            <?php endforeach; ?>
          </select>
          <span class="sg-field__help">Preview: <?= myronEscape($previewDate->format((string) ($settings['date_format'] ?? 'F j, Y'))) ?></span>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Time Format</span>
          <select class="sg-field__control" name="time_format">
            <?php foreach ($timeFormatOptions as $value => $example): ?>
            <option value="<?= myronEscape($value) ?>"<?= (string) ($settings['time_format'] ?? 'g:i a') === $value ? ' selected' : '' ?>><?= myronEscape($example) ?> (<?= myronEscape($value) ?>)</option>
            <?php endforeach; ?>
          </select>
          <span class="sg-field__help">Preview: <?= myronEscape($previewDate->format((string) ($settings['time_format'] ?? 'g:i a'))) ?></span>
        </label>

        <fieldset class="sg-fieldset sg-field--full">
          <legend>Analytics</legend>
          <div class="sg-form-grid">
            <label class="sg-checkbox sg-checkbox--spaced sg-field--full">
              <input type="checkbox" name="analytics_enabled" value="1"<?= !empty($settings['analytics_enabled']) ? ' checked' : '' ?>>
              <span>Use Myron Analytics on public pages</span>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Raw Data Retention</span>
              <select class="sg-field__control" name="analytics_retention_days">
                <?php foreach ([30, 90, 180, 365] as $days): ?>
                <option value="<?= $days ?>"<?= (int) ($settings['analytics_retention_days'] ?? 90) === $days ? ' selected' : '' ?>><?= $days ?> days</option>
                <?php endforeach; ?>
              </select>
              <span class="sg-field__help">Controls lazy purge of raw pageview and analytics event rows.</span>
            </label>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Third-Party Analytics Head Script</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="analytics_head_script" rows="6"><?= myronEscape((string) ($settings['analytics_head_script'] ?? '')) ?></textarea>
              <span class="sg-field__help">Optional raw script tag injected into the public site head for an external analytics provider.</span>
            </label>
          </div>
        </fieldset>

        <fieldset class="sg-fieldset sg-field--full">
          <legend>SEO</legend>
          <div class="sg-form-grid">
            <label class="sg-field">
              <span class="sg-field__label">Title Suffix</span>
              <input class="sg-field__control" type="text" name="seo_title_suffix" value="<?= myronEscape((string) ($settings['seo_title_suffix'] ?? '')) ?>">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Default Twitter Card</span>
              <select class="sg-field__control" name="seo_twitter_card_type">
                <?php foreach (['summary_large_image', 'summary'] as $cardType): ?>
                <option value="<?= myronEscape($cardType) ?>"<?= (string) ($settings['seo_twitter_card_type'] ?? 'summary_large_image') === $cardType ? ' selected' : '' ?>><?= myronEscape($cardType) ?></option>
                <?php endforeach; ?>
              </select>
            </label>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Default Meta Description</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="seo_default_description" rows="3"><?= myronEscape((string) ($settings['seo_default_description'] ?? '')) ?></textarea>
            </label>
            <?= MyronAssetPickerView::renderField([
                'id' => 'seo-default-og-image',
                'label' => 'Default OG Image',
                'name' => 'seo_default_og_image',
                'value' => (string) ($settings['seo_default_og_image'] ?? ''),
                'pickerId' => 'site-settings-logo-asset-picker',
            ]) . "\n" ?>
          </div>
          <div class="sg-form-grid">
            <label class="sg-field">
              <span class="sg-field__label">Organization Name</span>
              <input class="sg-field__control" type="text" name="seo_org_name" value="<?= myronEscape((string) ($settings['seo_org_name'] ?? '')) ?>">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Organization URL</span>
              <input class="sg-field__control" type="url" name="seo_org_url" value="<?= myronEscape((string) ($settings['seo_org_url'] ?? '')) ?>">
            </label>
            <?= MyronAssetPickerView::renderField([
                'id' => 'seo-org-logo',
                'label' => 'Organization Logo',
                'name' => 'seo_org_logo',
                'value' => (string) ($settings['seo_org_logo'] ?? ''),
                'pickerId' => 'site-settings-logo-asset-picker',
            ]) . "\n" ?>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Social Profiles</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="seo_social_profiles" rows="4"><?= myronEscape(implode("\n", array_map('strval', (array) ($settings['seo_social_profiles'] ?? [])))) ?></textarea>
            </label>
          </div>
          <div class="sg-form-grid">
            <label class="sg-checkbox sg-checkbox--spaced sg-field--full">
              <input type="checkbox" name="seo_local_business_enabled" value="1"<?= !empty($settings['seo_local_business_enabled']) ? ' checked' : '' ?>>
              <span>Emit LocalBusiness JSON-LD</span>
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Business Name</span>
              <input class="sg-field__control" type="text" name="seo_local_business_name" value="<?= myronEscape((string) ($settings['seo_local_business_name'] ?? '')) ?>">
            </label>
            <label class="sg-field">
              <span class="sg-field__label">Telephone</span>
              <input class="sg-field__control" type="text" name="seo_local_business_telephone" value="<?= myronEscape((string) ($settings['seo_local_business_telephone'] ?? '')) ?>">
            </label>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Address</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="seo_local_business_address" rows="3"><?= myronEscape((string) ($settings['seo_local_business_address'] ?? '')) ?></textarea>
            </label>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Opening Hours</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="seo_local_business_hours" rows="2"><?= myronEscape((string) ($settings['seo_local_business_hours'] ?? '')) ?></textarea>
            </label>
            <?= MyronAssetPickerView::renderField([
                'id' => 'seo-business-image',
                'label' => 'Business Image',
                'name' => 'seo_local_business_image',
                'value' => (string) ($settings['seo_local_business_image'] ?? ''),
                'pickerId' => 'site-settings-logo-asset-picker',
            ]) . "\n" ?>
          </div>
          <div class="mc-context-form__checkboxes">
            <?php foreach ([
                'seo_enable_canonical_output' => 'Enable canonical output',
                'seo_enable_json_ld_output' => 'Enable JSON-LD output',
                'seo_enable_social_output' => 'Enable social metadata output',
                'seo_enable_robots_output' => 'Enable robots meta output',
            ] as $field => $label): ?>
            <label class="mc-checkbox mc-checkbox--compact">
              <input type="checkbox" name="<?= myronEscape($field) ?>" value="1"<?= !empty($settings[$field]) ? ' checked' : '' ?>>
              <span><?= myronEscape($label) ?></span>
            </label>
            <?php endforeach; ?>
            <label class="sg-field sg-field--full">
              <span class="sg-field__label">Custom robots.txt content</span>
              <textarea class="sg-field__control sg-field__control--textarea" name="seo_robots_txt_override" rows="6"><?= myronEscape((string) ($settings['seo_robots_txt_override'] ?? '')) ?></textarea>
              <span class="sg-field__hint">Leave blank to use the default (allow all crawlers, sitemap reference included). Replace with custom content only if you know what you're doing.</span>
            </label>
          </div>
        </fieldset>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Save Site Settings</button>
        </div>
      </form>
    </section>
  </div>
</div>
<?= MyronAssetPickerView::renderModal('site-settings-logo-asset-picker', $availableImageFiles, $csrfToken, myronBuildAdminUrl('administration.siteSettings'), [
    'assetClass' => 'image',
    'canUpload' => true,
    'title' => 'Choose Site Logo Asset',
]) . "\n" ?>
<?php myronRenderAdminShellEnd(); ?>
