<?php

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

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

$admin = Auth::requireAdminTierView();
$isDemo = $admin['role'] === 'demo';

$flash = null;
$uploadDir = ROOT_PATH . '/public/uploads/branding';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($isDemo) {
        http_response_code(403);
        die(I18n::t('branding.error_demo_readonly'));
    }
    Csrf::requireValid();

    $siteName = trim($_POST['site_name'] ?? '');
    if ($siteName === '') {
        $flash = ['type' => 'error', 'message' => I18n::t('branding.flash.site_name_empty')];
    } else {
        Settings::set('site_name', $siteName);
        AuditLog::log($admin['id'], 'branding_name_updated', $siteName);
        $flash = ['type' => 'success', 'message' => I18n::t('branding.flash.saved')];
    }

    if (!empty($_FILES['favicon']) && $_FILES['favicon']['error'] !== UPLOAD_ERR_NO_FILE) {
        $result = ImageUpload::save($_FILES['favicon'], $uploadDir);
        if ($result['ok']) {
            $oldPath = Settings::faviconPath();
            Settings::set('favicon_path', '/uploads/branding/' . $result['filename']);
            AuditLog::log($admin['id'], 'branding_favicon_updated', $result['filename']);
            if ($oldPath) {
                @unlink(ROOT_PATH . '/public' . $oldPath);
            }
            $flash = ['type' => 'success', 'message' => I18n::t('branding.flash.saved')];
        } else {
            $flash = ['type' => 'error', 'message' => sprintf(I18n::t('branding.flash.favicon_error'), $result['error'])];
        }
    }

    if (!empty($_FILES['welcome_hero']) && $_FILES['welcome_hero']['error'] !== UPLOAD_ERR_NO_FILE) {
        $result = ImageUpload::save($_FILES['welcome_hero'], $uploadDir);
        if ($result['ok']) {
            $oldPath = Settings::welcomeHeroPath();
            Settings::set('welcome_hero_path', '/uploads/branding/' . $result['filename']);
            AuditLog::log($admin['id'], 'branding_welcome_hero_updated', $result['filename']);
            if ($oldPath) {
                @unlink(ROOT_PATH . '/public' . $oldPath);
            }
            $flash = ['type' => 'success', 'message' => I18n::t('branding.flash.saved')];
        } else {
            $flash = ['type' => 'error', 'message' => sprintf(I18n::t('branding.flash.welcome_hero_error'), $result['error'])];
        }
    }
}

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

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

<form method="post" enctype="multipart/form-data">
  <?= Csrf::field() ?>
  <fieldset <?= $isDemo ? 'disabled' : '' ?> style="border:0; margin:0; padding:0;">

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('branding.site_name_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('branding.site_name_hint')) ?></p>
    <div class="field">
      <input type="text" name="site_name" value="<?= Helpers::e(Settings::siteName()) ?>" required maxlength="64">
    </div>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('branding.favicon_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('branding.favicon_hint')) ?></p>
    <?php if (Settings::faviconPath()): ?>
      <div style="display:flex; align-items:center; gap:12px; margin-bottom:14px;">
        <img src="<?= Helpers::e(Settings::faviconPath()) ?>" alt="" style="width:40px; height:40px; border-radius:8px; border:1px solid var(--line); background:var(--bg-void); object-fit:contain;">
        <span style="font-size:12px; color:var(--text-muted);"><?= Helpers::e(I18n::t('branding.favicon_current')) ?></span>
      </div>
    <?php endif; ?>
    <label class="cover-upload" style="aspect-ratio:auto; padding:16px; cursor:pointer;">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="9" cy="10" r="2"/><path d="M21 16l-5.5-5.5L7 19"/></svg>
      <span id="favicon-filename"><?= Helpers::e(I18n::t('branding.favicon_upload_prompt')) ?></span>
      <input type="file" name="favicon" accept="image/png,image/jpeg,image/webp" style="display:none;" onchange="document.getElementById('favicon-filename').textContent = this.files[0]?.name || <?= json_encode(I18n::t('branding.favicon_upload_prompt'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;">
    </label>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('branding.welcome_hero_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('branding.welcome_hero_hint')) ?></p>
    <?php if (Settings::welcomeHeroPath()): ?>
      <div style="display:flex; align-items:center; gap:12px; margin-bottom:14px;">
        <img src="<?= Helpers::e(Settings::welcomeHeroPath()) ?>" alt="" style="width:56px; height:56px; border-radius:8px; border:1px solid var(--line); background:var(--bg-void); object-fit:contain;">
        <span style="font-size:12px; color:var(--text-muted);"><?= Helpers::e(I18n::t('branding.welcome_hero_current')) ?></span>
      </div>
    <?php endif; ?>
    <label class="cover-upload" style="aspect-ratio:auto; padding:16px; cursor:pointer;">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="9" cy="10" r="2"/><path d="M21 16l-5.5-5.5L7 19"/></svg>
      <span id="welcome-hero-filename"><?= Helpers::e(I18n::t('branding.welcome_hero_upload_prompt')) ?></span>
      <input type="file" name="welcome_hero" accept="image/png,image/jpeg,image/webp" style="display:none;" onchange="document.getElementById('welcome-hero-filename').textContent = this.files[0]?.name || <?= json_encode(I18n::t('branding.welcome_hero_upload_prompt'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;">
    </label>
  </div>

  <div class="form-actions">
    <button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('branding.save_button')) ?></button>
  </div>
  </fieldset>
</form>

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