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

// Fetch all verified submissions, ordered by most recent
$limit = 24; // Show 24 latest submissions per page
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// Updated query to fetch category fields including role
$stmt = $conn->prepare("SELECT id, org_name, title, story, created_at, role, service_chains, enabling_pillars, thematic_categories FROM submissions WHERE is_verified = 1 ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
$submissions = $result->fetch_all(MYSQLI_ASSOC);

// Get total count for pagination
$count_stmt = $conn->prepare("SELECT COUNT(*) as total FROM submissions WHERE is_verified = 1");
$count_stmt->execute();
$total_count = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_count / $limit);

// Collect all category IDs to fetch names in one go
$all_cat_ids = [];
foreach ($submissions as $key => $sub) {
    $chains = json_decode($sub['service_chains'] ?? '[]', true) ?: [];
    $pillars = json_decode($sub['enabling_pillars'] ?? '[]', true) ?: [];
    $themes = json_decode($sub['thematic_categories'] ?? '[]', true) ?: [];

    // Prioritize them: specific theme > pillar > chain (arbitrary, can be changed)
    // Or just merge them all. Let's merge and pick the first one for display.
    $cats = array_merge($themes, $pillars, $chains);

    $submissions[$key]['cats'] = $cats;
    $all_cat_ids = array_merge($all_cat_ids, $cats);
}

// 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 category names
// Fetch category names for Thematic Repositories
$cat_map = [];
if (!empty($all_cat_ids)) {
    $all_cat_ids = array_unique($all_cat_ids);
    // Filter out non-numeric IDs (since we merged strings and IDs)
    $valid_ids = array_filter($all_cat_ids, 'is_numeric');

    if (!empty($valid_ids)) {
        $placeholders = implode(',', array_fill(0, count($valid_ids), '?'));
        $types = str_repeat('i', count($valid_ids));
        $cat_stmt = $conn->prepare("SELECT id, title FROM categories WHERE id IN ($placeholders)");
        $cat_stmt->bind_param($types, ...$valid_ids);
        $cat_stmt->execute();
        $cat_res = $cat_stmt->get_result();
        while ($row = $cat_res->fetch_assoc()) {
            $cat_map[$row['id']] = $row['title'];
        }
    }
}

// Pillar Slug Map
$pillar_slugs = [
    'Financing' => 'financing',
    'Governance' => 'governance',
    'Research & Learning' => 'research',
    'Collaboration' => 'collaboration',
    'Menstrual Health Management' => 'mhm'
];

// Helper for clean output
function clean_out($text)
{
    return htmlspecialchars(html_entity_decode($text, ENT_QUOTES | ENT_HTML5), ENT_QUOTES | ENT_HTML5);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submitted Works | SaniBook Kenya</title>
    <meta name="description"
        content="Explore the latest verified sanitation projects and initiatives from across Kenya.">
    <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;
        }

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

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

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

        .fade-up.visible {
            opacity: 1;
            transform: translateY(0);
        }
    </style>
