<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/media.php';
require_once dirname(__DIR__) . '/lib/admin_layout.php';

require_admin();
$tenantId = current_tenant_id();
$flash = '';

$stmt = db()->prepare('SELECT * FROM page_settings WHERE tenant_id = ?');
$stmt->execute([$tenantId]);
$s = $stmt->fetch() ?: [];

$mediaStmt = db()->prepare('SELECT * FROM media_assets WHERE tenant_id = ? ORDER BY id DESC');
$mediaStmt->execute([$tenantId]);
$media = $mediaStmt->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $social = [
        'instagram' => trim((string) ($_POST['social_instagram'] ?? '')),
        'facebook' => trim((string) ($_POST['social_facebook'] ?? '')),
        'tiktok' => trim((string) ($_POST['social_tiktok'] ?? '')),
    ];
    $sql = 'INSERT INTO page_settings (
        tenant_id, hero_headline, hero_subheadline, hero_media_path, cta_text, cta_link,
        business_name, address, phone, social_links, maps_embed, seo_title, seo_description,
        announcement_enabled, announcement_text, announcement_bg_color
      ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
      ON DUPLICATE KEY UPDATE
        hero_headline=VALUES(hero_headline), hero_subheadline=VALUES(hero_subheadline),
        hero_media_path=VALUES(hero_media_path), cta_text=VALUES(cta_text), cta_link=VALUES(cta_link),
        business_name=VALUES(business_name), address=VALUES(address), phone=VALUES(phone),
        social_links=VALUES(social_links), maps_embed=VALUES(maps_embed),
        seo_title=VALUES(seo_title), seo_description=VALUES(seo_description),
        announcement_enabled=VALUES(announcement_enabled), announcement_text=VALUES(announcement_text),
        announcement_bg_color=VALUES(announcement_bg_color)';
    db()->prepare($sql)->execute([
        $tenantId,
        trim((string) ($_POST['hero_headline'] ?? '')),
        trim((string) ($_POST['hero_subheadline'] ?? '')),
        trim((string) ($_POST['hero_media_path'] ?? '')),
        trim((string) ($_POST['cta_text'] ?? 'Book Now')),
        trim((string) ($_POST['cta_link'] ?? '#book')),
        trim((string) ($_POST['business_name'] ?? '')),
        trim((string) ($_POST['address'] ?? '')),
        trim((string) ($_POST['phone'] ?? '')),
        json_encode($social),
        trim((string) ($_POST['maps_embed'] ?? '')),
        trim((string) ($_POST['seo_title'] ?? '')),
        trim((string) ($_POST['seo_description'] ?? '')),
        isset($_POST['announcement_enabled']) ? 1 : 0,
        trim((string) ($_POST['announcement_text'] ?? '')),
        trim((string) ($_POST['announcement_bg_color'] ?? '#1a1a1a')),
    ]);
    $flash = 'Page content saved.';
    $stmt->execute([$tenantId]);
    $s = $stmt->fetch() ?: [];
}

$social = json_decode((string) ($s['social_links'] ?? '{}'), true) ?: [];

admin_header('Page Content', 'content');
if ($flash): ?><div class="flash"><?= htmlspecialchars($flash) ?></div><?php endif; ?>

