<?php
session_start();
include 'config.php';
include 'rating_helpers.php';

// Pillar slug-to-label map (single source of truth)
$pillar_map = [
    'financing' => 'Financing',
    'governance' => 'Governance',
    'research' => 'Research & Learning',
    'collaboration' => 'Coordination and Collaboration',
    'mhm' => 'Menstrual Health Management',
    'capacity-building' => 'Capacity Building',
];

// Per-pillar hero & nav-card images
$pillar_images = [
    'financing' => [
        'hero' => 'images/pillars/financing.jpeg',
        'card' => 'images/pillars/Financing Navigation Button.jpg',
    ],
    'governance' => [
        'hero' => 'images/pillars/Governance Hero banner 1.jpg',
        'card' => 'images/pillars/Governance Navigation button.jpg',
    ],
    'research' => [
        'hero' => 'images/pillars/Research Hero banner.jpg',
        'card' => 'images/pillars/Research Navigation Button.jpg',
    ],
    'collaboration' => [
        'hero' => 'images/pillars/Coordination and collaboration Hero banner.jpg',
        'card' => 'images/pillars/Coordination and collaboration Navigation Banner.jpg',
    ],
    'mhm' => [
        'hero' => 'images/pillars/Menstrual Hygiene Hero Banner.jpg',
        'card' => 'images/pillars/Menstrual Hygiene Navigation Button.jpg',
    ],
    'capacity-building' => [
        'hero' => 'images/pillars/Capacity Building Hero Banner.jpg',
        'card' => 'images/pillars/Capacity Building navigation button.jpg',
    ],
];

// Read filter / sort / page params
$active_sub = isset($_GET['sub']) && isset($pillar_map[$_GET['sub']]) ? $_GET['sub'] : null;
$active_label = $active_sub ? $pillar_map[$active_sub] : null;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'most-viewed';
$page_num = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 12;
$offset = ($page_num - 1) * $per_page;

// Build query
$where = "is_verified = 1 AND enabling_pillars IS NOT NULL AND enabling_pillars != '' AND enabling_pillars != '[]'";
$params = [];
$types = '';

if ($active_label) {
    $where .= " AND enabling_pillars LIKE ?";
    $params[] = '%"' . $active_label . '"%';
    $types .= 's';
}

$q = trim($_GET['q'] ?? '');
if ($q !== '') {
    $where .= " AND (title LIKE ? OR org_name LIKE ? OR story LIKE ?)";
    $lk = "%$q%";
    array_push($params, $lk, $lk, $lk);
    $types .= 'sss';
}

$f_county = trim($_GET['county'] ?? '');
if ($f_county !== '') {
    // Exact match or partial if in JSON
    $where .= " AND county LIKE ?";
    $params[] = "%$f_county%";
    $types .= 's';
}

$f_sector = trim($_GET['sector'] ?? '');
if ($f_sector !== '') {
    // Sector can be in JSON org_sector or plain role
    $where .= " AND (org_sector LIKE ? OR role = ?)";
    $params[] = '%"sector":"' . $f_sector . '"%';
    $params[] = $f_sector;
    $types .= 'ss';
}

$f_org = trim($_GET['org'] ?? '');
if ($f_org !== '') {
    $where .= " AND org_name = ?";
    $params[] = $f_org;
    $types .= 's';
}

$order = match ($sort) {
    'oldest' => 'created_at ASC',
    'newest' => 'created_at DESC',
    'az' => 'org_name ASC',
    'top-rated' => 'avg_rat DESC, created_at DESC',
    default => 'view_count DESC, created_at DESC', // most-viewed
};

// Count total
$count_sql = "SELECT COUNT(*) as total FROM submissions WHERE $where";
$count_stmt = $conn->prepare($count_sql);
if ($types)
    $count_stmt->bind_param($types, ...$params);
$count_stmt->execute();
$total_count = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_count / $per_page);

