<?php
session_start();
$page_title = 'Customer Feedback';
$active_nav = 'feedback';
include("includes/header.php");
if (!$is_admin) { header("Location: dashboard.php"); exit; }

require_once __DIR__ . '/../customer/includes/feedback_lib.php';
feedback_ensure_tables($conn);

$rid = (int)$__rid;
$success = $error = "";

// ── Save configuration ──────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $enabled       = isset($_POST['enabled']) ? 1 : 0;
    $allow_comment = isset($_POST['allow_comment']) ? 1 : 0;
    $frequency_n   = max(1, (int)($_POST['frequency_n'] ?? 1));
    $intro_title   = trim($_POST['intro_title'] ?? '') ?: 'How was your experience?';
    $intro_sub     = trim($_POST['intro_subtitle'] ?? '') ?: 'Your feedback helps us improve your dining experience.';

    $cats = array_values(array_filter(array_map('trim', $_POST['categories'] ?? []), fn($v) => $v !== ''));
    $tags = array_values(array_filter(array_map('trim', $_POST['tags'] ?? []), fn($v) => $v !== ''));
    if (!$cats) $cats = ['Food Quality', 'Service', 'Wait Time'];

    $cats_json = json_encode(array_slice($cats, 0, 8));
    $tags_json = json_encode(array_slice($tags, 0, 12));

    $st = $conn->prepare(
        "INSERT INTO restaurant_feedback_settings
            (restaurant_id, enabled, frequency_n, intro_title, intro_subtitle, categories, tags, allow_comment)
         VALUES (?,?,?,?,?,?,?,?)
         ON DUPLICATE KEY UPDATE enabled=VALUES(enabled), frequency_n=VALUES(frequency_n),
            intro_title=VALUES(intro_title), intro_subtitle=VALUES(intro_subtitle),
            categories=VALUES(categories), tags=VALUES(tags), allow_comment=VALUES(allow_comment)"
    );
    $st->bind_param("iiissssi", $rid, $enabled, $frequency_n, $intro_title, $intro_sub, $cats_json, $tags_json, $allow_comment);
    if ($st->execute()) $success = "Feedback settings saved.";
    else $error = "Could not save your settings. Please try again.";
}

$s = rf_get_settings($conn, $rid);

// ── Results / analytics ─────────────────────────────────────────────────────
$total = 0; $overall_sum = 0; $overall_cnt = 0;
$cat_sum = []; $cat_cnt = []; $tag_counts = []; $recent = [];
if ($res = @$conn->query(
    "SELECT rf.overall_rating, rf.category_ratings, rf.tags, rf.comment, rf.created_at, u.name AS user_name
     FROM restaurant_feedback rf LEFT JOIN users u ON rf.user_id=u.id
     WHERE rf.restaurant_id=$rid AND rf.status='submitted'
     ORDER BY rf.created_at DESC"
)) {
    while ($row = $res->fetch_assoc()) {
        $total++;
        if ($row['overall_rating'] !== null && (int)$row['overall_rating'] > 0) { $overall_sum += (int)$row['overall_rating']; $overall_cnt++; }
        $cr = json_decode($row['category_ratings'] ?? '', true);
        if (is_array($cr)) foreach ($cr as $label => $v) { $v = (int)$v; if ($v > 0) { $cat_sum[$label] = ($cat_sum[$label] ?? 0) + $v; $cat_cnt[$label] = ($cat_cnt[$label] ?? 0) + 1; } }
        $tg = json_decode($row['tags'] ?? '', true);
        if (is_array($tg)) foreach ($tg as $t) { $tag_counts[$t] = ($tag_counts[$t] ?? 0) + 1; }
        if (trim((string)$row['comment']) !== '' && count($recent) < 8) $recent[] = $row;
    }
}
$avg_overall = $overall_cnt ? round($overall_sum / $overall_cnt, 1) : 0;
arsort($tag_counts);

function star_row($val) {
    $full = floor($val); $html = '';
    for ($i = 1; $i <= 5; $i++) {
        $color = $i <= $full ? 'var(--warning,#F59E0B)' : 'var(--border-dark,#CBD5E1)';
        $html .= '<svg width="15" height="15" viewBox="0 0 24 24" fill="'.$color.'" style="vertical-align:-2px"><path d="M12 2l2.9 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l7.1-1.01L12 2z"/></svg>';
    }
    return $html;
}
?>