<form method="post">
  <div class="panel">
    <h2>Homepage hero</h2>
    <div class="grid-2">
      <div>
        <label>Main headline</label>
        <input type="text" name="hero_headline" placeholder="Title Here" value="<?= htmlspecialchars((string) ($s['hero_headline'] ?? '')) ?>">
        <label>Subheadline</label>
        <textarea name="hero_subheadline"><?= htmlspecialchars((string) ($s['hero_subheadline'] ?? '')) ?></textarea>
      </div>
      <div>
        <label>Background media</label>
        <p class="muted" style="margin:.25rem 0 .75rem">Click a library thumbnail to select, or paste an external image/video URL below. Upload new files in <a href="<?= APP_BASE ?>/admin/media.php">Media</a>.</p>
        <input type="hidden" name="hero_media_path" id="hero_media_path" value="<?= htmlspecialchars((string) ($s['hero_media_path'] ?? '')) ?>">
        <div class="picker-grid" id="hero-picker">
          <button type="button" class="picker-item <?= ($s['hero_media_path'] ?? '') === '' ? 'selected' : '' ?>" data-path="">
            <div style="aspect-ratio:16/9;display:grid;place-items:center;color:var(--muted);font-size:.8rem;background:var(--panel-2)">None</div>
          </button>
          <?php foreach ($media as $m):
            $path = $m['optimized_path'] ?: $m['file_path'];
            $url = media_public_url($path);
            $sel = (($s['hero_media_path'] ?? '') === $path) ? 'selected' : '';
            $isVideo = str_starts_with((string) ($m['mime_type'] ?? ''), 'video/');
            ?>
            <button type="button" class="picker-item <?= $sel ?>" data-path="<?= htmlspecialchars($path) ?>" title="<?= htmlspecialchars((string) ($m['original_name'] ?? $path)) ?>">
              <?php if ($isVideo): ?>
                <video src="<?= htmlspecialchars($url) ?>" muted></video>
              <?php else: ?>
                <img src="<?= htmlspecialchars($url) ?>" alt="">
              <?php endif; ?>
              <span class="check">✓</span>
            </button>
          <?php endforeach; ?>
        </div>
        <label>Or external URL (optional override)</label>
        <input type="text" id="hero_media_url" placeholder="https://… or leave blank to use picker" value="<?php
          $cur = (string) ($s['hero_media_path'] ?? '');
          echo preg_match('#^https?://#i', $cur) ? htmlspecialchars($cur) : '';
        ?>">
        <label>CTA button text</label>
        <input type="text" name="cta_text" value="<?= htmlspecialchars((string) ($s['cta_text'] ?? 'Book Now')) ?>">
        <label>CTA link target</label>
        <input type="text" name="cta_link" value="<?= htmlspecialchars((string) ($s['cta_link'] ?? '#book')) ?>">
      </div>
    </div>
  </div>

  <div class="panel">
    <h2>Business metadata & SEO</h2>
    <div class="grid-2">
      <div>
        <label>Business name</label>
        <input type="text" name="business_name" placeholder="Company Name Here" value="<?= htmlspecialchars((string) ($s['business_name'] ?? '')) ?>">
        <label>Address</label>
        <textarea name="address"><?= htmlspecialchars((string) ($s['address'] ?? '')) ?></textarea>
        <label>Phone</label>
        <input type="text" name="phone" value="<?= htmlspecialchars((string) ($s['phone'] ?? '')) ?>">
        <label>Instagram URL</label>
        <input type="url" name="social_instagram" value="<?= htmlspecialchars((string) ($social['instagram'] ?? '')) ?>">
        <label>Facebook URL</label>
        <input type="url" name="social_facebook" value="<?= htmlspecialchars((string) ($social['facebook'] ?? '')) ?>">
        <label>TikTok URL</label>
        <input type="url" name="social_tiktok" value="<?= htmlspecialchars((string) ($social['tiktok'] ?? '')) ?>">
      </div>
      <div>
        <label>Google Maps embed URL / iframe src</label>
        <textarea name="maps_embed" placeholder="https://www.google.com/maps/embed?..."><?= htmlspecialchars((string) ($s['maps_embed'] ?? '')) ?></textarea>
        <label>SEO meta title</label>
        <input type="text" name="seo_title" placeholder="Company Name Here" value="<?= htmlspecialchars((string) ($s['seo_title'] ?? '')) ?>">
        <label>SEO meta description</label>
        <textarea name="seo_description"><?= htmlspecialchars((string) ($s['seo_description'] ?? '')) ?></textarea>
      </div>
    </div>
  </div>

  <div class="panel">
    <h2>Global announcement bar</h2>
    <label style="display:flex;gap:.5rem;align-items:center;color:var(--text)">
      <input type="checkbox" name="announcement_enabled" <?= !empty($s['announcement_enabled']) ? 'checked' : '' ?>>
      Announcement bar ON
    </label>
    <label style="margin-top:.75rem">Announcement text</label>
    <input type="text" name="announcement_text" value="<?= htmlspecialchars((string) ($s['announcement_text'] ?? '')) ?>">
    <label>Background color</label>
    <input type="color" name="announcement_bg_color" value="<?= htmlspecialchars((string) ($s['announcement_bg_color'] ?? '#1a1a1a')) ?>">
  </div>

  <button class="btn" type="submit">Save page content</button>
</form>
<script>
(function(){
  const hidden = document.getElementById('hero_media_path');
  const urlInput = document.getElementById('hero_media_url');
  document.querySelectorAll('#hero-picker .picker-item').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('#hero-picker .picker-item').forEach(b => b.classList.remove('selected'));
      btn.classList.add('selected');
      hidden.value = btn.dataset.path || '';
      if (urlInput) urlInput.value = '';
    });
  });
  if (urlInput) {
    urlInput.addEventListener('input', () => {
      const v = urlInput.value.trim();
      if (v) {
        hidden.value = v;
        document.querySelectorAll('#hero-picker .picker-item').forEach(b => b.classList.remove('selected'));
      }
    });
  }
})();
</script>
<?php admin_footer(); ?>
