<?php
ob_start(); // ensure header() redirects work regardless of server output buffering
session_start();
$page_title = 'Dabil Feedback';
$active_nav = 'orders';
include("includes/header.php");
require_once __DIR__ . '/includes/feedback_lib.php';
$uid = (int)$_SESSION['user_id'];
feedback_ensure_tables($conn);

$order_id = (int)($_GET['order_id'] ?? $_POST['order_id'] ?? 0);
$settings = df_get_settings($conn);

// Did the user just submit (not skip) restaurant feedback before landing here?
// Carried through so the final thank-you modal can cover both.
$rf_done   = isset($_GET['rfdone']) || !empty($_POST['rfdone']);
$done_base = $order_id ? "order_detail.php?id=$order_id" : "dashboard.php";
$done_sep  = $order_id ? '&' : '?';
// Default exit (skips / not-due): only thank for restaurant feedback if that was submitted.
$done_url  = $done_base . ($rf_done ? $done_sep.'fb=rest' : '');

// If platform feedback is off, already handled, or not due per schedule, move on.
if (!$settings['enabled'] || df_already_handled($conn, $order_id) || !df_due_for_order($conn, $uid, $order_id)) {
    header("Location: $done_url"); exit;
}

// Quick skip via the close button (GET).
if (isset($_GET['skip'])) {
    $st = $conn->prepare("INSERT INTO dabil_feedback (user_id, order_id, status) VALUES (?,?,'skipped')
                          ON DUPLICATE KEY UPDATE status='skipped'");
    $oid = $order_id ?: null;
    $st->bind_param("ii", $uid, $oid);
    $st->execute();
    header("Location: $done_url"); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'submit';
    $oid    = $order_id ?: null;

    if ($action === 'skip') {
        $st = $conn->prepare("INSERT INTO dabil_feedback (user_id, order_id, status) VALUES (?,?,'skipped')
                              ON DUPLICATE KEY UPDATE status='skipped'");
        $st->bind_param("ii", $uid, $oid);
        $st->execute();
        header("Location: $done_url"); exit;
    } else {
        $sentiment = in_array($_POST['sentiment'] ?? '', ['smooth','okay','issues'], true) ? $_POST['sentiment'] : null;
        $tags_in   = $_POST['tags'] ?? [];
        $tags      = is_array($tags_in) ? array_values(array_intersect($settings['tags'], $tags_in)) : [];
        $comment   = trim((string)($_POST['comment'] ?? ''));
        if (mb_strlen($comment) > 500) $comment = mb_substr($comment, 0, 500);
        $tags_json = json_encode($tags);
        $st = $conn->prepare(
            "INSERT INTO dabil_feedback (user_id, order_id, status, sentiment, tags, comment)
             VALUES (?,?,'submitted',?,?,?)
             ON DUPLICATE KEY UPDATE status='submitted', sentiment=VALUES(sentiment), tags=VALUES(tags), comment=VALUES(comment)"
        );
        $st->bind_param("iisss", $uid, $oid, $sentiment, $tags_json, $comment);
        $st->execute();
    }
    // Submitted → thank for Dabil feedback (and the restaurant one, if it was also just given).
    header("Location: " . $done_base . $done_sep . 'fb=' . ($rf_done ? 'both' : 'dabil')); exit;
}
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.df-wrap { max-width: 600px; margin: 0 auto; }

.df-bar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 20px; }
.df-bar .df-title { font-size: 1.1rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.df-bar .df-close { width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); text-decoration: none; }

.df-head h1 { font-size: 1.5rem; font-weight: 800; letter-spacing: -.02em; line-height: 1.2; margin-bottom: 8px; }
.df-head p { font-size: .86rem; color: var(--text-muted); line-height: 1.5; margin-bottom: 24px; }

.df-sent { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 28px; }
.df-sent .opt { background: #fff; border: 1.5px solid var(--border); border-radius: 16px; padding: 18px 8px; display: flex; flex-direction: column; align-items: center; gap: 10px; cursor: pointer; transition: all .15s; box-shadow: 0 4px 14px rgba(15,23,42,.05); }
.df-sent .opt .em { width: 46px; height: 46px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: var(--bg, #EEF1F5); color: var(--text-muted); transition: all .15s; }
.df-sent .opt .lbl { font-size: .86rem; font-weight: 700; color: var(--text); }
.df-sent .opt.on { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(34,90,227,.1); }
.df-sent .opt[data-val="smooth"].on .em { background: var(--primary-bg); color: var(--primary); }
.df-sent .opt[data-val="okay"].on   .em { background: #FEF6E7; color: #D9930B; }
.df-sent .opt[data-val="issues"].on .em { background: #FDECEC; color: var(--error); }

.df-section-label { font-size: .68rem; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; color: var(--text-light); margin: 0 2px 12px; }
.df-chips { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 26px; }
.df-chip { border: none; background: var(--bg, #EEF1F5); color: var(--text); font-family: var(--font); font-weight: 600; font-size: .86rem; padding: 10px 16px; border-radius: 12px; cursor: pointer; transition: all .15s; }
.df-chip.on { background: var(--primary-bg); color: var(--primary); box-shadow: inset 0 0 0 1.5px var(--primary); }

.df-textwrap { position: relative; margin-bottom: 26px; }
.df-textarea { width: 100%; min-height: 120px; border: 1.5px solid var(--border); border-radius: 14px; background: #fff; padding: 14px 14px 28px; font-size: max(16px, .92rem); font-family: var(--font); color: var(--text); outline: none; resize: vertical; transition: border-color .2s, box-shadow .2s; }
.df-textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(34,90,227,.1); }
.df-count { position: absolute; right: 14px; bottom: 10px; font-size: .74rem; color: var(--text-light); }

.df-submit { width: 100%; height: 54px; border: none; border-radius: 14px; background: var(--primary); color: #fff; font-family: var(--font); font-weight: 700; font-size: .98rem; cursor: pointer; box-shadow: 0 8px 22px rgba(34,90,227,.3); }
.df-submit:active { background: var(--primary-dark); }
.df-submit:disabled { background: var(--border-dark, #CBD5E1); box-shadow: none; }
</style>

<div class="df-wrap">
  <div class="df-bar">
    <span class="df-title">Dabil Feedback</span>
    <a href="?order_id=<?php echo $order_id; ?>&skip=1<?php echo $rf_done?'&rfdone=1':''; ?>" class="df-close" aria-label="Close">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
    </a>
  </div>

  <div class="df-head">
    <h1><?php echo htmlspecialchars($settings['intro_title']); ?></h1>
    <p><?php echo htmlspecialchars($settings['intro_subtitle']); ?></p>
  </div>

  <form method="POST" id="dfForm">
    <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
    <input type="hidden" name="action" id="dfAction" value="submit">
    <input type="hidden" name="rfdone" value="<?php echo $rf_done?'1':''; ?>">
    <input type="hidden" name="sentiment" id="sentimentInput" value="">

    <div class="df-sent">
      <div class="opt" data-val="smooth">
        <span class="em"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg></span>
        <span class="lbl">Smooth</span>
      </div>
      <div class="opt" data-val="okay">
        <span class="em"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg></span>
        <span class="lbl">Okay</span>
      </div>
      <div class="opt" data-val="issues">
        <span class="em"><svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M16 16s-1.5-2-4-2-4 2-4 2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg></span>
        <span class="lbl">Had Issues</span>
      </div>
    </div>

    <?php if (!empty($settings['tags'])): ?>
    <div class="df-section-label">What specifically stood out?</div>
    <div class="df-chips">
      <?php foreach ($settings['tags'] as $tag): ?>
      <button type="button" class="df-chip" data-tag="<?php echo htmlspecialchars($tag); ?>"><?php echo htmlspecialchars($tag); ?></button>
      <?php endforeach; ?>
    </div>
    <div id="dfTagInputs"></div>
    <?php endif; ?>

    <?php if ($settings['allow_comment']): ?>
    <div class="df-section-label">Anything else we should know? (optional)</div>
    <div class="df-textwrap">
      <textarea name="comment" id="dfComment" class="df-textarea" maxlength="500" placeholder="Tell us more about your experience…"></textarea>
      <span class="df-count"><span id="dfCount">0</span>/500</span>
    </div>
    <?php endif; ?>

    <button type="submit" class="df-submit" id="dfSubmit" disabled>Submit Feedback</button>
  </form>
</div>

<script>
(function () {
  const sentInput = document.getElementById('sentimentInput');
  const submitBtn = document.getElementById('dfSubmit');
  document.querySelectorAll('.df-sent .opt').forEach(opt => {
    opt.addEventListener('click', () => {
      document.querySelectorAll('.df-sent .opt').forEach(o => o.classList.remove('on'));
      opt.classList.add('on');
      sentInput.value = opt.dataset.val;
      submitBtn.disabled = false;
    });
  });

  const tagBox = document.getElementById('dfTagInputs');
  document.querySelectorAll('.df-chip').forEach(chip => {
    chip.addEventListener('click', () => { chip.classList.toggle('on'); rebuildTags(); });
  });
  function rebuildTags() {
    if (!tagBox) return;
    tagBox.innerHTML = '';
    document.querySelectorAll('.df-chip.on').forEach(c => {
      const inp = document.createElement('input');
      inp.type = 'hidden'; inp.name = 'tags[]'; inp.value = c.dataset.tag;
      tagBox.appendChild(inp);
    });
  }

  const comment = document.getElementById('dfComment');
  const counter = document.getElementById('dfCount');
  if (comment && counter) comment.addEventListener('input', () => { counter.textContent = comment.value.length; });
})();
</script>

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