<?php
/**
 * Content Builder — site settings (public theme header/footer/branding).
 */
require_once dirname(__DIR__, 3) . '/config.php';

Auth::require();
Auth::requirePerm('content.manage_types');

$pageTitle  = 'Site Settings';
$currentNav = 'content-site';

$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $flash = ['type'=>'error','msg'=>'Security check failed.'];
    } else {
        ContentBuilderAPI::setSiteSetting('theme',        $_POST['theme'] ?? 'clean-corporate');
        ContentBuilderAPI::setSiteSetting('layout_width', $_POST['layout_width'] ?? 'boxed');
        ContentBuilderAPI::setSiteSetting('type_scale',   $_POST['type_scale'] ?? 'm');
        ContentBuilderAPI::setSiteSetting('btn_shape',    $_POST['btn_shape'] ?? 'rounded');
        ContentBuilderAPI::setSiteSetting('site_name',    trim($_POST['site_name'] ?? ''));
        ContentBuilderAPI::setSiteSetting('logo_url',     trim($_POST['logo_url'] ?? ''));
        ContentBuilderAPI::setSiteSetting('tagline',      trim($_POST['tagline'] ?? ''));
        ContentBuilderAPI::setSiteSetting('accent_color', trim($_POST['accent_color'] ?? '#2563eb'));
        ContentBuilderAPI::setSiteSetting('footer_text',  trim($_POST['footer_text'] ?? ''));
        ContentBuilderAPI::setSiteSetting('show_header',  empty($_POST['show_header']) ? '0' : '1');
        ContentBuilderAPI::setSiteSetting('show_footer',  empty($_POST['show_footer']) ? '0' : '1');
        ContentBuilderAPI::setSiteSetting('header_style', $_POST['header_style'] ?? 'simple');
        ContentBuilderAPI::setSiteSetting('footer_style', $_POST['footer_style'] ?? 'simple');
        ContentBuilderAPI::setSiteSetting('palette',      $_POST['palette'] ?? '');
        ContentBuilderAPI::setSiteSetting('font_pairing', $_POST['font_pairing'] ?? '');
        ContentBuilderAPI::setSiteSetting('radius',       (string)(int)($_POST['radius'] ?? 10));
        $flash = ['type'=>'success','msg'=>'Settings saved.'];
    }
}

$siteName   = ContentBuilderAPI::getSiteSetting('site_name', '');
$tagline    = ContentBuilderAPI::getSiteSetting('tagline', '');
$accent     = ContentBuilderAPI::getSiteSetting('accent_color', '#2563eb');
$footerText = ContentBuilderAPI::getSiteSetting('footer_text', '');
$showHeader = ContentBuilderAPI::getSiteSetting('show_header', '1') !== '0';
$showFooter = ContentBuilderAPI::getSiteSetting('show_footer', '1') !== '0';
$headerStyle= ContentBuilderAPI::getSiteSetting('header_style', 'simple');
$footerStyle= ContentBuilderAPI::getSiteSetting('footer_style', 'simple');
$palette    = ContentBuilderAPI::getSiteSetting('palette', '');
$fontPair   = ContentBuilderAPI::getSiteSetting('font_pairing', '');
$radiusRaw  = ContentBuilderAPI::getSiteSetting('radius', '');
$radius     = $radiusRaw !== '' ? (int)$radiusRaw : (int)(Branding::resolve()['radius']);
$palettes   = Branding::palettes();
$fonts      = Branding::fontPairings();
$logoUrl    = ContentBuilderAPI::getSiteSetting('logo_url', '');
$cbHasMedia = PluginLoader::isActive('media-library');
$theme      = ContentBuilderAPI::getSiteSetting('theme', 'clean-corporate');
$themes     = Branding::themes();
$layoutWidth= ContentBuilderAPI::getSiteSetting('layout_width', 'boxed');
$typeScale  = ContentBuilderAPI::getSiteSetting('type_scale', 'm');
$btnShape   = ContentBuilderAPI::getSiteSetting('btn_shape', 'rounded');

$headerMenu = ContentBuilderAPI::getMenuByLocation('header');
$footerMenu = ContentBuilderAPI::getMenuByLocation('footer');

require SLATE_ROOT . '/admin/partials/header.php';
?>
<?php if ($cbHasMedia): ?>
    <link rel="stylesheet" href="<?= e(SLATE_URL) ?>/plugins/media-library/assets/css/picker.css">
    <script src="<?= e(SLATE_URL) ?>/plugins/media-library/assets/js/picker.js"></script>
<?php endif; ?>

<?php slate_breadcrumbs([
    ['label' => 'Dashboard', 'href' => SLATE_URL . '/admin/'],
    ['label' => 'Site Settings'],
]); ?>

<div class="page-header">
    <div><h1>Site Settings</h1>
    <p class="page-header-sub">Branding and the global header/footer for your public pages.</p></div>
