<?php
session_start();
// Navbar included in body
include 'config.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 1;
$is_portal = ($id === 9);

// 1. Fetch Current Category from DB

$stmt = $conn->prepare("SELECT * FROM categories WHERE id = ?");
if ($stmt) {
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $page = $stmt->get_result()->fetch_assoc();
} else {
    $page = null;
}

if (!$page) {
    header("Location: index.php");
    exit;
}

// 2. Fetch All Categories for Sidebar
$sidebar_categories = $conn->query("SELECT id, title, icon, color FROM categories ORDER BY id ASC");
if (!$sidebar_categories) {
    $sidebar_categories = []; // Fallback to empty array
}

// 3. Fetch Stakeholders for this Category
// Search by category title in thematic_categories JSON, OR legacy category_id
$cat_title = $page['title'] ?? '';
$stakeholder_stmt = $conn->prepare("SELECT org_name, role, county, story, created_at, contact_role, contact_person, service_chains, enabling_pillars, thematic_categories FROM submissions WHERE is_verified = 1 AND (thematic_categories LIKE ? OR category_id = ?) ORDER BY created_at DESC");
if ($stakeholder_stmt) {
    $like_val = '%"' . $conn->real_escape_string($cat_title) . '"%';
    $stakeholder_stmt->bind_param("si", $like_val, $id);
    $stakeholder_stmt->execute();
    $stakeholders = $stakeholder_stmt->get_result();
} else {
    $stakeholders = null;
}

$current_image = !empty($page['image_file']) ? $page['image_file'] : "nexus_intro.jpg";
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo $page['title']; ?> | SaniBook
    </title>
    <!-- Favicon -->
    <link rel="icon" href="images/saniBook logo.png" type="image/png">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        brand: { dark: '#001F3F', teal: '#008080', gold: '#D4AF37', red: '#dc2626' }
                    },
                    fontFamily: { sans: ['Inter', 'sans-serif'], display: ['Space Grotesk', 'sans-serif'] }
                }
            }
        }
    </script>
    <style>
        .sidebar-link.active {
            background-color: #008080;
            color: white;
            border-left: 4px solid #D4AF37;
        }

        .badge-ngo {
            background-color: #dcfce7;
            color: #166534;
        }

        .badge-private {
            background-color: #dbeafe;
            color: #1e40af;
        }

        .badge-gov {
            background-color: #f3e8ff;
            color: #6b21a8;
        }

        .badge-innovator {
            background-color: #fef9c3;
            color: #854d0e;
        }

        .badge-community {
            background-color: #ffedd5;
            color: #9a3412;
        }

        .badge-default {
            background-color: #f1f5f9;
            color: #475569;
        }

        /* Left Accent Strips */
        .accent-ngo {
            border-left: 4px solid #008080 !important;
        }

        .accent-government {
            border-left: 4px solid #001F3F !important;
        }

        .accent-service_provider {
            border-left: 4px solid #D4AF37 !important;
        }

        .accent-default {
            border-left: 4px solid #cbd5e1 !important;
        }
    </style>
