<?php
session_start();
$page_title = 'App Feedback';
$active_nav = 'app_feedback';
include("includes/header.php");

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

$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'] ?? 5));
    $intro_title   = trim($_POST['intro_title'] ?? '') ?: 'How was your Dabil experience?';
    $intro_sub     = trim($_POST['intro_subtitle'] ?? '') ?: 'Your feedback helps us make everyday transactions faster and more reliable.';
    $tags = array_values(array_filter(array_map('trim', $_POST['tags'] ?? []), fn($v) => $v !== ''));
    $tags_json = json_encode(array_slice($tags, 0, 12));

    $st = $conn->prepare(
        "UPDATE dabil_feedback_settings
            SET enabled=?, frequency_n=?, intro_title=?, intro_subtitle=?, tags=?, allow_comment=?
          WHERE id=1"
    );
    $st->bind_param("iisssi", $enabled, $frequency_n, $intro_title, $intro_sub, $tags_json, $allow_comment);
    if ($st->execute()) $success = "App feedback settings saved.";
    else $error = "Could not save settings. Please try again.";
}

$s = df_get_settings($conn);

// ── Results ─────────────────────────────────────────────────────────────────
$total = 0;
$sent = ['smooth'=>0, 'okay'=>0, 'issues'=>0];
$tag_counts = []; $recent = [];
if ($res = @$conn->query(
    "SELECT df.sentiment, df.tags, df.comment, df.created_at, u.name AS user_name
     FROM dabil_feedback df LEFT JOIN users u ON df.user_id=u.id
     WHERE df.status='submitted'
     ORDER BY df.created_at DESC"
)) {
    while ($row = $res->fetch_assoc()) {
        $total++;
        if (isset($sent[$row['sentiment']])) $sent[$row['sentiment']]++;
        $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;
    }
}
arsort($tag_counts);
$sent_meta = [
    'smooth' => ['Smooth', 'var(--primary)'],
    'okay'   => ['Okay',   '#D9930B'],
    'issues' => ['Had issues', 'var(--error)'],
];
?>

<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%; border-radius:5px; }
</style>

<div style="margin-bottom:22px">
  <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">App Feedback</h1>
  <p style="color:var(--text-muted);font-size:.875rem">The platform-wide "Dabil experience" prompt — what it asks and how often customers see it</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">
  <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 app feedback</div>
            <div style="font-size:.8rem;color:var(--text-muted)">Show the Dabil experience prompt to customers</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">Counts a customer's served orders across all restaurants.</div>
        <div class="freq-opts" id="freqOpts">
          <?php
          $presets = [3=>'Every 3 orders', 5=>'Every 5 orders', 10=>'Every 10 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="100" 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>
        <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" 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. The Smooth / Okay / Had Issues choice is fixed.</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. Notifications)" maxlength="40">
            <button type="button" class="btn btn-secondary btn-md" onclick="addChip()">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 (500 chars)</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 app feedback settings</button>
  </div>

  <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 app feedback yet.</p>
        <?php else: ?>
          <div class="stat-tile" style="margin-bottom:14px"><div class="v"><?php echo $total; ?></div><div class="l">Total responses</div></div>
          <div style="font-size:.8rem;font-weight:700;margin:6px 0 10px;color:var(--text-muted)">Sentiment</div>
          <?php foreach ($sent_meta as $k => $meta): $c = $sent[$k]; $pct = $total ? round($c/$total*100) : 0; ?>
            <div class="bar-row"><span class="bn"><?php echo $meta[0]; ?></span><span class="bar-track"><span class="bar-fill" style="width:<?php echo $pct; ?>%;background:<?php echo $meta[1]; ?>"></span></span><span style="width:42px;text-align:right;color:var(--text-muted)"><?php echo $pct; ?>%</span></div>
          <?php endforeach; ?>

          <?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); ?>%;background:var(--primary)"></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 echo htmlspecialchars(ucfirst($r['sentiment'] ?: '')); ?></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 () {
  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); });

  const data = <?php echo json_encode(array_values($s['tags'])); ?>;
  function render() {
    const list = document.getElementById('tagList'); list.innerHTML = '';
    data.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 = 'tags[]'; inp.value = val;
      const x = document.createElement('button'); x.type = 'button'; x.textContent = '×';
      x.onclick = () => { data.splice(i,1); render(); };
      ce.appendChild(span); ce.appendChild(inp); ce.appendChild(x); list.appendChild(ce);
    });
  }
  window.addChip = function () {
    const input = document.getElementById('tagInput'); const v = input.value.trim();
    if (!v) return;
    if (data.length >= 12) { alert('You can add up to 12.'); return; }
    if (!data.some(x => x.toLowerCase() === v.toLowerCase())) data.push(v);
    input.value = ''; render();
  };
  document.getElementById('tagInput').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); addChip(); } });
  render();
})();
</script>

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