</head>

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

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

    <!-- Hero Section -->
    <header class="pt-32 pb-16 bg-gradient-to-br from-teal-600 to-teal-800">
        <div class="max-w-7xl mx-auto px-4 text-center text-white">
            <div class="w-20 h-20 rounded-full bg-white/20 flex items-center justify-center mx-auto mb-6">
                <i class="fa-solid fa-clock-rotate-left text-4xl"></i>
            </div>
            <h1 class="font-heading font-black text-5xl md:text-6xl mb-6">
                Submitted Works
            </h1>
            <p class="text-xl text-teal-100 max-w-3xl mx-auto mb-4">
                Discover the most recent verified sanitation projects and initiatives from organizations across Kenya.
            </p>
            <div class="flex items-center justify-center gap-2 text-teal-200">
                <i class="fa-solid fa-check-circle"></i>
                <span class="font-semibold">
                    <?php echo number_format($total_count); ?> Verified Submissions
                </span>
            </div>
        </div>
    </header>

    <!-- Submissions Grid -->
    <section class="py-16 bg-slate-50">
        <div class="max-w-7xl mx-auto px-4">
            <?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.</p>
                </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="block bg-white rounded-xl p-6 shadow-sm hover:shadow-md transition-all border border-slate-100 group h-full flex flex-col relative">

                            <!-- Badges & Meta -->
                            <div class="mb-4">
                                <div class="flex items-center justify-between mb-3">
                                    <span class="text-xs font-bold uppercase text-teal-600 tracking-wider truncate max-w-[40%]">
                                        <?php echo clean_out($sub['org_name']); ?>
                                    </span>

                                    <!-- Top Right: Sub-Categories (Tags) -->
                                    <div class="flex flex-wrap justify-end gap-1.5 max-w-[55%]">
                                        <?php
                                        // 1. Service Chains (Links to service-chain.php)
                                        $chains = json_decode($sub['service_chains'] ?? '[]', true) ?: [];
                                        foreach ($chains as $chain) {
                                            $encoded_chain = urlencode($chain);
                                            echo "<a href='service-chain.php' class='px-2 py-0.5 bg-blue-50 text-blue-600 rounded text-[10px] font-bold border border-blue-100 hover:bg-blue-100 transition-colors truncate max-w-[100px]'>" . clean_out($chain) . "</a>";
                                        }

                                        // 2. Pillars (Links to enabling-pillars.php)
                                        $pillars = json_decode($sub['enabling_pillars'] ?? '[]', true) ?: [];
                                        foreach ($pillars as $pillar) {
                                            $slug = $pillar_slugs[$pillar] ?? 'financing';
                                            echo "<a href='enabling-pillars.php?pillar=$slug' class='px-2 py-0.5 bg-orange-50 text-orange-600 rounded text-[10px] font-bold border border-orange-100 hover:bg-orange-100 transition-colors truncate max-w-[100px]'>" . clean_out($pillar) . "</a>";
                                        }

                                        // 3. Thematic (Links to thematic-repositories.php)
                                        $themes = json_decode($sub['thematic_categories'] ?? '[]', true) ?: [];
                                        foreach ($themes as $tid) {
                                            if (isset($cat_map[$tid])) {
                                                echo "<a href='thematic-repositories.php?id=$tid' class='px-2 py-0.5 bg-teal-50 text-teal-600 rounded text-[10px] font-bold border border-teal-100 hover:bg-teal-100 transition-colors truncate max-w-[100px]'>" . clean_out($cat_map[$tid]) . "</a>";
                                            }
                                        }
                                        ?>
                                    </div>
                                </div>

                                <h3 class="font-bold text-xl text-slate-800 mt-1 mb-2 line-clamp-2">
                                    <a href="view_submission.php?id=<?php echo $sub['id']; ?>"
                                        class="group-hover:text-teal-600 transition-colors">
                                        <?php echo clean_out($sub['title']); ?>
                                    </a>
                                </h3>

                                <div class="text-slate-600 text-sm line-clamp-3 prose prose-sm max-w-none">
                                    <?php
                                    // Decode HTML entities in Data Content (it's HTML stored as text sometimes)
                                    // Use html_entity_decode to fix double encoded entities if present
                                    echo html_entity_decode($sub['story']);
                                    ?>
                                </div>
                            </div>

                            <!-- Footer -->
                            <div class="mt-auto pt-4 border-t border-slate-100 text-xs text-slate-500 flex flex-col gap-2">

                                <!-- Categories a post is in (Role) -->
                                <?php if (!empty($sub['role'])): ?>
                                    <div class="font-bold text-slate-400 uppercase tracking-wider text-[10px]">
                                        <i class="fa-solid fa-tag mr-1"></i> <?php echo clean_out($sub['role']); ?>
                                    </div>
                                <?php endif; ?>

                                <div class="flex justify-between items-center w-full">
                                    <span><i class="fa-regular fa-calendar mr-1"></i>
                                        <?php echo date('M d, Y', strtotime($sub['created_at'])); ?>
                                    </span>
                                    <a href="view_submission.php?id=<?php echo $sub['id']; ?>"
                                        class="text-teal-600 font-semibold group-hover:text-teal-700 flex items-center">
                                        Read More <i class="fa-solid fa-arrow-right ml-1"></i>
                                    </a>
                                </div>

                                <!-- Media Indicators -->
                                <?php if (isset($media_counts[$sub['id']])): ?>
                                    <div class="flex gap-2 mt-2 pt-2 border-t border-slate-50 w-full">
                                        <?php if (!empty($media_counts[$sub['id']]['image'])): ?>
                                            <span
                                                class="text-[10px] text-slate-500 bg-slate-50 px-1.5 py-0.5 rounded border border-slate-100"
                                                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-500 bg-slate-50 px-1.5 py-0.5 rounded border border-slate-100"
                                                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-500 bg-slate-50 px-1.5 py-0.5 rounded border border-slate-100"
                                                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-500 bg-slate-50 px-1.5 py-0.5 rounded border border-slate-100"
                                                title="PDFs"><i class="fa-regular fa-file-pdf"></i>
                                                <?php echo $media_counts[$sub['id']]['pdf']; ?></span>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </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 > 1): ?>
                            <a href="?page=<?php echo $page - 1; ?>"
                                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; ?> of
                            <?php echo $total_pages; ?>
                        </span>

                        <?php if ($page < $total_pages): ?>
                            <a href="?page=<?php echo $page + 1; ?>"
                                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; ?>
        </div>
    </section>

    <!-- Footer -->
    <!-- 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>

</body>

</html>