<?php
/**
 * ============================================================================
 * groups/index.php  –  Facebook-style Groups main page
 * ============================================================================
 * • Pulls data from BOTH the chats table (group chats) AND the standalone
 *   groups / group_members tables, then merges them into a single feed.
 * • All ORDER BY clauses use CASE WHEN … IS NULL instead of NULLS LAST
 *   so the queries run cleanly on MariaDB 10.x.
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle  = 'Groups';
$userId    = getUserId();

$database   = new Database();
$db         = $database->getConnection();

// ── URL filter: all | my | discover ─────────────────────────────────────────
$filter = in_array($_GET['filter'] ?? '', ['all','my','discover'])
        ? $_GET['filter'] : 'all';

// ════════════════════════════════════════════════════════════════════════════
// 1.  MY GROUPS  –  from the chats table (group-type chats the user is in)
// ════════════════════════════════════════════════════════════════════════════
$stmt = $db->prepare("
    SELECT
        c.id,
        c.chat_name    AS group_name,
        c.chat_avatar,
        c.created_at,
        cm.role        AS user_role,

        /* member count */
        (SELECT COUNT(*)
         FROM   chat_members
         WHERE  chat_id = c.id)                         AS member_count,

        /* total posts / messages */
        (SELECT COUNT(*)
         FROM   messages
         WHERE  chat_id = c.id)                         AS posts_count,

        /* last message text */
        (SELECT content
         FROM   messages
         WHERE  chat_id = c.id
         ORDER BY created_at DESC LIMIT 1)             AS last_message,

        /* last message timestamp  (may be NULL) */
        (SELECT created_at
         FROM   messages
         WHERE  chat_id = c.id
         ORDER BY created_at DESC LIMIT 1)             AS last_message_time,

        /* unread count since last_read_at */
        (SELECT COUNT(*)
         FROM   messages   m
         WHERE  m.chat_id   = c.id
           AND  m.sender_id <> :uid1
           AND  m.created_at > COALESCE(
                    (SELECT last_read_at
                     FROM   chat_members
                     WHERE  chat_id = c.id AND user_id = :uid2),
                    '2000-01-01 00:00:00'))            AS unread_count

    FROM   chats        c
    JOIN   chat_members cm ON c.id = cm.chat_id
    WHERE  cm.user_id  = :uid3
      AND  c.chat_type = 'group'

    /* MariaDB-safe: NULLs last, then newest first */
    ORDER BY
        CASE WHEN (SELECT created_at FROM messages WHERE chat_id = c.id ORDER BY created_at DESC LIMIT 1)
                  IS NULL THEN 1 ELSE 0 END,
        (SELECT created_at FROM messages WHERE chat_id = c.id ORDER BY created_at DESC LIMIT 1) DESC,
        c.created_at DESC