<style>
.fbcfg-grid { display:grid; grid-template-columns:1.3fr 1fr; gap:20px; align-items:start; }
@media (max-width:900px){ .fbcfg-grid { grid-template-columns:1fr; } }
.switch { position:relative; display:inline-block; width:46px; height:26px; }
.switch input { opacity:0; width:0; height:0; }
.switch .sl { position:absolute; inset:0; background:var(--border-dark,#CBD5E1); border-radius:30px; transition:.2s; cursor:pointer; }
.switch .sl:before { content:''; position:absolute; width:20px; height:20px; left:3px; bottom:3px; background:#fff; border-radius:50%; transition:.2s; }
.switch input:checked + .sl { background:var(--primary); }
.switch input:checked + .sl:before { transform:translateX(20px); }
.row-between { display:flex; align-items:center; justify-content:space-between; gap:12px; }
.freq-opts { display:flex; gap:8px; flex-wrap:wrap; margin-top:8px; }
.freq-opt { border:1.5px solid var(--border); border-radius:10px; padding:8px 14px; font-size:.85rem; font-weight:600; cursor:pointer; background:#fff; }
.freq-opt.on { border-color:var(--primary); background:var(--primary-bg); color:var(--primary); }
.chip-edit { display:flex; flex-wrap:wrap; gap:8px; margin-top:8px; }
.chip-edit .ce { display:flex; align-items:center; gap:6px; background:var(--bg,#F1F5F9); border:1px solid var(--border); border-radius:10px; padding:6px 8px 6px 12px; font-size:.84rem; }
.chip-edit .ce button { border:none; background:none; cursor:pointer; color:var(--text-muted); font-size:1rem; line-height:1; padding:0 2px; }
.chip-add { display:flex; gap:8px; margin-top:10px; }
.chip-add input { flex:1; }
.stat-tile { background:var(--bg,#F8FAFC); border:1px solid var(--border); border-radius:12px; padding:14px 16px; }
.stat-tile .v { font-size:1.5rem; font-weight:800; letter-spacing:-.02em; }
.stat-tile .l { font-size:.76rem; color:var(--text-muted); font-weight:600; }
.bar-row { display:flex; align-items:center; gap:10px; margin-bottom:8px; font-size:.84rem; }
.bar-row .bn { width:120px; flex-shrink:0; color:var(--text-muted); }
.bar-track { flex:1; height:8px; background:var(--bg,#EEF1F5); border-radius:5px; overflow:hidden; }
.bar-fill { height:100%; background:var(--primary); border-radius:5px; }
</style>

<div style="margin-bottom:22px">
  <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Customer Feedback</h1>
  <p style="color:var(--text-muted);font-size:.875rem">Decide what customers are asked after their meal and when they're asked</p>
</div>

<?php if ($success): ?><div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><?php echo $success; ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

<form method="POST" class="fbcfg-grid">
  <!-- ── LEFT: configuration ── -->
  <div>
    <div class="card" style="margin-bottom:16px">
      <div class="card-header"><h3>Status &amp; Schedule</h3></div>
      <div class="card-body">
        <div class="row-between" style="margin-bottom:18px">
          <div>
            <div style="font-weight:700;font-size:.92rem">Collect feedback</div>
            <div style="font-size:.8rem;color:var(--text-muted)">Show the feedback sheet to customers after they're served</div>
          </div>
          <label class="switch"><input type="checkbox" name="enabled" <?php echo $s['enabled']?'checked':''; ?>><span class="sl"></span></label>
        </div>

        <label style="font-weight:700;font-size:.85rem;display:block;margin-bottom:2px">How often should it appear?</label>
        <div style="font-size:.8rem;color:var(--text-muted);margin-bottom:6px">Pick how many served orders should pass between prompts.</div>
        <div class="freq-opts" id="freqOpts">
          <?php
          $presets = [1=>'Every order', 2=>'Every 2 orders', 3=>'Every 3 orders', 5=>'Every 5 orders'];
          $is_preset = array_key_exists((int)$s['frequency_n'], $presets);
          foreach ($presets as $n=>$lbl): ?>
            <div class="freq-opt <?php echo ((int)$s['frequency_n']===$n)?'on':''; ?>" data-n="<?php echo $n; ?>"><?php echo $lbl; ?></div>
          <?php endforeach; ?>
          <div class="freq-opt <?php echo !$is_preset?'on':''; ?>" data-n="custom">Custom…</div>
        </div>
        <div id="customWrap" style="margin-top:10px;<?php echo $is_preset?'display:none':''; ?>">
          <label style="font-size:.82rem;font-weight:600">Every N served orders</label>
          <input type="number" min="1" max="50" name="frequency_n_custom" value="<?php echo (int)$s['frequency_n']; ?>" class="form-control" style="max-width:160px">
        </div>
        <input type="hidden" name="frequency_n" id="frequency_n" value="<?php echo (int)$s['frequency_n']; ?>">
      </div>
    </div>

    <div class="card" style="margin-bottom:16px">
      <div class="card-header"><h3>What customers see</h3></div>
      <div class="card-body">
        <div class="form-group">
          <label>Heading</label>
          <input type="text" name="intro_title" class="form-control" maxlength="160" value="<?php echo htmlspecialchars($s['intro_title']); ?>">
          <div style="font-size:.76rem;color:var(--text-muted);margin-top:4px">Shown with your restaurant name, e.g. "How was your experience with <?php echo htmlspecialchars($__rest_name ?? 'your restaurant'); ?>?"</div>
        </div>
        <div class="form-group">
          <label>Subtitle</label>
          <input type="text" name="intro_subtitle" class="form-control" maxlength="255" value="<?php echo htmlspecialchars($s['intro_subtitle']); ?>">
        </div>

        <div class="form-group">
          <label>Rating categories</label>
          <div style="font-size:.76rem;color:var(--text-muted);margin-bottom:4px">Each gets its own 1–5 star row. Up to 8.</div>
          <div class="chip-edit" id="catList"></div>
          <div class="chip-add">
            <input type="text" id="catInput" class="form-control" placeholder="Add a category (e.g. Ambience)" maxlength="40">
            <button type="button" class="btn btn-secondary btn-md" onclick="addChip('cat')">Add</button>
          </div>
        </div>

        <div class="form-group" style="margin-bottom:14px">
          <label>"What stood out?" chips</label>
          <div style="font-size:.76rem;color:var(--text-muted);margin-bottom:4px">Quick tap options. Up to 12.</div>
          <div class="chip-edit" id="tagList"></div>
          <div class="chip-add">
            <input type="text" id="tagInput" class="form-control" placeholder="Add a chip (e.g. Great value)" maxlength="40">
            <button type="button" class="btn btn-secondary btn-md" onclick="addChip('tag')">Add</button>
          </div>
        </div>

        <div class="row-between">
          <div>
            <div style="font-weight:700;font-size:.92rem">Allow a written comment</div>
            <div style="font-size:.8rem;color:var(--text-muted)">Optional free-text box at the end</div>
          </div>
          <label class="switch"><input type="checkbox" name="allow_comment" <?php echo $s['allow_comment']?'checked':''; ?>><span class="sl"></span></label>
        </div>
      </div>
    </div>

    <button type="submit" class="btn btn-primary btn-lg btn-block">Save feedback settings</button>
  </div>

  <!-- ── RIGHT: results ── -->
  <div>
    <div class="card" style="margin-bottom:16px">
      <div class="card-header"><h3>Results</h3></div>
      <div class="card-body">
        <?php if ($total === 0): ?>
          <p style="font-size:.85rem;color:var(--text-muted);text-align:center;padding:20px 0">No feedback yet. Once customers start responding, a summary appears here.</p>
        <?php else: ?>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:16px">
            <div class="stat-tile"><div class="v"><?php echo $avg_overall ?: '—'; ?> <span style="font-size:.9rem;color:var(--text-muted)">/5</span></div><div class="l">Average rating</div></div>
            <div class="stat-tile"><div class="v"><?php echo $total; ?></div><div class="l">Responses</div></div>
          </div>

          <?php if ($cat_cnt): ?>
          <div style="font-size:.8rem;font-weight:700;margin:6px 0 10px;color:var(--text-muted)">By category</div>
          <?php foreach ($cat_cnt as $label => $cnt): $avg = round($cat_sum[$label]/$cnt, 1); ?>
            <div class="row-between" style="margin-bottom:8px">
              <span style="font-size:.84rem"><?php echo htmlspecialchars($label); ?></span>
              <span style="font-size:.82rem;color:var(--text-muted)"><?php echo star_row($avg); ?> <?php echo $avg; ?></span>
            </div>
          <?php endforeach; ?>
          <?php endif; ?>

          <?php if ($tag_counts): ?>
          <div style="font-size:.8rem;font-weight:700;margin:16px 0 10px;color:var(--text-muted)">What stood out</div>
          <?php $maxt = max($tag_counts); foreach ($tag_counts as $t => $c): ?>
            <div class="bar-row"><span class="bn"><?php echo htmlspecialchars($t); ?></span><span class="bar-track"><span class="bar-fill" style="width:<?php echo round($c/$maxt*100); ?>%"></span></span><span style="width:24px;text-align:right;color:var(--text-muted)"><?php echo $c; ?></span></div>
          <?php endforeach; ?>
          <?php endif; ?>
        <?php endif; ?>
      </div>
    </div>

    <?php if ($recent): ?>
    <div class="card">
      <div class="card-header"><h3>Recent comments</h3></div>
      <div class="card-body" style="display:flex;flex-direction:column;gap:12px">
        <?php foreach ($recent as $r): ?>
        <div style="border-left:3px solid var(--primary);padding:2px 0 2px 12px">
          <div style="font-size:.74rem;color:var(--text-muted);margin-bottom:3px"><?php echo htmlspecialchars($r['user_name'] ?: 'Customer'); ?> · <?php echo date('M j', strtotime($r['created_at'])); ?><?php if ($r['overall_rating']): ?> · <?php echo (int)$r['overall_rating']; ?>★<?php endif; ?></div>
          <div style="font-size:.85rem;line-height:1.5;color:var(--text)"><?php echo htmlspecialchars($r['comment']); ?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>
</form>

<script>
(function () {
  // Frequency selector
  const hidden = document.getElementById('frequency_n');
  const customWrap = document.getElementById('customWrap');
  const customInput = document.querySelector('[name="frequency_n_custom"]');
  document.querySelectorAll('#freqOpts .freq-opt').forEach(opt => {
    opt.addEventListener('click', () => {
      document.querySelectorAll('#freqOpts .freq-opt').forEach(o => o.classList.remove('on'));
      opt.classList.add('on');
      if (opt.dataset.n === 'custom') { customWrap.style.display = 'block'; hidden.value = customInput.value || 1; }
      else { customWrap.style.display = 'none'; hidden.value = opt.dataset.n; }
    });
  });
  if (customInput) customInput.addEventListener('input', () => { hidden.value = Math.max(1, parseInt(customInput.value,10) || 1); });

  // Chip / category editors
  const data = {
    cat: <?php echo json_encode(array_values($s['categories'])); ?>,
    tag: <?php echo json_encode(array_values($s['tags'])); ?>
  };
  const limits = { cat: 8, tag: 12 };
  const fieldName = { cat: 'categories[]', tag: 'tags[]' };
  function render(kind) {
    const list = document.getElementById(kind === 'cat' ? 'catList' : 'tagList');
    list.innerHTML = '';
    data[kind].forEach((val, i) => {
      const ce = document.createElement('div'); ce.className = 'ce';
      const span = document.createElement('span'); span.textContent = val;
      const inp = document.createElement('input'); inp.type = 'hidden'; inp.name = fieldName[kind]; inp.value = val;
      const x = document.createElement('button'); x.type = 'button'; x.textContent = '×';
      x.onclick = () => { data[kind].splice(i,1); render(kind); };
      ce.appendChild(span); ce.appendChild(inp); ce.appendChild(x);
      list.appendChild(ce);
    });
  }
  window.addChip = function (kind) {
    const input = document.getElementById(kind === 'cat' ? 'catInput' : 'tagInput');
    const v = input.value.trim();
    if (!v) return;
    if (data[kind].length >= limits[kind]) { alert('You can add up to ' + limits[kind] + '.'); return; }
    if (!data[kind].some(x => x.toLowerCase() === v.toLowerCase())) data[kind].push(v);
    input.value = ''; render(kind);
  };
  ['catInput','tagInput'].forEach(id => {
    const el = document.getElementById(id);
    el.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); addChip(id === 'catInput' ? 'cat' : 'tag'); } });
  });
  render('cat'); render('tag');
})();
</script>

<?php include("includes/footer.php"); ?>