</head>

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

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



    <div class="max-w-7xl mx-auto px-4 py-8">
        <div class="grid lg:grid-cols-12 gap-8">

            <div class="lg:col-span-3 hidden lg:block">
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden sticky top-24">
                    <div class="p-4 bg-slate-100 border-b border-slate-200">
                        <h3 class="font-bold text-slate-700 uppercase text-xs tracking-wider">Barriers</h3>
                    </div>
                    <div class="flex flex-col">
                        <?php if ($sidebar_categories instanceof mysqli_result): ?>
                            <?php while ($chapter = $sidebar_categories->fetch_assoc()):
                                $key = (int) $chapter['id'];
                                ?>
                                <a href="category.php?id=<?php echo $key; ?>"
                                    class="sidebar-link px-4 py-3 text-sm font-medium border-b border-slate-50 hover:bg-slate-50 transition-colors flex items-center gap-3 <?php echo ($key === $id) ? 'active' : 'text-slate-600'; ?>">
                                    <div
                                        class="w-6 h-6 rounded flex items-center justify-center <?php echo ($key === $id) ? 'text-white' : $chapter['color']; ?>">
                                        <i class="fa-solid <?php echo $chapter['icon']; ?>"></i>
                                    </div>
                                    <span class="line-clamp-1"><?php echo $chapter['title']; ?></span>
                                </a>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="p-4 text-xs text-slate-400 italic text-center">No repositories found.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="lg:col-span-9">

                <div class="bg-white rounded-2xl p-8 shadow-sm border border-slate-200 mb-8 relative overflow-hidden">
                    <div class="absolute top-0 right-0 p-4 opacity-5">
                        <i class="fa-solid <?php echo $page['icon']; ?> text-9xl"></i>
                    </div>

                    <div class="relative z-10">
                        <span
                            class="inline-block px-3 py-1 bg-brand-teal/10 text-brand-teal text-xs font-bold rounded-full mb-3">
                            Chapter 0<?php echo $id; ?>
                        </span>
                        <h1 class="text-3xl md:text-4xl font-display font-bold text-slate-900 mb-2">
                            <?php echo $page['title']; ?>
                        </h1>
                        <?php if (!empty($page['short_desc'])): ?>
                            <h2 class="text-xl text-slate-500 mb-6 font-medium">
                                <?php echo htmlspecialchars($page['short_desc']); ?>
                            </h2>
                        <?php endif; ?>

                        <div class="prose max-w-none text-slate-600 leading-relaxed">
                            <?php echo $page['full_desc']; ?>
                        </div>
                    </div>
                </div>

                <!-- Tab Navigation -->
                <div class="flex border-b border-slate-200 mb-8" role="tablist">
                    <button onclick="switchTab('overview')" id="btn-overview"
                        class="tab-btn py-3 px-6 border-b-2 border-brand-teal font-bold text-brand-teal focus:outline-none transition-colors">
                        Overview
                    </button>
                    <button onclick="switchTab('chronicles')" id="btn-chronicles"
                        class="tab-btn py-3 px-6 border-b-2 border-transparent font-bold text-slate-500 hover:text-brand-teal focus:outline-none transition-colors">
                        Sanitation Chronicles
                    </button>
                    <button onclick="switchTab('data')" id="btn-data"
                        class="tab-btn py-3 px-6 border-b-2 border-transparent font-bold text-slate-500 hover:text-brand-teal focus:outline-none transition-colors">
                        Impact data
                    </button>
                </div>

                <!-- Tab Content: Overview -->
                <div id="tab-overview" class="tab-content block">
                    <div class="grid md:grid-cols-12 gap-8">
                        <div class="md:col-span-5">
                            <div class="sticky top-24">
                                <img src="images/<?php echo $current_image; ?>" alt="<?php echo $page['title']; ?>"
                                    class="w-full rounded-xl shadow-lg object-cover aspect-video mb-6 ring-1 ring-slate-900/5">

                                <div class="bg-blue-50 border border-blue-100 rounded-lg p-4">
                                    <h4 class="font-bold text-blue-900 text-sm mb-2"><i
                                            class="fa-solid fa-lightbulb mr-2"></i>Did You Know?</h4>
                                    <p class="text-xs text-blue-800 leading-relaxed">
                                        Your data contributes to the National Sanitation Strategy. By completing this
                                        form,
                                        you help visualize the gaps and opportunities in Kenya's sanitation sector.
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div class="md:col-span-7">
                            <div class="bg-white rounded-xl shadow-lg border border-slate-200 p-8 relative text-center">
                                <div
                                    class="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-brand-teal to-brand-gold rounded-t-xl">
                                </div>

                                <div
                                    class="w-16 h-16 bg-brand-gold/10 rounded-2xl flex items-center justify-center mx-auto mb-6">
                                    <i class="fa-solid fa-pen-nib text-brand-gold text-2xl"></i>
                                </div>

                                <h3 class="font-display text-xl font-bold text-slate-900 mb-3">Contribute Insights</h3>
                                <p class="text-slate-600 text-sm mb-6 max-w-md mx-auto">
                                    Share your sanitation data, impact data, and chronicles through our unified
                                    submission portal.
                                    Registered users can submit data using their tokens.
                                </p>

                                <a href="submit.php"
                                    class="inline-flex items-center gap-2 px-8 py-3 bg-brand-dark text-white font-bold rounded-lg hover:bg-slate-800 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 active:translate-y-0 transition-all">
                                    <i class="fa-solid fa-upload"></i>
                                    <span>Submit Data</span>
                                </a>

                                <p class="text-xs text-slate-400 mt-4">
                                    Don't have an account? <a href="submit-data.php"
                                        class="text-brand-teal font-semibold hover:underline">Register here</a>
                                </p>
                            </div>
                        </div>

                    </div>

                    <!-- Stakeholder Card List Section -->
                    <?php if ($stakeholders instanceof mysqli_result && $stakeholders->num_rows > 0): ?>
                        <div class="mt-12">
                            <h3 class="font-display text-2xl font-bold text-slate-900 mb-6 flex items-center gap-3">
                                <span
                                    class="bg-brand-teal text-white w-10 h-10 rounded-xl flex items-center justify-center">
                                    <i class="fa-solid fa-handshake"></i>
                                </span>
                                Existing Stakeholders (<?php echo $stakeholders->num_rows; ?>)
                            </h3>

                            <div class="flex flex-col gap-4">
                                <?php
                                $accent_classes = [
                                    'ngo' => 'accent-ngo',
                                    'dev_partner' => 'accent-ngo',
                                    'government' => 'accent-government',
                                    'gov_agency' => 'accent-government',
                                    'regulator' => 'accent-government',
                                    'service_provider' => 'accent-service_provider',
                                    'wsp' => 'accent-service_provider',
                                    'academic' => 'accent-default',
                                    'social_enterprise' => 'accent-innovator'
                                ];
                                $role_names = [
                                    'ngo' => 'NGO',
                                    'dev_partner' => 'Dev. Partner',
                                    'service_provider' => 'Service Provider',
                                    'private_sector' => 'Private Sector',
                                    'wsp' => 'Water Utility',
                                    'government' => 'Government',
                                    'gov_agency' => 'Govt. Agency',
                                    'regulator' => 'Regulator',
                                    'academic' => 'Academic',
                                    'individual' => 'Individual',
                                    'social_enterprise' => 'Social Ent.',
                                    'innovator' => 'Innovator',
                                    'financer' => 'Financer',
                                    'community' => 'Community Group'
                                ];
                                while ($s = $stakeholders->fetch_assoc()):
                                    $accent_class = $accent_classes[$s['role']] ?? 'accent-default';
                                    $role_name = $role_names[$s['role']] ?? ucfirst(str_replace('_', ' ', $s['role']));
                                    $date = date("M Y", strtotime($s['created_at']));
                                    $snippet = strip_tags($s['story']);
                                    if (strlen($snippet) > 150) {
                                        $snippet = substr($snippet, 0, 150) . "...";
                                    }
                                    ?>
                                    <?php
                                    $s_chains = json_decode($s['service_chains'] ?? '[]', true) ?: [];
                                    $s_pillars = json_decode($s['enabling_pillars'] ?? '[]', true) ?: [];
                                    $s_themes = json_decode($s['thematic_categories'] ?? '[]', true) ?: [];
                                    ?>
                                    <div
                                        class="w-full bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 border border-gray-200 mb-4 overflow-hidden flex flex-col md:flex-row <?php echo $accent_class; ?>">
                                        <div class="p-6 flex-grow">
                                            <div class="flex items-center gap-3 mb-2">
                                                <h4 class="text-xl font-bold text-brand-dark">
                                                    <?php echo htmlspecialchars($s['org_name']); ?>
                                                </h4>
                                                <span
                                                    class="px-3 py-1 bg-brand-teal text-white text-[10px] font-bold rounded-full uppercase tracking-wider">
                                                    <?php echo htmlspecialchars($role_name); ?>
                                                </span>
                                            </div>

                                            <div class="flex flex-wrap items-center gap-2 text-slate-500 text-sm mb-3">
                                                <span class="flex items-center">
                                                    <i class="fas fa-map-marker-alt text-brand-gold mr-1.5"></i>
                                                    <?php echo htmlspecialchars($s['county']); ?>
                                                </span>
                                                <span class="flex items-center ml-0 md:ml-4">
                                                    <i class="fas fa-user text-brand-gold mr-1.5"></i>
                                                    <?php echo htmlspecialchars($s['contact_person']); ?>
                                                </span>
                                                <span class="flex items-center ml-0 md:ml-4">
                                                    <i class="fas fa-clock text-brand-gold mr-1.5"></i>
                                                    <?php echo $date; ?>
                                                </span>
                                            </div>

                                            <?php if (!empty($s_chains) || !empty($s_pillars) || !empty($s_themes)): ?>
                                                <div class="flex flex-wrap gap-1.5 mb-3">
                                                    <?php foreach ($s_chains as $chain): ?>
                                                        <span
                                                            class="px-2 py-0.5 bg-teal-50 text-teal-700 text-[10px] font-bold rounded-full border border-teal-200">
                                                            <i
                                                                class="fa-solid fa-link text-[8px] mr-0.5"></i><?php echo htmlspecialchars($chain); ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                    <?php foreach ($s_pillars as $pill): ?>
                                                        <span
                                                            class="px-2 py-0.5 bg-orange-50 text-orange-700 text-[10px] font-bold rounded-full border border-orange-200">
                                                            <i
                                                                class="fa-solid fa-cubes text-[8px] mr-0.5"></i><?php echo htmlspecialchars($pill); ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                    <?php foreach ($s_themes as $theme): ?>
                                                        <span
                                                            class="px-2 py-0.5 bg-purple-50 text-purple-700 text-[10px] font-bold rounded-full border border-purple-200">
                                                            <i
                                                                class="fa-solid fa-tag text-[8px] mr-0.5"></i><?php echo htmlspecialchars($theme); ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>

                                            <p class="text-gray-500 italic text-sm line-clamp-1">
                                                "<?php echo htmlspecialchars($snippet); ?>"
                                            </p>
                                        </div>

                                        <div
                                            class="flex items-center justify-center p-6 bg-slate-50/50 md:bg-transparent border-t md:border-t-0 md:border-l border-gray-100 min-w-[160px]">
                                            <!-- Profile button hidden until profile pages are available -->
                                            <!--
                                            <a href="#"
                                                class="px-6 py-2 border-2 border-brand-dark text-brand-dark font-bold text-xs uppercase tracking-widest rounded-lg hover:bg-brand-dark hover:text-white transition-all">
                                                View Profile
                                            </a>
                                            -->
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Tab Content: Chronicles -->
                <div id="tab-chronicles" class="tab-content hidden">
                    <h3 class="font-display text-2xl font-bold text-slate-900 mb-6">Sanitation Chronicles</h3>
                    <div class="space-y-4">
                        <?php
                        $chronicles = $conn->query("SELECT id, title, created_at, body FROM content WHERE category_id = $id AND type = 'chronicle' ORDER BY created_at DESC");
                        if ($chronicles && $chronicles->num_rows > 0):
                            while ($row = $chronicles->fetch_assoc()):
                                $date = date("F j, Y", strtotime($row['created_at']));
                                $snippet = strip_tags($row['body']);
                                if (strlen($snippet) > 200)
                                    $snippet = substr($snippet, 0, 200) . '...';
                                ?>
                                <div
                                    class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 hover:shadow-md transition-all">
                                    <a href="view_content.php?id=<?php echo $row['id']; ?>" class="group">
                                        <h4 class="text-xl font-bold text-brand-dark group-hover:text-brand-teal mb-2">
                                            <?php echo htmlspecialchars($row['title']); ?>
                                        </h4>
                                    </a>
                                    <p class="text-sm text-slate-400 mb-3"><i
                                            class="fa-solid fa-calendar-day mr-2"></i><?php echo $date; ?></p>
                                    <p class="text-slate-600 mb-4"><?php echo $snippet; ?></p>
                                    <a href="view_content.php?id=<?php echo $row['id']; ?>"
                                        class="text-brand-teal font-bold text-sm uppercase tracking-wide hover:underline">Read
                                        Chronicle <i class="fa-solid fa-arrow-right ml-1"></i></a>
                                </div>
                            <?php endwhile; else: ?>
                            <p class="text-slate-500 italic">No chronicles found for this chapter.</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Tab Content: Impact data -->
                <div id="tab-data" class="tab-content hidden">
                    <h3 class="font-display text-2xl font-bold text-slate-900 mb-6">Impact data</h3>
                    <div class="space-y-4">
                        <?php
                        $data = $conn->query("SELECT id, title, created_at, body FROM content WHERE category_id = $id AND type = 'story' ORDER BY created_at DESC");
                        if ($data && $data->num_rows > 0):
                            while ($row = $data->fetch_assoc()):
                                $date = date("F j, Y", strtotime($row['created_at']));
                                $snippet = strip_tags($row['body']);
                                if (strlen($snippet) > 200)
                                    $snippet = substr($snippet, 0, 200) . '...';
                                ?>
                                <div
                                    class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 hover:shadow-md transition-all border-l-4 border-l-brand-gold">
                                    <a href="view_content.php?id=<?php echo $row['id']; ?>" class="group">
                                        <h4 class="text-xl font-bold text-brand-dark group-hover:text-brand-teal mb-2">
                                            <?php echo htmlspecialchars($row['title']); ?>
                                        </h4>
                                    </a>
                                    <p class="text-sm text-slate-400 mb-3"><i
                                            class="fa-solid fa-calendar-day mr-2"></i><?php echo $date; ?></p>
                                    <p class="text-slate-600 mb-4"><?php echo $snippet; ?></p>
                                    <a href="view_content.php?id=<?php echo $row['id']; ?>"
                                        class="text-brand-gold font-bold text-sm uppercase tracking-wide hover:underline text-brand-dark">Read
                                        data <i class="fa-solid fa-arrow-right ml-1"></i></a>
                                </div>
                            <?php endwhile; else: ?>
                            <p class="text-slate-500 italic">No data found for this chapter.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="bg-brand-dark text-white py-12 border-t border-white/10 mt-12">
        <div class="max-w-7xl mx-auto px-4 text-center">
            <div class="flex justify-center gap-6 mb-6">
                <a href="#" class="text-slate-400 hover:text-white transition-colors"><i
                        class="fa-brands fa-twitter"></i></a>
                <a href="#" class="text-slate-400 hover:text-white transition-colors"><i
                        class="fa-brands fa-linkedin"></i></a>
                <a href="#" class="text-slate-400 hover:text-white transition-colors"><i
                        class="fa-brands fa-github"></i></a>
            </div>
            <p class="text-slate-400 text-sm">&copy; <?php echo date('Y'); ?> SaniBook Kenya Volume 01. All rights
                reserved.</p>
        </div>
    </footer>


    <script>
        function switchTab(tabId) {
            // Hide all tab contents
            document.querySelectorAll('.tab-content').forEach(el => {
                el.classList.add('hidden');
                el.classList.remove('block');
            });
            // Show selected tab
            document.getElementById('tab-' + tabId).classList.remove('hidden');
            document.getElementById('tab-' + tabId).classList.add('block');

            // Reset all buttons
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('border-brand-teal', 'text-brand-teal');
                btn.classList.add('border-transparent', 'text-slate-500');
            });

            // Highlight selected button
            const activeBtn = document.getElementById('btn-' + tabId);
            activeBtn.classList.remove('border-transparent', 'text-slate-500');
            activeBtn.classList.add('border-brand-teal', 'text-brand-teal');
        }
    </script>
</body>

</html>