// Fetch users to map user_id -> slug
$slug_map = [];
$u_sql = "SELECT id, slug FROM users WHERE slug IS NOT NULL AND slug != ''";
$u_res = $conn->query($u_sql);
if ($u_res) {
    while ($ur = $u_res->fetch_assoc()) {
        $slug_map[$ur['id']] = $ur['slug'];
    }
}

// Fetch page
if ($sort === 'top-rated') {
    $sql = "SELECT s.id, s.org_name, s.user_id, s.title, s.story, s.created_at, s.service_chains, s.enabling_pillars, s.thematic_categories, IFNULL(s.view_count, 0) as view_count, IFNULL(AVG(r.rating), 0) as avg_rat FROM submissions s LEFT JOIN ratings r ON s.id = r.item_id AND r.item_type = 'submission' WHERE $where GROUP BY s.id ORDER BY $order LIMIT ? OFFSET ?";
} else {
    $sql = "SELECT id, org_name, user_id, title, story, created_at, service_chains, enabling_pillars, thematic_categories, IFNULL(view_count, 0) as view_count FROM submissions WHERE $where ORDER BY $order LIMIT ? OFFSET ?";
}

$fetch_stmt = $conn->prepare($sql);
$fetch_types = $types . 'ii';
$fetch_params = array_merge($params, [$per_page, $offset]);
$fetch_stmt->bind_param($fetch_types, ...$fetch_params);
$fetch_stmt->execute();
$submissions = $fetch_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch media indicators
$sub_ids = array_column($submissions, 'id');
$media_counts = [];
if (!empty($sub_ids)) {
    $in = implode(',', array_fill(0, count($sub_ids), '?'));
    $m_stmt = $conn->prepare("SELECT submission_id, media_type, COUNT(*) as cnt FROM media_uploads WHERE submission_id IN ($in) GROUP BY submission_id, media_type");
    $m_stmt->bind_param(str_repeat('i', count($sub_ids)), ...$sub_ids);
    $m_stmt->execute();
    $m_res = $m_stmt->get_result();
    while ($m_row = $m_res->fetch_assoc()) {
        $media_counts[$m_row['submission_id']][$m_row['media_type']] = $m_row['cnt'];
    }
}

// Fetch batch ratings
$is_logged_in = isset($_SESSION['user_id']);
$current_user_id = $_SESSION['user_id'] ?? 0;
$batch_ratings = get_batch_ratings($conn, 'submission', $sub_ids);
$batch_user_ratings = $is_logged_in ? get_batch_user_ratings($conn, (int) $current_user_id, 'submission', $sub_ids) : [];

// Helper
function ep_clean($text)
{
    return htmlspecialchars(html_entity_decode($text, ENT_QUOTES | ENT_HTML5), ENT_QUOTES | ENT_HTML5);
}

