<?php
ob_start(); // ensure header() redirects work regardless of server output buffering
session_start();
$page_title = 'Restaurant 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);

// Load the order (must belong to this customer and be served).
$stmt = $conn->prepare(
    "SELECT o.id, o.restaurant_id, o.order_status, r.name AS restaurant_name, r.logo AS restaurant_logo
     FROM orders o LEFT JOIN restaurants r ON o.restaurant_id = r.id
     WHERE o.id=? AND o.user_id=? LIMIT 1"
);
$stmt->bind_param("ii", $order_id, $uid);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();

if (!$order || $order['order_status'] !== 'completed') { header("Location: orders.php"); exit; }

$rid      = (int)$order['restaurant_id'];
$settings = rf_get_settings($conn, $rid);

// If this restaurant has feedback off, already handled, or simply not due per the
// restaurant's schedule, continue the flow (maybe Dabil feedback is due) or go back.
$rf_due = rf_due_for_order($conn, $uid, $order);
if (!$settings['enabled'] || rf_already_handled($conn, $order_id) || !$rf_due) {
    $dabil_oid = 0;
    if (df_due($conn, $uid, $dabil_oid)) { header("Location: dabil_feedback.php?order_id=$dabil_oid"); exit; }
    header("Location: order_detail.php?id=$order_id"); exit;
}

// Dismiss via the close (X) button — records a skip so we don't re-prompt.
if (isset($_GET['skip'])) {
    $st = $conn->prepare("INSERT INTO restaurant_feedback (restaurant_id, order_id, user_id, status) VALUES (?,?,?,'skipped')
                          ON DUPLICATE KEY UPDATE status='skipped'");
    $st->bind_param("iii", $rid, $order_id, $uid);
    $st->execute();
    $dabil_oid = 0;
    if (df_due($conn, $uid, $dabil_oid)) { header("Location: dabil_feedback.php?order_id=$dabil_oid"); exit; }
    header("Location: order_detail.php?id=$order_id"); exit;
}

// ── Handle submission / skip ────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'submit';

    if ($action === 'skip') {
        $st = $conn->prepare("INSERT INTO restaurant_feedback (restaurant_id, order_id, user_id, status) VALUES (?,?,?,'skipped')
                              ON DUPLICATE KEY UPDATE status='skipped'");
        $st->bind_param("iii", $rid, $order_id, $uid);
        $st->execute();
    } else {
        $overall = max(0, min(5, (int)($_POST['overall'] ?? 0)));
        $cat_in  = $_POST['cat'] ?? [];
        $cats    = [];
        foreach ($settings['categories'] as $label) {
            $v = isset($cat_in[$label]) ? (int)$cat_in[$label] : 0;
            if ($v >= 1 && $v <= 5) $cats[$label] = $v;
        }
        $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) > 800) $comment = mb_substr($comment, 0, 800);

        $cats_json = json_encode($cats);
        $tags_json = json_encode($tags);
        $st = $conn->prepare(
            "INSERT INTO restaurant_feedback (restaurant_id, order_id, user_id, status, overall_rating, category_ratings, tags, comment)
             VALUES (?,?,?,'submitted',?,?,?,?)
             ON DUPLICATE KEY UPDATE status='submitted', overall_rating=VALUES(overall_rating),
               category_ratings=VALUES(category_ratings), tags=VALUES(tags), comment=VALUES(comment)"
        );
        $st->bind_param("iiiisss", $rid, $order_id, $uid, $overall, $cats_json, $tags_json, $comment);
        $st->execute();
    }

    // Chain into Dabil feedback if it's also due, otherwise back to the order.
    // A real submission (not a skip) carries a flag so the destination page can
    // pop the "thank you — your opinion matters" modal.
    $submitted = ($action !== 'skip');
    $dabil_oid = 0;
    if (df_due($conn, $uid, $dabil_oid)) { header("Location: dabil_feedback.php?order_id=$dabil_oid&from=rf".($submitted?'&rfdone=1':'')); exit; }
    header("Location: order_detail.php?id=$order_id".($submitted?'&fb=rest':'')); exit;
}

$logo_path = $order['restaurant_logo'] ? '../restaurantadmin/uploads/logos/' . $order['restaurant_logo'] : null;
$has_logo  = $logo_path && file_exists(__DIR__ . '/' . $logo_path);
$rname     = $order['restaurant_name'] ?: 'this restaurant';
?>

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

.fb-bar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 18px; }
.fb-bar .fb-title { font-size: 1.1rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.fb-bar .fb-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; }