</div>

<?php if ($flash): ?>
    <div class="alert alert-<?= e($flash['type']) ?>" role="status"><?= e($flash['msg']) ?></div>
<?php endif; ?>

<form method="post">
    <?= csrf_field() ?>

    <div class="card">
        <div class="card-header"><h2>Theme preset</h2></div>
        <p class="text-sub">Pick a whole look in one click — sets fonts, colors, backgrounds, and card style together. You can fine-tune below.</p>
        <div class="cb-theme-grid">
            <?php foreach ($themes as $key => $th): ?>
                <label class="cb-theme-card <?= $theme===$key?'is-active':'' ?>">
                    <input type="radio" name="theme" value="<?= e($key) ?>" <?= $theme===$key?'checked':'' ?> hidden>
                    <span class="cb-theme-swatch" style="background:<?= e($th['page_bg']) ?>">
                        <span style="background:<?= e($th['accent']) ?>"></span>
                        <span style="background:<?= e($th['surface']) ?>"></span>
                    </span>
                    <span class="cb-theme-name"><?= e($th['label']) ?></span>
                </label>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="card">
        <div class="card-header"><h2>Branding</h2></div>
        <div class="field">
            <label class="field-label" for="site_name">Site name</label>
            <input type="text" id="site_name" name="site_name" value="<?= e($siteName) ?>"
                   placeholder="Chef Gregory's">
        </div>
        <div class="field">
            <label class="field-label" for="logo_url">Logo image (optional — replaces text name in header)</label>
            <input type="text" id="logo_url" name="logo_url" value="<?= e($logoUrl) ?>"
                   placeholder="https://… or pick from library">
            <?php if ($cbHasMedia): ?>
                <button type="button" class="btn btn-sm mt-2" id="cb-logo-pick">Choose from library</button>
            <?php endif; ?>
            <?php if ($logoUrl): ?>
                <div class="mt-2"><img src="<?= e($logoUrl) ?>" alt="" style="max-height:48px;border:1px solid #e4e7ec;border-radius:6px;padding:4px;background:#fff"></div>
            <?php endif; ?>
        </div>
        <div class="field">
            <label class="field-label" for="tagline">Tagline</label>
            <input type="text" id="tagline" name="tagline" value="<?= e($tagline) ?>"
                   placeholder="Fine dining, delivered">
        </div>

        <div class="field">
            <label class="field-label">Color palette <span class="text-muted">(optional — overrides the theme's color)</span></label>
            <div class="cb-swatch-grid">
                <label class="cb-swatch <?= $palette===''?'is-active':'' ?>">
                    <input type="radio" name="palette" value="" <?= $palette===''?'checked':'' ?> hidden>
                    <span class="cb-swatch-dot" style="background:linear-gradient(135deg,#999,#ddd)"></span>
                    <span class="cb-swatch-label">Follow theme</span>
                </label>
                <?php foreach ($palettes as $key => $p): ?>
                    <label class="cb-swatch <?= $palette===$key?'is-active':'' ?>">
                        <input type="radio" name="palette" value="<?= e($key) ?>" <?= $palette===$key?'checked':'' ?> hidden>
                        <span class="cb-swatch-dot" style="background:<?= e($p['accent']) ?>"></span>
                        <span class="cb-swatch-label"><?= e($p['label']) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="field">
            <label class="field-label" for="accent_color">Custom accent (overrides palette — leave default to use palette)</label>
            <input type="text" id="accent_color" name="accent_color"
                   value="<?= e(ContentBuilderAPI::getSiteSetting('accent_color','')) ?>"
                   placeholder="#2563eb (optional)">
        </div>

        <div class="field">
            <label class="field-label" for="font_pairing">Font pairing (system fonts — zero load time)</label>
            <select id="font_pairing" name="font_pairing" class="field-input">
                <option value="" <?= $fontPair===''?'selected':'' ?>>Follow theme</option>
                <?php foreach ($fonts as $key => $f): ?>
                    <option value="<?= e($key) ?>" <?= $fontPair===$key?'selected':'' ?>><?= e($f['label']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="field">
            <label class="field-label" for="radius">Corner roundness: <span id="cb-radius-val"><?= $radius ?></span>px</label>
            <input type="range" id="radius" name="radius" min="0" max="24" value="<?= $radius ?>"
                   oninput="document.getElementById('cb-radius-val').textContent=this.value">
        </div>
    </div>

    <div class="card">
        <div class="card-header"><h2>Layout &amp; type</h2></div>
        <div class="field">
            <label class="field-label" for="layout_width">Default page width</label>
            <select id="layout_width" name="layout_width" class="field-input">
                <option value="boxed"  <?= $layoutWidth==='boxed'?'selected':'' ?>>Boxed (centered, comfortable)</option>
                <option value="full"   <?= $layoutWidth==='full'?'selected':'' ?>>Full (wider content)</option>
                <option value="canvas" <?= $layoutWidth==='canvas'?'selected':'' ?>>Canvas (edge to edge)</option>
            </select>
            <small class="text-muted">Each page can override this in its editor.</small>
        </div>
        <div class="field">
            <label class="field-label" for="type_scale">Font size scale</label>
            <select id="type_scale" name="type_scale" class="field-input">
                <option value="s"  <?= $typeScale==='s'?'selected':'' ?>>Small</option>
                <option value="m"  <?= $typeScale==='m'?'selected':'' ?>>Medium (default)</option>
                <option value="l"  <?= $typeScale==='l'?'selected':'' ?>>Large</option>
                <option value="xl" <?= $typeScale==='xl'?'selected':'' ?>>Extra large</option>
            </select>
        </div>
        <div class="field">
            <label class="field-label" for="btn_shape">Button style</label>
            <select id="btn_shape" name="btn_shape" class="field-input">
                <option value="rounded" <?= $btnShape==='rounded'?'selected':'' ?>>Rounded</option>
                <option value="square"  <?= $btnShape==='square'?'selected':'' ?>>Square</option>
                <option value="pill"    <?= $btnShape==='pill'?'selected':'' ?>>Pill</option>
            </select>
        </div>
    </div>

    <div class="card">
        <div class="card-header"><h2>Header</h2></div>
        <div class="field">
            <label class="field-label" for="header_style">Header preset</label>
            <select id="header_style" name="header_style" class="field-input">
                <option value="simple"   <?= $headerStyle==='simple'?'selected':'' ?>>Simple (brand left, nav right)</option>
                <option value="centered" <?= $headerStyle==='centered'?'selected':'' ?>>Centered (brand and nav stacked, centered)</option>
                <option value="minimal"  <?= $headerStyle==='minimal'?'selected':'' ?>>Minimal (small brand, thin border)</option>
            </select>
        </div>
        <div class="field">
            <label class="cb-term">
                <input type="checkbox" name="show_header" value="1" <?= $showHeader?'checked':'' ?>>
                Show header on public pages
            </label>
        </div>
        <p class="text-sub">
            Header navigation:
            <?php if ($headerMenu): ?>
                <strong><?= e($headerMenu['name']) ?></strong> (<?= count($headerMenu['items']) ?> items).
            <?php else: ?>
                none assigned.
            <?php endif; ?>
            <a href="menus.php">Manage menus →</a>
        </p>
    </div>

    <div class="card">
        <div class="card-header"><h2>Footer</h2></div>
        <div class="field">
            <label class="cb-term">
                <input type="checkbox" name="show_footer" value="1" <?= $showFooter?'checked':'' ?>>
                Show footer on public pages
            </label>
        </div>
        <div class="field">
            <label class="field-label" for="footer_style">Footer preset</label>
            <select id="footer_style" name="footer_style" class="field-input">
                <option value="simple"  <?= $footerStyle==='simple'?'selected':'' ?>>Simple (centered nav + copyright)</option>
                <option value="minimal" <?= $footerStyle==='minimal'?'selected':'' ?>>Minimal (copyright only)</option>
            </select>
        </div>
        <div class="field">
            <label class="field-label" for="footer_text">Footer text</label>
            <input type="text" id="footer_text" name="footer_text" value="<?= e($footerText) ?>"
                   placeholder="© 2026 Chef Gregory's. All rights reserved.">
            <small class="text-muted">Leave blank for an automatic copyright line.</small>
        </div>
        <p class="text-sub">
            Footer navigation:
            <?php if ($footerMenu): ?>
                <strong><?= e($footerMenu['name']) ?></strong> (<?= count($footerMenu['items']) ?> items).
            <?php else: ?>
                none assigned.
            <?php endif; ?>
            <a href="menus.php">Manage menus →</a>
        </p>
    </div>

    <button type="submit" class="btn btn-primary">Save settings</button>
</form>

<script>
(function(){
  var swatches = document.querySelectorAll('.cb-swatch');
  swatches.forEach(function(s){
    s.addEventListener('click', function(){
      swatches.forEach(function(x){ x.classList.remove('is-active'); });
      s.classList.add('is-active');
    });
  });
  var themeCards = document.querySelectorAll('.cb-theme-card');
  themeCards.forEach(function(c){
    c.addEventListener('click', function(){
      themeCards.forEach(function(x){ x.classList.remove('is-active'); });
      c.classList.add('is-active');
    });
  });
  var logoBtn = document.getElementById('cb-logo-pick');
  if (logoBtn && window.MediaPicker) {
    logoBtn.addEventListener('click', function(){
      window.MediaPicker.open({ mode:'single', onPick:function(path){
        document.getElementById('logo_url').value = path;
      }});
    });
  }
})();
</script>

<?php require SLATE_ROOT . '/admin/partials/footer.php'; ?>
