<?php
include('../config/db.php');
include('../includes/auth.php');
require_admin_role();
require_once '../includes/csrf.php';
include('partials/header.php');

$flash = ''; $flashType = 'success';
$brandingFile = __DIR__ . '/user_branding.json';
$branding = file_exists($brandingFile) ? json_decode(file_get_contents($brandingFile), true) : [];

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $branding['title']       = trim($_POST['title'] ?? 'My Vouchers');
    $branding['color']       = preg_match('/^#[0-9a-f]{6}$/i', $_POST['color']??'') ? $_POST['color'] : '#d32f2f';
    $branding['footer_text'] = trim($_POST['footer_text'] ?? '');

    $uploadDir = __DIR__ . '/../uploads/';

    // Header image upload
    if (!empty($_FILES['header_img']['name'])) {
        $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
        $allowedExts = ['jpg','jpeg','png','gif','webp'];
        $ext  = strtolower(pathinfo($_FILES['header_img']['name'], PATHINFO_EXTENSION));
        $mime = $_FILES['header_img']['type'];
        if (!in_array($ext, $allowedExts) || !in_array($mime, $allowed)) {
            $flash = 'Header image: only JPG/PNG/GIF/WEBP allowed.'; $flashType = 'error';
        } elseif ($_FILES['header_img']['size'] > 3 * 1024 * 1024) {
            $flash = 'Header image must be under 3MB.'; $flashType = 'error';
        } else {
            $ext = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/webp'=>'webp'][$mime]??'jpg';
            $fn  = 'header_' . time() . '.' . $ext;
            // Remove old
            if (!empty($branding['header_img']) && file_exists($uploadDir . $branding['header_img']))
                unlink($uploadDir . $branding['header_img']);
            move_uploaded_file($_FILES['header_img']['tmp_name'], $uploadDir . $fn);
            $branding['header_img'] = $fn;
        }
    }

    // Remove header image
    if (isset($_POST['remove_header']) && !empty($branding['header_img'])) {
        if (file_exists($uploadDir . $branding['header_img'])) unlink($uploadDir . $branding['header_img']);
        $branding['header_img'] = '';
    }

    if (empty($flash)) {
        $saved = file_put_contents($brandingFile, json_encode($branding, JSON_PRETTY_PRINT));
        if ($saved === false) {
            $flash = 'Could not save settings — check file permissions on admin/user_branding.json.';
            $flashType = 'error';
        } else {
            $flash = 'User page settings saved.';
        }
    }
}
?>

<div class="pg-title">User Page Settings</div>
<div class="pg-sub">Customise how the user-facing voucher page looks</div>

<?php if ($flash): ?>
<div class="adm-alert adm-alert-<?= $flashType==='error'?'danger':'success' ?>" style="margin-bottom:18px">
  <i class="bi bi-<?= $flashType==='error'?'exclamation-circle-fill':'check-circle-fill' ?>"></i>
  <?= htmlspecialchars($flash) ?>
</div>
<?php endif; ?>