.fb-hero { text-align: center; margin-bottom: 18px; }
.fb-avatar { width: 78px; height: 78px; border-radius: 50%; overflow: hidden; margin: 0 auto 16px; background: linear-gradient(135deg, var(--primary-bg), #dce8fb); display: flex; align-items: center; justify-content: center; font-weight: 800; color: var(--primary); font-size: 1.5rem; box-shadow: 0 6px 18px rgba(15,23,42,.1); }
.fb-avatar img { width: 100%; height: 100%; object-fit: cover; }
.fb-hero h1 { font-size: 1.45rem; font-weight: 800; letter-spacing: -.02em; line-height: 1.2; max-width: 320px; margin: 0 auto 8px; }
.fb-hero p { font-size: .86rem; color: var(--text-muted); line-height: 1.5; max-width: 320px; margin: 0 auto; }

.fb-overall { display: flex; justify-content: center; gap: 8px; margin: 22px 0; }
.star { background: none; border: none; padding: 0; cursor: pointer; line-height: 0; color: var(--border-dark, #CBD5E1); transition: transform .1s; }
.star:active { transform: scale(.9); }
.star.on { color: var(--primary); }
.fb-overall .star svg { width: 38px; height: 38px; }

.fb-card { background: #fff; border: 1px solid var(--border); border-radius: 18px; box-shadow: 0 4px 18px rgba(15,23,42,.06); padding: 6px 18px; margin-bottom: 22px; }
.fb-cat-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 15px 0; border-top: 1px solid var(--border); }
.fb-cat-row:first-child { border-top: none; }
.fb-cat-label { font-weight: 600; font-size: .92rem; color: var(--text); }
.fb-cat-stars { display: flex; gap: 4px; }
.fb-cat-stars .star svg { width: 20px; height: 20px; }

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

.fb-textarea { width: 100%; min-height: 96px; border: 1.5px solid var(--border); border-radius: 14px; background: #fff; padding: 14px; font-size: max(16px, .92rem); font-family: var(--font); color: var(--text); outline: none; resize: vertical; transition: border-color .2s, box-shadow .2s; }
.fb-textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(34,90,227,.1); }

.fb-actions { margin-top: 22px; display: flex; flex-direction: column; gap: 10px; }
.fb-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); }
.fb-submit:active { background: var(--primary-dark); }
.fb-submit:disabled { background: var(--border-dark, #CBD5E1); box-shadow: none; }
.fb-skip { width: 100%; height: 50px; border: none; border-radius: 14px; background: var(--primary-bg); color: var(--primary); font-family: var(--font); font-weight: 700; font-size: .95rem; cursor: pointer; }
</style>

<div class="fb-wrap">
  <div class="fb-bar">
    <span class="fb-title">Restaurant Feedback</span>
    <a href="?order_id=<?php echo $order_id; ?>&skip=1" class="fb-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="fb-hero">
    <div class="fb-avatar">
      <?php if ($has_logo): ?><img src="<?php echo htmlspecialchars($logo_path); ?>" alt=""><?php else: echo htmlspecialchars(strtoupper(substr($rname, 0, 1))); endif; ?>
    </div>
    <h1>How was your experience with <?php echo htmlspecialchars($rname); ?>?</h1>
    <p><?php echo htmlspecialchars($settings['intro_subtitle']); ?></p>
  </div>

  <form method="POST" id="fbForm">
    <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
    <input type="hidden" name="action" id="fbAction" value="submit">
    <input type="hidden" name="overall" id="overallInput" value="0">

    <!-- Overall stars -->
    <div class="fb-overall" data-rating-group="overall">
      <?php for ($i = 1; $i <= 5; $i++): ?>
      <button type="button" class="star" data-val="<?php echo $i; ?>" aria-label="<?php echo $i; ?> star">
        <svg viewBox="0 0 24 24" fill="currentColor"><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>
      </button>
      <?php endfor; ?>
    </div>

    <!-- Per-category -->
    <?php if (!empty($settings['categories'])): ?>
    <div class="fb-card">
      <?php foreach ($settings['categories'] as $ci => $label): ?>
      <div class="fb-cat-row">
        <span class="fb-cat-label"><?php echo htmlspecialchars($label); ?></span>
        <input type="hidden" name="cat[<?php echo htmlspecialchars($label); ?>]" id="cat_<?php echo $ci; ?>" value="0">
        <div class="fb-cat-stars" data-rating-group="cat_<?php echo $ci; ?>">
          <?php for ($i = 1; $i <= 5; $i++): ?>
          <button type="button" class="star" data-val="<?php echo $i; ?>" aria-label="<?php echo $i; ?> star">
            <svg viewBox="0 0 24 24" fill="currentColor"><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>
          </button>
          <?php endfor; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

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

    <!-- Comment -->
    <?php if ($settings['allow_comment']): ?>
    <div class="fb-section-label">Tell us more… (optional)</div>
    <textarea name="comment" class="fb-textarea" maxlength="800" placeholder="Share specific details about your experience…"></textarea>
    <?php endif; ?>

    <div class="fb-actions">
      <button type="submit" class="fb-submit" id="fbSubmit" disabled>Submit Feedback</button>
      <button type="submit" class="fb-skip" onclick="document.getElementById('fbAction').value='skip'">Skip</button>
    </div>
  </form>
</div>

<script>
(function () {
  function wireStars(group, hiddenId) {
    const stars = group.querySelectorAll('.star');
    const hidden = document.getElementById(hiddenId);
    function paint(v) { stars.forEach(s => s.classList.toggle('on', parseInt(s.dataset.val, 10) <= v)); }
    stars.forEach(s => s.addEventListener('click', () => {
      const v = parseInt(s.dataset.val, 10);
      hidden.value = v; paint(v); checkReady();
    }));
  }
  wireStars(document.querySelector('[data-rating-group="overall"]'), 'overallInput');
  document.querySelectorAll('.fb-cat-stars[data-rating-group]').forEach(g => {
    wireStars(g, g.dataset.ratingGroup);
  });

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

  // Enable Submit once an overall rating is given
  const submitBtn = document.getElementById('fbSubmit');
  window.checkReady = function () {
    submitBtn.disabled = parseInt(document.getElementById('overallInput').value, 10) < 1;
  };
})();
</script>

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