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

$success = $error = "";
$action  = $_GET['action'] ?? '';

// Make sure the table exists so a fresh install never errors out.
@$conn->query(
    "CREATE TABLE IF NOT EXISTS `support_messages` (
        `id` INT NOT NULL AUTO_INCREMENT,
        `user_id` INT NOT NULL,
        `subject` VARCHAR(200) NOT NULL,
        `message` TEXT NOT NULL,
        `status` ENUM('open','resolved') NOT NULL DEFAULT 'open',
        `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        KEY `idx_support_messages_user` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci"
);

// Mark resolved / reopen
if (($action === 'resolve' || $action === 'reopen') && isset($_GET['id'])) {
    $mid       = (int)$_GET['id'];
    $newstatus = $action === 'resolve' ? 'resolved' : 'open';
    $stmt = $conn->prepare("UPDATE support_messages SET status=? WHERE id=?");
    $stmt->bind_param("si", $newstatus, $mid);
    $stmt->execute();
    header("Location: feedback.php?status=" . urlencode($_GET['status'] ?? 'all') . "&msg=" . $action);
    exit;
}

$msg = $_GET['msg'] ?? '';
if ($msg === 'resolve') $success = "Message marked as resolved.";
if ($msg === 'reopen')  $success = "Message reopened.";

// Filter
$status_filter = $_GET['status'] ?? 'all';
$where = "";
if ($status_filter === 'open')     $where = "WHERE sm.status='open'";
if ($status_filter === 'resolved') $where = "WHERE sm.status='resolved'";

$rows = $conn->query(
    "SELECT sm.*, u.name AS user_name, u.email AS user_email
     FROM support_messages sm
     LEFT JOIN users u ON sm.user_id = u.id
     $where
     ORDER BY (sm.status='open') DESC, sm.created_at DESC"
);

// Counts for the tabs
$counts = ['all' => 0, 'open' => 0, 'resolved' => 0];
if ($cres = @$conn->query("SELECT status, COUNT(*) c FROM support_messages GROUP BY status")) {
    while ($cr = $cres->fetch_assoc()) {
        $counts[$cr['status']] = (int)$cr['c'];
        $counts['all'] += (int)$cr['c'];
    }
}
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <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">Messages sent by customers from the app's Contact Admin screen</p>
  </div>
</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; ?>

<!-- Status Filter Tabs -->
<div style="display:flex;gap:8px;margin-bottom:20px;flex-wrap:wrap;align-items:center">
  <?php
  $tabs = ['all'=>'All','open'=>'Open','resolved'=>'Resolved'];
  foreach ($tabs as $k=>$l):
  ?>
  <a href="?status=<?php echo $k; ?>" class="btn btn-sm <?php echo $status_filter===$k?'btn-primary':'btn-secondary'; ?>">
    <?php echo $l; ?> <span style="opacity:.7">(<?php echo $counts[$k]; ?>)</span>
  </a>
  <?php endforeach; ?>
</div>

<?php if (!$rows || $rows->num_rows === 0): ?>
  <div class="card">
    <div style="padding:60px;text-align:center;color:var(--text-muted)">
      <svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="var(--text-light)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom:12px"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>
      <p style="font-weight:700;margin-bottom:6px">No feedback here yet</p>
      <p style="font-size:.85rem">When customers send a message, it'll show up on this page.</p>
    </div>
  </div>
<?php else: ?>
  <div style="display:flex;flex-direction:column;gap:12px">
  <?php while ($r = $rows->fetch_assoc()):
    $is_open = $r['status'] === 'open';
    $name    = $r['user_name'] ?: 'Customer #' . (int)$r['user_id'];
    $initial = strtoupper(substr($name, 0, 1));
  ?>
    <div class="card" style="padding:18px 20px">
      <div style="display:flex;align-items:flex-start;gap:14px;flex-wrap:wrap">
        <div style="width:40px;height:40px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;font-size:.85rem;font-weight:800;color:#fff;flex-shrink:0"><?php echo htmlspecialchars($initial); ?></div>
        <div style="flex:1;min-width:200px">
          <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:2px">
            <span style="font-weight:800;font-size:.95rem"><?php echo htmlspecialchars($r['subject']); ?></span>
            <span class="badge <?php echo $is_open?'badge-warning':'badge-success'; ?>"><?php echo $is_open?'Open':'Resolved'; ?></span>
          </div>
          <div style="font-size:.78rem;color:var(--text-muted)">
            <?php echo htmlspecialchars($name); ?>
            <?php if ($r['user_email']): ?> · <a href="mailto:<?php echo htmlspecialchars($r['user_email']); ?>" style="color:var(--primary)"><?php echo htmlspecialchars($r['user_email']); ?></a><?php endif; ?>
            · <?php echo date('M j, Y · g:i A', strtotime($r['created_at'])); ?>
          </div>
          <p style="font-size:.88rem;color:var(--text);line-height:1.55;margin-top:10px;white-space:pre-wrap"><?php echo htmlspecialchars($r['message']); ?></p>
        </div>
        <div style="display:flex;flex-direction:column;gap:8px;flex-shrink:0">
          <?php if ($is_open): ?>
            <a href="?action=resolve&id=<?php echo (int)$r['id']; ?>&status=<?php echo htmlspecialchars($status_filter); ?>" class="btn btn-success btn-sm">Mark resolved</a>
          <?php else: ?>
            <a href="?action=reopen&id=<?php echo (int)$r['id']; ?>&status=<?php echo htmlspecialchars($status_filter); ?>" class="btn btn-secondary btn-sm">Reopen</a>
          <?php endif; ?>
          <?php if ($r['user_email']): ?>
            <a href="mailto:<?php echo htmlspecialchars($r['user_email']); ?>?subject=<?php echo rawurlencode('Re: ' . $r['subject']); ?>" class="btn btn-secondary btn-sm">Reply by email</a>
          <?php endif; ?>
        </div>
      </div>
    </div>
  <?php endwhile; ?>
  </div>
<?php endif; ?>

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