<div class="row g-4">
  <!-- Settings form -->
  <div class="col-lg-6">
    <form method="POST" enctype="multipart/form-data">
      <?php csrf_field(); ?>

      <div class="adm-card mb-3" style="padding:0;overflow:hidden">
        <div class="adm-card-header"><span><i class="bi bi-palette-fill" style="color:var(--accent)"></i> Brand & Colours</span></div>
        <div style="padding:20px">
          <div class="mb-3">
            <label class="frm-label">Page Title</label>
            <input type="text" name="title" class="frm-ctrl" value="<?= htmlspecialchars($branding['title']??'My Vouchers') ?>" placeholder="My Vouchers">
            <div style="font-size:11px;color:var(--muted);margin-top:4px">Shown in the topbar of the user page</div>
          </div>
          <div class="mb-1">
            <label class="frm-label">Brand Colour</label>
            <div style="display:flex;align-items:center;gap:10px">
              <input type="color" name="color" value="<?= htmlspecialchars($branding['color']??'#d32f2f') ?>"
                     style="width:48px;height:40px;border:1px solid var(--border);border-radius:8px;background:var(--surface2);cursor:pointer;padding:4px">
              <input type="text" id="colorHex" class="frm-ctrl" style="font-family:var(--mono);width:110px"
                     value="<?= htmlspecialchars($branding['color']??'#d32f2f') ?>"
                     oninput="syncColor(this.value)">
              <span style="font-size:12px;color:var(--muted)">Used for topbar, hero, and accents</span>
            </div>
          </div>
        </div>
      </div>

      <div class="adm-card mb-3" style="padding:0;overflow:hidden">
        <div class="adm-card-header"><span><i class="bi bi-image-fill" style="color:var(--blue)"></i> Hero Header Image</span></div>
        <div style="padding:20px">
          <?php if (!empty($branding['header_img']) && file_exists(__DIR__.'/../uploads/'.$branding['header_img'])): ?>
          <div style="margin-bottom:14px;position:relative;border-radius:10px;overflow:hidden">
            <img src="../uploads/<?= htmlspecialchars($branding['header_img']) ?>"
                 style="width:100%;height:140px;object-fit:cover;display:block;border-radius:10px;border:1px solid var(--border)">
            <div style="position:absolute;top:8px;right:8px">
              <label style="display:flex;align-items:center;gap:5px;background:rgba(224,82,82,.9);color:#fff;padding:5px 10px;border-radius:7px;font-size:11px;font-weight:700;cursor:pointer">
                <input type="checkbox" name="remove_header" value="1" style="display:none" onchange="this.form.submit()">
                <i class="bi bi-trash-fill"></i> Remove
              </label>
            </div>
          </div>
          <?php else: ?>
          <div style="height:100px;background:var(--surface2);border:2px dashed var(--border);border-radius:10px;display:grid;place-items:center;margin-bottom:14px;color:var(--muted);font-size:13px">
            <span><i class="bi bi-image" style="font-size:24px;display:block;text-align:center;margin-bottom:4px;opacity:.4"></i>No header image set</span>
          </div>
          <?php endif; ?>
          <input type="file" name="header_img" class="frm-ctrl" accept="image/*" style="padding:7px 13px">
          <div style="font-size:11.5px;color:var(--muted);margin-top:7px;background:var(--surface2);border-radius:8px;padding:10px 13px;line-height:1.7">
            <span><i class="bi bi-rulers" style="color:var(--accent)"></i> <strong>Recommended:</strong> 1200 × 400 px (banner/wide)</span> ·
            <span><i class="bi bi-hdd" style="color:var(--yellow)"></i> Max 3 MB</span> ·
            <span><i class="bi bi-file-earmark-image" style="color:var(--green)"></i> JPG, PNG, WEBP, GIF</span>
            <div style="margin-top:4px;font-size:11px">Displayed as a semi-transparent overlay behind the user's name in the hero section.</div>
          </div>
        </div>
      </div>

      <div class="adm-card mb-4" style="padding:0;overflow:hidden">
        <div class="adm-card-header"><span><i class="bi bi-layout-text-window-reverse" style="color:var(--green)"></i> Footer Text</span></div>
        <div style="padding:20px">
          <textarea name="footer_text" class="frm-ctrl" rows="2"
                    placeholder="e.g. © 2025 Perna Events. All rights reserved."><?= htmlspecialchars($branding['footer_text']??'') ?></textarea>
          <div style="font-size:11px;color:var(--muted);margin-top:5px">Shown at the bottom of the user voucher page. Leave blank to hide.</div>
        </div>
      </div>

      <button class="btn-accent" style="width:100%;padding:13px">
        <i class="bi bi-check2-circle"></i> Save Settings
      </button>
    </form>
  </div>

  <!-- Live preview panel -->
  <div class="col-lg-6">
    <div class="adm-card" style="padding:0;overflow:hidden;position:sticky;top:74px">
      <div class="adm-card-header"><span><i class="bi bi-phone-fill" style="color:var(--accent)"></i> Live Preview</span></div>
      <div style="padding:16px">
        <div id="preview-frame" style="border-radius:12px;overflow:hidden;border:1px solid var(--border);background:#f4f5f7;max-width:340px;margin:0 auto">
          <!-- Topbar preview -->
          <div id="prev-topbar" style="background:#111;padding:10px 14px;display:flex;align-items:center;justify-content:space-between;border-bottom:3px solid <?= htmlspecialchars($branding['color']??'#d32f2f') ?>">
            <span style="color:rgba(255,255,255,.5);font-size:10px;font-weight:700">← OUT</span>
            <span id="prev-title" style="color:#fff;font-size:14px;font-weight:900;letter-spacing:1px;text-transform:uppercase;font-family:'Barlow Condensed',sans-serif"><?= htmlspecialchars($branding['title']??'My Vouchers') ?></span>
            <div id="prev-avatar" style="width:26px;height:26px;border-radius:50%;background:<?= htmlspecialchars($branding['color']??'#d32f2f') ?>;display:grid;place-items:center;font-size:12px;font-weight:900;color:#fff">U</div>
          </div>
          <!-- Hero preview -->
          <div id="prev-hero" style="background:<?= htmlspecialchars($branding['color']??'#d32f2f') ?>;padding:18px 14px;text-align:center;position:relative;overflow:hidden">
            <?php if (!empty($branding['header_img'])): ?>
            <img src="../uploads/<?= htmlspecialchars($branding['header_img']) ?>"
                 style="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:.25">
            <?php endif; ?>
            <div style="font-size:9px;font-weight:800;letter-spacing:2px;color:rgba(255,255,255,.55);text-transform:uppercase;position:relative">Welcome back</div>
            <div style="font-size:26px;font-weight:900;color:#fff;text-transform:uppercase;font-family:'Barlow Condensed',sans-serif;position:relative">YOUR NAME</div>
            <div style="font-size:11px;color:rgba(255,255,255,.7);font-weight:700;position:relative">0123456789</div>
          </div>
          <!-- Stats preview -->
          <div style="display:flex;background:#fff;border-bottom:1px solid #eee">
            <?php foreach(['3 Total','2 Valid','1 Used','0 Exp'] as $st): ?>
            <div style="flex:1;padding:8px 4px;text-align:center;border-right:1px solid #eee;font-size:9px;font-weight:700;color:#888"><?= $st ?></div>
            <?php endforeach; ?>
          </div>
          <!-- Sample card preview -->
          <div style="padding:10px">
            <div style="background:#fff;border-radius:10px;overflow:hidden;border:1px solid #e4e6ea;box-shadow:0 1px 4px rgba(0,0,0,.07)">
              <div style="height:60px;background:linear-gradient(135deg,#1c1c2e,#0f3460);display:grid;place-items:center">
                <i class="bi bi-ticket-perforated" style="font-size:24px;color:rgba(255,255,255,.15)"></i>
              </div>
              <div style="padding:10px 12px;display:flex;justify-content:space-between;align-items:flex-end">
                <div>
                  <div style="font-size:13px;font-weight:900;text-transform:uppercase;font-family:'Barlow Condensed',sans-serif">VOUCHER NAME</div>
                  <div style="font-size:9px;color:#888;margin-top:2px">Expires 31 Dec 2025</div>
                </div>
                <div id="prev-qr-icon" style="width:30px;height:30px;border-radius:50%;background:color-mix(in srgb,<?= htmlspecialchars($branding['color']??'#d32f2f') ?> 12%,transparent);display:grid;place-items:center;color:<?= htmlspecialchars($branding['color']??'#d32f2f') ?>;font-size:14px">
                  <i class="bi bi-qr-code"></i>
                </div>
              </div>
            </div>
          </div>
          <?php if (!empty($branding['footer_text'])): ?>
          <div id="prev-footer" style="padding:10px;text-align:center;font-size:10px;color:#888;font-weight:600;border-top:1px solid #e4e6ea"><?= htmlspecialchars($branding['footer_text']) ?></div>
          <?php endif; ?>
        </div>
        <div style="text-align:center;margin-top:12px">
          <a href="../user/index.php" target="_blank" class="btn-ghost" style="font-size:12px;padding:7px 16px">
            <i class="bi bi-box-arrow-up-right"></i> Open User Page
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
// Sync color picker and text input
document.querySelector('input[type=color]').addEventListener('input', function(){
  document.getElementById('colorHex').value = this.value;
  applyColor(this.value);
});
function syncColor(val){
  if(/^#[0-9a-f]{6}$/i.test(val)){
    document.querySelector('input[type=color]').value=val;
    applyColor(val);
  }
}
function applyColor(c){
  document.getElementById('prev-topbar').style.borderBottomColor = c;
  document.getElementById('prev-hero').style.background = c;
  document.getElementById('prev-avatar').style.background = c;
  document.getElementById('prev-qr-icon').style.color = c;
}

// Sync title
document.querySelector('input[name=title]').addEventListener('input', function(){
  document.getElementById('prev-title').textContent = this.value || 'My Vouchers';
});
</script>

<?php include('partials/footer.php'); ?>