// Build base URL helper for filter/sort links
function ep_url($sub = null, $sort = 'most-viewed', $page = 1)
{
    $params = [];
    if ($sub)
        $params['sub'] = $sub;
    if ($sort !== 'most-viewed')
        $params['sort'] = $sort;
    if ($page > 1)
        $params['page'] = $page;
    $qs = http_build_query($params);
    return 'enabling-pillars.php' . ($qs ? '?' . $qs : '');
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo $active_label ? ep_clean($active_label) . ' — Enabling Pillars' : 'Enabling Pillars'; ?>
        | SaniBook Kenya
    </title>
    <meta name="description" content="Explore the six enabling pillars that drive Kenya's sanitation transformation.">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;900&family=Merriweather:wght@400;700&display=swap"
        rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
    <link rel="icon" href="images/saniBook logo.png" type="image/png">

    <style>
        :root {
            --brand-teal: #008080;
            --brand-navy: #001F3F;
            --brand-gold: #D4AF37;
            --brand-terracotta: #E2725B;
            --brand-ochre: #CC7722;
        }

        .font-heading {
            font-family: 'Montserrat', sans-serif;
        }

        .font-serif {
            font-family: 'Merriweather', serif;
        }

        .pillar-card {
            position: relative;
            padding: 2rem;
            border-radius: 1rem;
            background: linear-gradient(135deg, var(--brand-terracotta), var(--brand-ochre));
            color: white;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(226, 114, 91, 0.3);
            overflow: hidden;
        }

        .pillar-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: translate(30%, -30%);
        }

        .pillar-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 30px rgba(226, 114, 91, 0.4);
        }

        .pillar-card.mhm {
            background: linear-gradient(135deg, #D4AF37, #008080);
        }

        .pillar-card.mhm:hover {
            box-shadow: 0 12px 30px rgba(212, 175, 55, 0.4);
        }

        .stats-counter {
            display: inline-block;
            background: rgba(255, 255, 255, 0.2);
            padding: 0.5rem 1rem;
            border-radius: 2rem;
            font-weight: 700;
            font-size: 0.875rem;
            margin-top: 1rem;
        }

        .icon-badge {
            width: 64px;
            height: 64px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1.5rem;
        }

        .icon-badge i {
            font-size: 2rem;
        }

        .fade-up {
            opacity: 0;
            transform: translateY(30px);
            transition: all 0.6s ease-out;
        }

        .fade-up.visible {
            opacity: 1;
            transform: translateY(0);
        }

        /* Star Rating Styles */
        .star-rating-widget {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-bottom: 8px;
        }

        .star-rating-stars {
            display: flex;
            gap: 2px;
        }

        .star-rating-stars .star {
            color: #cbd5e1;
            font-size: 14px;
            cursor: default;
            transition: color 0.15s, transform 0.15s;
        }

        .star-rating-stars .star.filled {
            color: #facc15;
        }

        .star-rating-stars .star.user-rated {
            color: #f59e0b;
        }

        .star-rating-stars .star.clickable {
            cursor: pointer;
        }

        .star-rating-stars .star.clickable:hover {
            color: #f59e0b;
            transform: scale(1.2);
        }

        .star-rating-info {
            font-size: 11px;
            color: #94a3b8;
            font-weight: 600;
        }
    </style>
</head>

<body class="bg-slate-50 text-slate-900">

    <!-- Navbar -->
    <?php include 'navbar.php'; ?>

    <!-- Title block above hero -->
    <div class="bg-white border-b border-slate-100 py-8 text-center">
        <div class="max-w-7xl mx-auto px-4 flex flex-col items-center">
            <?php if ($active_sub): ?>
                <p class="text-sm font-semibold text-slate-400 uppercase tracking-widest mb-2">
                    <a href="enabling-pillars.php" class="hover:text-orange-500 transition-colors">
                        The Enabling Pillars
                    </a>
                </p>
                <h1 class="font-heading font-black text-2xl md:text-3xl text-slate-900 text-center">
                    <?php echo ep_clean($active_label); ?>
                </h1>
            <?php else: ?>
                <h1 class="font-heading font-black text-2xl md:text-3xl text-slate-900 mb-3 text-center">
                    The <span class="text-orange-500">Enabling Pillars</span>
                </h1>
                <p class="text-xl text-slate-600 max-w-3xl text-center mx-auto">
                    Six foundational systems that support and accelerate Kenya's sanitation transformation.
                </p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Hero Section -->
    <header class="relative overflow-hidden h-[75vh] bg-slate-50">
        <?php if ($active_sub && isset($pillar_images[$active_sub])): ?>
            <!-- Per-pillar hero: clean image, no overlay -->
            <img src="<?php echo ep_clean($pillar_images[$active_sub]['hero']); ?>"
                alt="<?php echo ep_clean($active_label); ?>" class="w-full h-full object-contain object-center">
        <?php else: ?>
            <!-- Main page: clean hero image -->
            <img src="images/enabling_pillars_hero.jpeg" alt="Enabling Pillars"
                class="w-full h-full object-contain object-center">
        <?php endif; ?>
    </header>



    <!-- Compact Category Dashboard -->
    <?php if ($active_sub): ?>
        <?php include 'category_dashboard.php'; ?>
    <?php endif; ?>

    <?php if (!$active_sub): ?>
        <!-- Pillars Grid -->
        <section class="py-20 bg-white">
            <div class="max-w-7xl mx-auto px-4">
                <div class="text-center mb-16">
                    <h2 class="font-heading font-bold text-4xl text-slate-800 mb-4">The Six Pillars</h2>
                    <p class="text-lg text-slate-600 max-w-2xl mx-auto">
                        Cross-cutting systems that enable effective sanitation service delivery across the value chain.
                    </p>
                </div>

                <?php
                $pillar_cards = [
                    'financing' => ['text' => 'Innovative funding mechanisms, blended finance models, and investment strategies.'],
                    'governance' => ['text' => 'Policy frameworks, regulatory coordination, and institutional mandates.'],
                    'research' => ['text' => 'Evidence-based approaches, innovation testing, and knowledge sharing.'],
                    'collaboration' => ['text' => 'Partnerships between government, private sector, NGOs, and communities.'],
                    'capacity-building' => ['text' => 'Training, skill development, and institutional strengthening for sanitation.'],
                    'mhm' => ['text' => 'Dignity, equity, and health for women and girls through menstrual hygiene solutions.'],
                ];
                ?>
                <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
                    <?php foreach ($pillar_cards as $slug => $card): ?>
                        <?php
                        $label = $pillar_map[$slug];
                        $imgSrc = $pillar_images[$slug]['card'] ?? '';
                        ?>
                        <a href="<?php echo ep_url($slug, $sort); ?>"
                            class="group block no-underline rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-all border border-slate-100 bg-white">
                            <?php if ($imgSrc): ?>
                                <div class="relative h-36 overflow-hidden bg-slate-100">
                                    <img src="<?php echo ep_clean($imgSrc); ?>" alt="<?php echo ep_clean($label); ?>"
                                        class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500">
                                    <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
                                    <h3 class="absolute bottom-3 left-4 right-4 font-bold text-white text-xl leading-tight">
                                        <?php echo ep_clean($label); ?>
                                    </h3>
                                </div>
                            <?php endif; ?>
                            <div class="p-5">
                                <p class="text-slate-600 text-sm mb-4"><?php echo ep_clean($card['text']); ?></p>
                                <div
                                    class="inline-flex items-center gap-2 text-xs font-bold text-teal-700 bg-teal-50 px-3 py-1 rounded-full">
                                    <i class="fa-solid fa-chart-line"></i>
                                    <?php echo get_pillar_count($slug); ?> Verified Submissions
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
    <?php endif; ?>

    <!-- Submissions Listing -->
    <section class="py-16 bg-slate-50" id="submissions">
        <div class="max-w-7xl mx-auto px-4">

            <!-- Section Header + Controls -->
            <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-6">
                <div>
                    <h2 class="font-heading font-bold text-xl text-slate-800">
                        <?php echo $active_label ? ep_clean($active_label) : 'All Pillar'; ?> Submissions
                    </h2>
                    <p class="text-xs text-slate-500">
                        <?php echo number_format($total_count); ?> result<?php echo $total_count !== 1 ? 's' : ''; ?>
                    </p>
                </div>

                <!-- Sort Dropdown -->
                <div class="flex items-center gap-2">
                    <label for="sort-select" class="text-sm font-semibold text-slate-600">Sort by:</label>
                    <select id="sort-select" onchange="window.location.href=this.value"
                        class="px-3 py-2 border border-slate-200 rounded-lg bg-white text-sm font-medium text-slate-700 focus:ring-2 focus:ring-orange-400 focus:border-orange-400">
                        <option value="<?php echo ep_url($active_sub, 'most-viewed'); ?>" <?php echo $sort === 'most-viewed' ? 'selected' : ''; ?>>Most Viewed</option>
                        <option value="<?php echo ep_url($active_sub, 'top-rated'); ?>" <?php echo $sort === 'top-rated' ? 'selected' : ''; ?>>Highest Rated</option>
                        <option value="<?php echo ep_url($active_sub, 'newest'); ?>" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>Newest First</option>
                        <option value="<?php echo ep_url($active_sub, 'oldest'); ?>" <?php echo $sort === 'oldest' ? 'selected' : ''; ?>>Oldest First</option>
                        <option value="<?php echo ep_url($active_sub, 'az'); ?>" <?php echo $sort === 'az' ? 'selected' : ''; ?>>A–Z (Org Name)</option>
                    </select>
                </div>
            </div>

            <!-- Filter Pills (Main Category Page) -->
            <?php if (!$active_sub): ?>
                <div class="flex flex-wrap gap-2 mb-8">
                    <a href="<?php echo ep_url(null, $sort); ?>#submissions"
                        class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo !$active_sub ? 'bg-orange-500 text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                        All
                    </a>
                    <?php foreach ($pillar_map as $slug => $label): ?>
                        <a href="<?php echo ep_url($slug, $sort); ?>#submissions"
                            class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $active_sub === $slug ? 'bg-orange-500 text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                            <?php echo ep_clean($label); ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <!-- Sub Category Page: Sidebar for Desktop, Pills for Mobile -->
                <div class="flex flex-col md:flex-row gap-8">
                    <!-- Sidebar -->
                    <div class="w-full md:w-1/4 hidden md:block">
                        <div class="sticky top-24 bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                            <h3 class="font-display font-bold text-lg text-slate-800 mb-4 border-b border-slate-100 pb-2">
                                Filter Submissions</h3>
                            <nav class="space-y-2">
                                <a href="<?php echo ep_url(null, $sort); ?>#submissions"
                                    class="block px-4 py-2 rounded-lg text-sm font-medium transition-all <?php echo !$active_sub ? 'bg-orange-500 text-white' : 'text-slate-600 hover:bg-slate-50 hover:text-orange-500'; ?>">
                                    All Enabling Pillars
                                </a>
                                <?php foreach ($pillar_map as $slug => $label): ?>
                                    <a href="<?php echo ep_url($slug, $sort); ?>#submissions"
                                        class="block px-4 py-2 rounded-lg text-sm font-medium transition-all <?php echo $active_sub === $slug ? 'bg-orange-500 text-white' : 'text-slate-600 hover:bg-slate-50 hover:text-orange-500'; ?>">
                                        <?php echo ep_clean($label); ?>
                                    </a>
                                <?php endforeach; ?>
                            </nav>
                        </div>
                    </div>

                    <!-- Filter Pills (Mobile Only) -->
                    <div class="w-full md:hidden mb-8">
                        <div class="flex flex-wrap gap-2">
                            <a href="<?php echo ep_url(null, $sort); ?>#submissions"
                                class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo !$active_sub ? 'bg-orange-500 text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                All
                            </a>
                            <?php foreach ($pillar_map as $slug => $label): ?>
                                <a href="<?php echo ep_url($slug, $sort); ?>#submissions"
                                    class="px-4 py-2 rounded-full text-sm font-bold transition-all <?php echo $active_sub === $slug ? 'bg-orange-500 text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-100'; ?>">
                                    <?php echo ep_clean($label); ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Main Content Area -->
                    <div class="w-full md:w-3/4">
                    <?php endif; ?>

                    <?php
                    $ep_active_filters = [];
                    if (!empty($f_org))
                        $ep_active_filters[] = ['label' => 'Organisation: ' . ep_clean($f_org), 'param' => 'org'];
                    if (!empty($f_county))
                        $ep_active_filters[] = ['label' => 'County: ' . ep_clean($f_county), 'param' => 'county'];
                    if (!empty($f_sector))
                        $ep_active_filters[] = ['label' => 'Sector: ' . ep_clean($f_sector), 'param' => 'sector'];
                    if (!empty($q))
                        $ep_active_filters[] = ['label' => 'Search: "' . ep_clean($q) . '"', 'param' => 'q'];
                    ?>
                    <?php if (!empty($ep_active_filters)): ?>
                        <div
                            class="flex flex-wrap items-center gap-3 mb-6 p-4 bg-orange-50 border border-orange-200 rounded-xl">
                            <span class="text-sm font-semibold text-orange-800"><i
                                    class="fa-solid fa-filter mr-1.5"></i>Filtering by:</span>
                            <?php foreach ($ep_active_filters as $af): ?>
                                <?php
                                $clear_params = $_GET;
                                unset($clear_params[$af['param']]);
                                $clear_url = '?' . http_build_query($clear_params) . '#submissions';
                                ?>
                                <span
                                    class="inline-flex items-center gap-1.5 px-3 py-1 bg-orange-600 text-white text-xs font-bold rounded-full">
                                    <?php echo $af['label']; ?>
                                    <a href="<?php echo htmlspecialchars($clear_url); ?>"
                                        class="hover:text-orange-200 transition-colors" title="Remove this filter">
                                        <i class="fa-solid fa-xmark"></i>
                                    </a>
                                </span>
                            <?php endforeach; ?>
                            <a href="<?php echo ep_url($active_sub, $sort); ?>#submissions"
                                class="ml-auto text-xs font-semibold text-orange-700 hover:text-orange-900 hover:underline flex items-center gap-1">
                                <i class="fa-solid fa-rotate-left"></i> Clear All Filters
                            </a>
                        </div>
                    <?php endif; ?>

                    <!-- Submissions Grid -->
                    <?php if (empty($submissions)): ?>
                        <div class="text-center py-20">
                            <i class="fa-solid fa-inbox text-6xl text-slate-300 mb-4"></i>
                            <p class="text-xl text-slate-500">No submissions
                                found<?php echo $active_label ? ' for ' . ep_clean($active_label) : ''; ?>.</p>
                            <a href="<?php echo isset($_SESSION['user_id']) ? 'submit-data.php' : 'signup.php?redirect=submit-data.php'; ?>"
                                class="inline-block mt-4 px-6 py-3 bg-orange-500 text-white rounded-lg hover:bg-orange-600 font-bold transition-colors">
                                <i class="fa-solid fa-plus mr-2"></i>Submit Data
                            </a>
                        </div>
                    <?php else: ?>
                        <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6 fade-up">
                            <?php foreach ($submissions as $sub): ?>
                                <div
                                    class="bg-slate-800 rounded-xl p-6 shadow-md hover:shadow-xl transition-all border border-slate-700 flex flex-col h-full">
                                    <!-- Header -->
                                    <div class="flex items-center justify-between mb-3">
                                        <?php 
                                        $org_clean = ep_clean($sub['org_name']);
                                        $u_id = $sub['user_id'] ?? 0;
                                        $p_slug = $slug_map[$u_id] ?? '';
                                        if (!empty($p_slug)): 
                                        ?>
                                            <a href="/profile/<?php echo htmlspecialchars($p_slug); ?>" onclick="event.stopPropagation()" class="text-xs font-bold uppercase text-orange-400 tracking-wider truncate max-w-[60%] hover:text-orange-300 hover:underline transition-colors" title="View <?php echo htmlspecialchars($org_clean); ?> profile">
                                                <?php echo $org_clean; ?>
                                            </a>
                                        <?php else: ?>
                                            <span class="text-xs font-bold uppercase text-orange-400 tracking-wider truncate max-w-[60%]">
                                                <?php echo $org_clean; ?>
                                            </span>
                                        <?php endif; ?>
                                        <div class="flex items-center gap-2 text-xs text-slate-400 shrink-0">
                                            <span><?php echo date('M d, Y', strtotime($sub['created_at'])); ?></span>
                                            <span title="<?php echo number_format((int) $sub['view_count']); ?> views"
                                                class="flex items-center gap-1">
                                                <i
                                                    class="fa-regular fa-eye"></i><?php echo number_format((int) $sub['view_count']); ?>
                                            </span>
                                        </div>
                                    </div>

                                    <!-- Title -->
                                    <h3 class="font-bold text-base text-white mb-2 line-clamp-2">
                                        <a href="view_submission.php?id=<?php echo $sub['id']; ?>"
                                            class="hover:text-orange-400 transition-colors">
                                            <?php echo ep_clean($sub['title']); ?>
                                        </a>
                                    </h3>

                                    <!-- Excerpt -->
                                    <?php if (!empty($sub['story'])): ?>
                                        <div class="text-slate-400 text-sm mb-4 line-clamp-3">
                                            <?php echo htmlspecialchars(mb_strimwidth(strip_tags($sub['story']), 0, 200, '...')); ?>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Cross-Category Badges -->
                                    <?php
                                    $sub_pillars = json_decode($sub['enabling_pillars'] ?? '[]', true) ?: [];
                                    $sub_chains = json_decode($sub['service_chains'] ?? '[]', true) ?: [];
                                    if (!empty($sub_pillars) || !empty($sub_chains)):
                                        ?>
                                        <div class="flex flex-wrap gap-1.5 mb-3">
                                            <?php foreach ($sub_pillars as $pill): 
                                                $cat_url = 'submitted.php?subcategory=' . urlencode($pill);
                                            ?>
                                                <a href="<?php echo htmlspecialchars($cat_url); ?>" onclick="event.stopPropagation()"
                                                    class="px-2 py-0.5 bg-orange-900/40 text-orange-300 text-[10px] font-bold rounded-full border border-orange-700 hover:bg-orange-800/80 hover:text-orange-200 transition-colors cursor-pointer">
                                                    <?php echo ep_clean($pill); ?>
                                                </a>
                                            <?php endforeach; ?>
                                            <?php foreach ($sub_chains as $chain): 
                                                $cat_url = 'submitted.php?subcategory=' . urlencode($chain);
                                            ?>
                                                <a href="<?php echo htmlspecialchars($cat_url); ?>" onclick="event.stopPropagation()"
                                                    class="px-2 py-0.5 bg-teal-900/60 text-teal-300 text-[10px] font-bold rounded-full border border-teal-700 hover:bg-teal-800/80 hover:text-teal-200 transition-colors cursor-pointer">
                                                    <i class="fa-solid fa-link text-[8px] mr-0.5"></i><?php echo ep_clean($chain); ?>
                                                </a>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>

                                    <div class="mt-auto"></div>

                                    <!-- Media Indicators -->
                                    <?php if (isset($media_counts[$sub['id']])): ?>
                                        <div class="flex gap-2 mb-3">
                                            <?php if (!empty($media_counts[$sub['id']]['image'])): ?>
                                                <span
                                                    class="text-[10px] text-slate-400 bg-slate-700 px-1.5 py-0.5 rounded border border-slate-600"
                                                    title="Images"><i class="fa-regular fa-image"></i>
                                                    <?php echo $media_counts[$sub['id']]['image']; ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($media_counts[$sub['id']]['video'])): ?>
                                                <span
                                                    class="text-[10px] text-slate-400 bg-slate-700 px-1.5 py-0.5 rounded border border-slate-600"
                                                    title="Videos"><i class="fa-solid fa-video"></i>
                                                    <?php echo $media_counts[$sub['id']]['video']; ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($media_counts[$sub['id']]['audio'])): ?>
                                                <span
                                                    class="text-[10px] text-slate-400 bg-slate-700 px-1.5 py-0.5 rounded border border-slate-600"
                                                    title="Audio"><i class="fa-solid fa-microphone"></i>
                                                    <?php echo $media_counts[$sub['id']]['audio']; ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($media_counts[$sub['id']]['pdf'])): ?>
                                                <span
                                                    class="text-[10px] text-slate-400 bg-slate-700 px-1.5 py-0.5 rounded border border-slate-600"
                                                    title="PDFs"><i class="fa-regular fa-file-pdf"></i>
                                                    <?php echo $media_counts[$sub['id']]['pdf']; ?></span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Star Rating -->
                                    <?php
                                    $r_avg = $batch_ratings[$sub['id']]['avg'] ?? 0;
                                    $r_cnt = $batch_ratings[$sub['id']]['count'] ?? 0;
                                    $r_user = $batch_user_ratings[$sub['id']] ?? 0;
                                    echo render_stars($r_avg, $r_cnt, 'submission', $sub['id'], $r_user, $is_logged_in);
                                    ?>

                                    <!-- Footer -->
                                    <div class="pt-4 border-t border-slate-700 flex items-center justify-between mt-2">
                                        <a href="view_submission.php?id=<?php echo $sub['id']; ?>"
                                            class="text-orange-400 font-semibold text-sm hover:text-orange-300 flex items-center">
                                            Read More <i class="fa-solid fa-arrow-right ml-2"></i>
                                        </a>
                                        <span class="text-xs text-slate-500 flex items-center gap-1" title="Views">
                                            <i class="fa-solid fa-eye"></i>
                                            <?php echo number_format($sub['view_count']); ?>
                                        </span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <div class="flex items-center justify-center gap-2 mt-12">
                                <?php if ($page_num > 1): ?>
                                    <a href="<?php echo ep_url($active_sub, $sort, $page_num - 1); ?>#submissions"
                                        class="px-4 py-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 font-semibold text-slate-700">
                                        <i class="fa-solid fa-chevron-left mr-1"></i> Previous
                                    </a>
                                <?php endif; ?>

                                <span class="px-4 py-2 text-slate-600 font-semibold">
                                    Page <?php echo $page_num; ?> of <?php echo $total_pages; ?>
                                </span>

                                <?php if ($page_num < $total_pages): ?>
                                    <a href="<?php echo ep_url($active_sub, $sort, $page_num + 1); ?>#submissions"
                                        class="px-4 py-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 font-semibold text-slate-700">
                                        Next <i class="fa-solid fa-chevron-right ml-1"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                    <?php if ($active_sub): ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <!-- Data Submission CTA -->
    <section class="py-16 bg-gradient-to-r from-orange-500 to-orange-600">
        <div class="max-w-4xl mx-auto px-4 text-center text-white">
            <h2 class="font-heading font-bold text-3xl mb-4">
                Contribute Your Pillar Insights
            </h2>
            <p class="text-lg mb-8 text-orange-100">
                Share your financing models, governance frameworks, research findings, partnerships, or MHM initiatives.
            </p>
            <a href="thematic-repositories.php#portal"
                class="inline-block px-8 py-4 bg-white text-orange-600 font-bold rounded-xl hover:bg-slate-100 shadow-lg">
                <i class="fa-solid fa-upload mr-2"></i> Submit Your Data
            </a>
        </div>
    </section>

    <!-- Footer -->
    <?php include 'footer.php'; ?>

    <script>
        // Fade-up animation on scroll
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) entry.target.classList.add('visible');
            });
        }, { threshold: 0.1 });
        document.querySelectorAll('.fade-up').forEach(el => observer.observe(el));

    </script>
    <script src="assets/js/star-rating.js"></script>

    <!-- Auto-scroll to results when filters are active -->
    <script src="assets/js/filter-scroll.js"></script>
</body>

</html>