");
$stmt->execute([':uid1' => $userId, ':uid2' => $userId, ':uid3' => $userId]);
$myChatGroups = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ════════════════════════════════════════════════════════════════════════════
// 2.  MY GROUPS  –  from the standalone groups table
// ════════════════════════════════════════════════════════════════════════════
$stmt = $db->prepare("
    SELECT
        g.id            AS group_id,
        g.group_name,
        g.group_avatar,
        g.description,
        g.privacy,
        g.category,
        g.created_at,
        gm.role         AS user_role,
        g.member_count,
        COALESCE(
            (SELECT COUNT(*) FROM group_posts gp WHERE gp.group_id = g.id), 0
        )               AS posts_count
    FROM   groups        g
    JOIN   group_members gm ON g.id = gm.group_id
    WHERE  gm.user_id  = :uid
      AND  gm.status   = 'active'
    ORDER BY g.created_at DESC
");
$stmt->execute([':uid' => $userId]);
$myStandaloneGroups = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ════════════════════════════════════════════════════════════════════════════
// 3.  MERGE into one unified array
// ════════════════════════════════════════════════════════════════════════════
$myGroups = [];

foreach ($myChatGroups as $row) {
    $myGroups[] = [
        'id'            => $row['id'],
        'source'        => 'chat',
        'group_name'    => $row['group_name'] ?? 'Unnamed Group',
        'avatar'        => $row['chat_avatar'],
        'description'   => '',
        'privacy'       => 'public',
        'category'      => null,
        'user_role'     => $row['user_role'],
        'member_count'  => (int)$row['member_count'],
        'posts_count'   => (int)$row['posts_count'],
        'last_message'  => $row['last_message'],
        'last_msg_time' => $row['last_message_time'],
        'unread_count'  => (int)$row['unread_count'],
        'created_at'    => $row['created_at'],
    ];
}

foreach ($myStandaloneGroups as $row) {
    $myGroups[] = [
        'id'            => $row['group_id'],
        'source'        => 'group',
        'group_name'    => $row['group_name'],
        'avatar'        => $row['group_avatar'] ?? null,
        'description'   => $row['description'] ?? '',
        'privacy'       => $row['privacy']   ?? 'public',
        'category'      => $row['category']  ?? null,
        'user_role'     => $row['user_role'],
        'member_count'  => (int)$row['member_count'],
        'posts_count'   => (int)$row['posts_count'],
        'last_message'  => null,
        'last_msg_time' => null,
        'unread_count'  => 0,
        'created_at'    => $row['created_at'],
    ];
}

// ════════════════════════════════════════════════════════════════════════════
// 4.  DISCOVER  –  public standalone groups the user hasn't joined
// ════════════════════════════════════════════════════════════════════════════
$stmt = $db->prepare("
    SELECT
        g.id            AS group_id,
        g.group_name,
        g.group_avatar,
        g.description,
        g.privacy,
        g.category,
        g.member_count,
        g.created_at,
        u.full_name     AS creator_name,
        COALESCE(
            (SELECT COUNT(*) FROM group_posts gp WHERE gp.group_id = g.id), 0
        )               AS posts_count
    FROM   groups  g
    LEFT JOIN users u ON g.created_by = u.id
    WHERE  g.privacy = 'public'
      AND  g.id NOT IN (
              SELECT group_id
              FROM   group_members
              WHERE  user_id = :uid AND status = 'active'
          )
    ORDER BY g.member_count DESC, g.created_at DESC
    LIMIT 20
");
$stmt->execute([':uid' => $userId]);
$suggestedGroups = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ════════════════════════════════════════════════════════════════════════════
// HELPERS
// ════════════════════════════════════════════════════════════════════════════

/**
 * Deterministic gradient from a group name (10 palettes, picked by hash).
 */
function groupGradient(string $name): string {
    $palettes = [
        ['#667eea','#764ba2'],
        ['#f093fb','#f5576c'],
        ['#4facfe','#00f2fe'],
        ['#43e97b','#38f9d7'],
        ['#fa709a','#fee140'],
        ['#a18cd1','#fbc2eb'],
        ['#fbc2eb','#a6c1ee'],
        ['#89f7fe','#66a6ff'],
        ['#fddb92','#d1fdff'],
        ['#a1c4fd','#c2e9fb'],
    ];
    return $palettes[abs(crc32($name)) % count($palettes)][0] . ',' .
           $palettes[abs(crc32($name)) % count($palettes)][1];
}

/** Full CSS gradient string. */
function groupGradientCSS(string $name): string {
    $palettes = [
        ['#667eea','#764ba2'],
        ['#f093fb','#f5576c'],
        ['#4facfe','#00f2fe'],
        ['#43e97b','#38f9d7'],
        ['#fa709a','#fee140'],
        ['#a18cd1','#fbc2eb'],
        ['#fbc2eb','#a6c1ee'],
        ['#89f7fe','#66a6ff'],
        ['#fddb92','#d1fdff'],
        ['#a1c4fd','#c2e9fb'],
    ];
    $idx = abs(crc32($name)) % count($palettes);
    return "linear-gradient(135deg, {$palettes[$idx][0]} 0%, {$palettes[$idx][1]} 100%)";
}

/** Correct URL based on whether the group came from chats or groups table. */
function groupViewLink(array $g): string {
    if ($g['source'] === 'chat') {
        return APP_URL . '/groups/view.php?id=' . urlencode($g['id']);
    }
    return APP_URL . '/groups/view.php?id=' . urlencode($g['id']) . '&type=group';
}

// ── Include layout shells ───────────────────────────────────────────────────
include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>
<!-- ═══════════════════════════════════════════════════════════════════════
     STYLES  –  Facebook-inspired groups page
     ═══════════════════════════════════════════════════════════════════════ -->
<style>
/* ─── base ─── */
.gp { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #f0f2f5; min-height: calc(100vh - 120px); }

/* ─── sticky top bar ─── */
.gp-bar { background:#fff; border-bottom:1px solid #e4e6eb; padding:14px 0;
          position:sticky; top:0; z-index:100; }
.gp-bar-inner { max-width:1120px; margin:0 auto; padding:0 18px;
                display:flex; align-items:center; justify-content:space-between;
                flex-wrap:wrap; gap:12px; }
.gp-bar-left  { display:flex; align-items:center; gap:14px; }
.gp-bar-icon  { width:48px; height:48px; border-radius:10px;
                background:linear-gradient(135deg,#1877f2,#0c5ca5);
                display:flex; align-items:center; justify-content:center;
                font-size:22px; color:#fff; }
.gp-bar-title { margin:0; font-size:21px; font-weight:700; color:#1c1d23; }
.gp-bar-sub   { margin:2px 0 0; font-size:13px; color:#65676b; }

.btn-cg { background:linear-gradient(135deg,#1877f2,#0c5ca5); color:#fff;
          border:none; border-radius:8px; padding:10px 20px; font-size:14px;
          font-weight:600; cursor:pointer; text-decoration:none;
          display:inline-flex; align-items:center; gap:6px;
          transition:transform .15s,box-shadow .15s; }
.btn-cg:hover { transform:translateY(-1px);
                box-shadow:0 4px 12px rgba(24,119,242,.4); color:#fff; }

/* ─── two-column layout ─── */
.gp-layout { max-width:1120px; margin:20px auto; padding:0 18px;
             display:grid; grid-template-columns:360px 1fr; gap:20px;
             align-items:start; }
@media(max-width:860px){
  .gp-layout { grid-template-columns:1fr; }
  .gp-sidebar { order:-1; position:static !important; }
}

/* ─── sidebar ─── */
.gp-sidebar { background:#fff; border-radius:12px;
              box-shadow:0 1px 3px rgba(0,0,0,.08); overflow:hidden;
              position:sticky; top:100px; }
.gp-stitle  { font-size:12px; font-weight:700; color:#65676b;
              text-transform:uppercase; letter-spacing:.6px;
              padding:16px 16px 6px; }

.gp-nav     { display:flex; align-items:center; gap:12px; padding:10px 16px;
              text-decoration:none; color:#1c1d23; font-size:14px;
              font-weight:500; transition:background .15s; }
.gp-nav:hover       { background:#f0f2f5; color:#1c1d23; }
.gp-nav.active      { background:#e7f3ff; color:#1877f2; }
.gp-nav.active .gp-nav-ic { background:#cce0fc; color:#1877f2; }

.gp-nav-ic  { width:36px; height:36px; border-radius:8px; background:#f0f2f5;
              display:flex; align-items:center; justify-content:center;
              font-size:16px; color:#65676b; flex-shrink:0;
              transition:background .15s,color .15s; }

.gp-badge   { margin-left:auto; background:#1877f2; color:#fff;
              font-size:11px; font-weight:700; padding:2px 7px;
              border-radius:10px; min-width:20px; text-align:center; }

.gp-divider { border:none; border-top:1px solid #e4e6eb; margin:6px 0; }

/* sidebar mini-group rows */
.gp-sg      { display:flex; align-items:center; gap:10px; padding:8px 16px;
              text-decoration:none; color:#1c1d23; font-size:13.5px;
              font-weight:500; transition:background .15s; position:relative; }
.gp-sg:hover { background:#f0f2f5; color:#1c1d23; }
.gp-sg-av   { width:40px; height:40px; border-radius:8px; flex-shrink:0;
              display:flex; align-items:center; justify-content:center;
              overflow:hidden; }
.gp-sg-av img { width:100%; height:100%; object-fit:cover; }
.gp-sg-name { font-weight:600; white-space:nowrap; overflow:hidden;
              text-overflow:ellipsis; }
.gp-sg-meta { font-size:12px; color:#65676b; }
.gp-sg-dot  { position:absolute; right:16px; top:50%; transform:translateY(-50%);
              width:10px; height:10px; background:#1877f2; border-radius:50%; }

/* ─── main content ─── */
.gp-main { min-width:0; }

.gp-sh      { display:flex; align-items:center; justify-content:space-between;
              margin-bottom:14px; }
.gp-sh h3  { font-size:18px; font-weight:700; color:#1c1d23; margin:0; }
.gp-sh a   { font-size:13px; color:#1877f2; font-weight:600;
              text-decoration:none; }
.gp-sh a:hover { text-decoration:underline; }

/* cards grid */
.gp-grid    { display:grid;
              grid-template-columns:repeat(auto-fill,minmax(220px,1fr));
              gap:14px; margin-bottom:28px; }

/* ─── card ─── */
.gp-card    { background:#fff; border-radius:12px;
              box-shadow:0 1px 3px rgba(0,0,0,.08); overflow:hidden;
              transition:transform .2s,box-shadow .2s;
              display:flex; flex-direction:column;
              text-decoration:none; color:inherit; position:relative; }
.gp-card:hover { transform:translateY(-3px);
                 box-shadow:0 6px 20px rgba(0,0,0,.12); }

/* cover */
.gp-cover   { height:140px; position:relative; overflow:hidden; }
.gp-cover-bg{ width:100%; height:100%;
              display:flex; align-items:center; justify-content:center; }
.gp-cover-ic{ font-size:48px; opacity:.25; color:#fff; }

/* unread badge on card */
.gp-unread  { position:absolute; top:10px; right:10px;
              background:#1877f2; color:#fff; font-size:11px; font-weight:700;
              padding:3px 8px; border-radius:12px; z-index:2; }

/* avatar overlap */
.gp-av-wrap { display:flex; justify-content:center; margin-top:-28px;
              position:relative; z-index:1; }
.gp-av      { width:56px; height:56px; border-radius:12px;
              border:3px solid #fff; background:#e4e6eb;
              display:flex; align-items:center; justify-content:center;
              font-size:24px; color:#65676b;
              box-shadow:0 2px 6px rgba(0,0,0,.12); overflow:hidden; }
.gp-av img  { width:100%; height:100%; object-fit:cover; }

/* body */
.gp-body    { padding:10px 14px 14px; flex:1; display:flex; flex-direction:column; }
.gp-cname   { font-size:15px; font-weight:700; color:#1c1d23; text-align:center;
              margin-bottom:4px; white-space:nowrap; overflow:hidden;
              text-overflow:ellipsis; }
.gp-ccat    { font-size:12px; color:#65676b; text-align:center;
              margin-bottom:8px; text-transform:capitalize; }
.gp-cstats  { display:flex; justify-content:center; gap:16px;
              font-size:12px; color:#65676b; margin-bottom:10px; }
.gp-cstats span { display:flex; align-items:center; gap:4px; }
.gp-cprev   { font-size:12px; color:#65676b; text-align:center; font-style:italic;
              white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
              margin-bottom:10px; }
.gp-admin   { display:inline-flex; align-items:center; gap:4px;
              background:#e7f3ff; color:#1877f2; font-size:11px; font-weight:600;
              padding:3px 8px; border-radius:6px; align-self:center;
              margin-bottom:8px; }

/* buttons */
.gp-btn     { margin-top:auto; display:block; width:100%; padding:9px 0;
              border:none; border-radius:8px; font-size:13px; font-weight:600;
              cursor:pointer; text-decoration:none; text-align:center;
              transition:background .15s,color .15s; }
.gp-btn-pri { background:#e7f3ff; color:#1877f2; }
.gp-btn-pri:hover { background:#cce0fc; color:#1877f2; }
.gp-btn-join{ background:#1877f2; color:#fff; }
.gp-btn-join:hover{ background:#1661cf; color:#fff; }

/* empty states */
.gp-empty   { background:#fff; border-radius:12px;
              box-shadow:0 1px 3px rgba(0,0,0,.08);
              padding:48px 24px; text-align:center; margin-bottom:24px; }
.gp-empty-ic{ font-size:56px; margin-bottom:12px; }
.gp-empty h4{ font-size:17px; color:#1c1d23; margin:0 0 6px; }
.gp-empty p { font-size:14px; color:#65676b; margin:0 0 16px;
              max-width:360px; margin-left:auto; margin-right:auto; }

/* discover divider */
.gp-disc-d  { display:flex; align-items:center; gap:12px; margin:8px 0 20px; }
.gp-disc-d::before,.gp-disc-d::after { content:''; flex:1; height:1px; background:#e4e6eb; }
.gp-disc-d span { font-size:13px; font-weight:600; color:#65676b; white-space:nowrap; }

/* discover cards – shorter cover */
.gp-card.discover .gp-cover { height:120px; }

/* join form inside card – no extra margin */
.gp-card form { margin-top:auto; }
</style>

<!-- ═══════════════════════════════════════════════════════════════════════
     PAGE MARKUP
     ═══════════════════════════════════════════════════════════════════════ -->
<div class="gp">

  <!-- ── sticky top bar ── -->
  <div class="gp-bar">
    <div class="gp-bar-inner">
      <div class="gp-bar-left">
        <div class="gp-bar-icon"><i class="bi bi-people-fill"></i></div>
        <div>
          <h1 class="gp-bar-title">Groups</h1>
          <p class="gp-bar-sub">Connect with farmers who share your interests</p>
        </div>
      </div>
      <a href="<?=APP_URL?>/groups/create.php" class="btn-cg">
        <i class="bi bi-plus-lg"></i> Create Group
      </a>
    </div>
  </div>

  <!-- ── two-column layout ── -->
  <div class="gp-layout">

    <!-- ════════════════════════════════════════════════════════════════
         SIDEBAR
         ════════════════════════════════════════════════════════════════ -->
    <aside class="gp-sidebar">

      <div class="gp-stitle">Groups</div>

      <a href="<?=APP_URL?>/groups/?filter=all"
         class="gp-nav <?= $filter==='all' ? 'active' : '' ?>">
        <span class="gp-nav-ic"><i class="bi bi-collection"></i></span>
        All Groups
      </a>

      <a href="<?=APP_URL?>/groups/?filter=my"
         class="gp-nav <?= $filter==='my' ? 'active' : '' ?>">
        <span class="gp-nav-ic"><i class="bi bi-person-check"></i></span>
        Your Groups
        <?php if (count($myGroups)): ?>
          <span class="gp-badge"><?=count($myGroups)?></span>
        <?php endif; ?>
      </a>

      <a href="<?=APP_URL?>/groups/?filter=discover"
         class="gp-nav <?= $filter==='discover' ? 'active' : '' ?>">
        <span class="gp-nav-ic"><i class="bi bi-compass"></i></span>
        Discover
        <?php if (count($suggestedGroups)): ?>
          <span class="gp-badge"><?=count($suggestedGroups)?></span>
        <?php endif; ?>
      </a>

      <hr class="gp-divider">
      <div class="gp-stitle">Quick Links</div>

      <a href="<?=APP_URL?>/chat/"    class="gp-nav">
        <span class="gp-nav-ic"><i class="bi bi-chat-dots"></i></span> Messages
      </a>
      <a href="<?=APP_URL?>/friends/" class="gp-nav">
        <span class="gp-nav-ic"><i class="bi bi-people"></i></span>   Friends
      </a>
      <a href="<?=APP_URL?>/posts/"   class="gp-nav">
        <span class="gp-nav-ic"><i class="bi bi-newspaper"></i></span> Posts
      </a>

      <!-- mini list: up to 6 of your groups -->
      <?php if ($myGroups): ?>
        <hr class="gp-divider">
        <div class="gp-stitle">Your Groups</div>
        <?php foreach (array_slice($myGroups,0,6) as $g): ?>
          <a href="<?=groupViewLink($g)?>" class="gp-sg">
            <div class="gp-sg-av" style="background:<?=groupGradientCSS($g['group_name'])?>;">
              <?php if ($g['avatar']): ?>
                <img src="<?=htmlspecialchars($g['avatar'])?>" alt="">
              <?php else: ?>
                <i class="bi bi-people-fill" style="color:#fff;font-size:18px;"></i>
              <?php endif; ?>
            </div>
            <div>
              <div class="gp-sg-name"><?=htmlspecialchars($g['group_name'])?></div>
              <div class="gp-sg-meta"><?=number_format($g['member_count'])?> members</div>
            </div>
            <?php if ($g['unread_count']>0): ?><span class="gp-sg-dot"></span><?php endif; ?>
          </a>
        <?php endforeach; ?>
        <?php if (count($myGroups)>6): ?>
          <a href="<?=APP_URL?>/groups/?filter=my"
             style="font-size:13px;color:#1877f2;padding:8px 16px;display:block;text-align:center;text-decoration:none;font-weight:600;">
            See all (<?=count($myGroups)?>)
          </a>
        <?php endif; ?>
      <?php endif; ?>

    </aside>

    <!-- ════════════════════════════════════════════════════════════════
         MAIN CONTENT
         ════════════════════════════════════════════════════════════════ -->
    <main class="gp-main">

      <!-- ────── YOUR GROUPS ────── (shown on 'all' or 'my') -->
      <?php if ($filter !== 'discover'): ?>

        <div class="gp-sh">
          <h3><i class="bi bi-collection-fill" style="color:#1877f2;"></i> Your Groups</h3>
          <?php if (count($myGroups)>4): ?>
            <a href="<?=APP_URL?>/groups/?filter=my">See all</a>
          <?php endif; ?>
        </div>

        <?php if ($myGroups): ?>
          <div class="gp-grid">
            <?php foreach ($myGroups as $g): ?>
            <a href="<?=groupViewLink($g)?>" class="gp-card" style="cursor:pointer;">

              <?php if ($g['unread_count']>0): ?>
                <span class="gp-unread"><?=$g['unread_count']?> new</span>
              <?php endif; ?>

              <!-- cover -->
              <div class="gp-cover">
                <div class="gp-cover-bg" style="background:<?=groupGradientCSS($g['group_name'])?>;">
                  <i class="bi bi-people-fill gp-cover-ic"></i>
                </div>
              </div>

              <!-- avatar -->
              <div class="gp-av-wrap">
                <div class="gp-av">
                  <?php if ($g['avatar']): ?>
                    <img src="<?=htmlspecialchars($g['avatar'])?>" alt="">
                  <?php else: ?>
                    <i class="bi bi-people-fill"></i>
                  <?php endif; ?>
                </div>
              </div>

              <!-- body -->
              <div class="gp-body">
                <div class="gp-cname"><?=htmlspecialchars($g['group_name'])?></div>

                <?php if ($g['category']): ?>
                  <div class="gp-ccat"><?=htmlspecialchars($g['category'])?></div>
                <?php endif; ?>

                <?php if ($g['user_role']==='admin'): ?>
                  <div class="gp-admin"><i class="bi bi-shield-check"></i> You're an admin</div>
                <?php endif; ?>

                <div class="gp-cstats">
                  <span><i class="bi bi-people"></i> <?=number_format($g['member_count'])?></span>
                  <span><i class="bi bi-chat-dots"></i> <?=number_format($g['posts_count'])?></span>
                </div>

                <?php if ($g['last_message']): ?>
                  <div class="gp-cprev"><?=htmlspecialchars(substr($g['last_message'],0,60))?></div>
                <?php endif; ?>

                <a href="<?=groupViewLink($g)?>" class="gp-btn gp-btn-pri"
                   onclick="event.stopPropagation();">
                  <i class="bi bi-chat-dots"></i> Open Group
                </a>
              </div>
            </a>
            <?php endforeach; ?>
          </div>

        <?php else: ?>
          <div class="gp-empty">
            <div class="gp-empty-ic">👥</div>
            <h4>You haven't joined any groups yet</h4>
            <p>Groups are a great way to connect with other farmers, share tips, and stay updated on agricultural news.</p>
            <a href="<?=APP_URL?>/groups/create.php" class="btn-cg" style="display:inline-flex;">
              <i class="bi bi-plus-lg"></i> Create a Group
            </a>
          </div>
        <?php endif; ?>

      <?php endif; // filter !== discover ?>

      <!-- ────── DISCOVER ────── (shown on 'all' or 'discover') -->
      <?php if ($filter !== 'my'): ?>

        <?php if ($filter==='all' && $suggestedGroups): ?>
          <div class="gp-disc-d"><span><i class="bi bi-compass"></i> Discover New Groups</span></div>
        <?php endif; ?>

        <div class="gp-sh">
          <h3><i class="bi bi-compass-fill" style="color:#43a047;"></i> Discover Groups</h3>
        </div>

        <?php if ($suggestedGroups): ?>
          <div class="gp-grid">
            <?php foreach ($suggestedGroups as $g): ?>
            <div class="gp-card discover">

              <!-- cover -->
              <div class="gp-cover">
                <div class="gp-cover-bg" style="background:<?=groupGradientCSS($g['group_name'])?>;">
                  <i class="bi bi-people-fill gp-cover-ic"></i>
                </div>
              </div>

              <!-- avatar -->
              <div class="gp-av-wrap">
                <div class="gp-av">
                  <?php if ($g['group_avatar']): ?>
                    <img src="<?=htmlspecialchars($g['group_avatar'])?>" alt="">
                  <?php else: ?>
                    <i class="bi bi-people-fill"></i>
                  <?php endif; ?>
                </div>
              </div>

              <!-- body -->
              <div class="gp-body">
                <div class="gp-cname"><?=htmlspecialchars($g['group_name'])?></div>

                <?php if ($g['category']): ?>
                  <div class="gp-ccat"><?=htmlspecialchars($g['category'])?></div>
                <?php endif; ?>

                <?php if ($g['description']): ?>
                  <div class="gp-cprev" style="font-style:normal;">
                    <?=htmlspecialchars(substr($g['description'],0,70))?>
                  </div>
                <?php endif; ?>

                <div class="gp-cstats">
                  <span><i class="bi bi-people"></i> <?=number_format($g['member_count'])?></span>
                  <span><i class="bi bi-chat-dots"></i> <?=number_format($g['posts_count'])?></span>
                </div>

                <?php if ($g['creator_name']): ?>
                  <div style="font-size:11.5px;color:#65676b;text-align:center;margin-bottom:8px;">
                    Created by <?=htmlspecialchars($g['creator_name'])?>
                  </div>
                <?php endif; ?>

                <!-- Join button -->
                <form method="POST" action="<?=APP_URL?>/groups/join.php" style="margin-top:auto;">
                  <input type="hidden" name="group_id" value="<?=$g['group_id']?>">
                  <button type="submit" class="gp-btn gp-btn-join">
                    <i class="bi bi-box-arrow-in-right"></i> Join Group
                  </button>
                </form>
              </div>
            </div>
            <?php endforeach; ?>
          </div>

        <?php else: ?>
          <div class="gp-empty">
            <div class="gp-empty-ic">🔍</div>
            <h4>No groups to discover right now</h4>
            <p>Be the first to create a farming group in your area. Others will be able to find and join it.</p>
            <a href="<?=APP_URL?>/groups/create.php" class="btn-cg" style="display:inline-flex;">
              <i class="bi bi-plus-lg"></i> Create a Group
            </a>
          </div>
        <?php endif; ?>

      <?php endif; // filter !== my ?>

    </main>
  </div><!-- /gp-layout -->
</div><!-- /gp -->

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>