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

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id <= 0) {
    header("Location: submitted.php");
    exit;
}

// Check if user is logged in
$curr_user_id = $_SESSION['user_id'] ?? 0;
$is_logged_in = $curr_user_id > 0;
$start_session = session_status() === PHP_SESSION_NONE;
if ($start_session)
    session_start();
$role = $_SESSION['role'] ?? 'user';

// Fetch verification status and user_id first to check permissions
$stmt = $conn->prepare("SELECT user_id, is_verified FROM submissions WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$check = $stmt->get_result()->fetch_assoc();

if (!$check) {
    header("Location: submitted.php");
    exit;
}

// Allow view if: Verified OR Owner OR Admin
if ($check['is_verified'] == 1 || $check['user_id'] == $curr_user_id || $role === 'admin') {
    // Increment view count for non-owner views (Removed session limitation as requested)
    if ($check['user_id'] != $curr_user_id) {
        $inc_stmt = $conn->prepare("UPDATE submissions SET view_count = IFNULL(view_count, 0) + 1 WHERE id = ?");
        $inc_stmt->bind_param("i", $id);
        $inc_stmt->execute();
        $inc_stmt->close();
    }

    $stmt = $conn->prepare("SELECT * FROM submissions WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $submission = $stmt->get_result()->fetch_assoc();
} else {
    // Redirect if not authorized
    header("Location: submitted.php");
    exit;
}

// Decode JSON fields
$service_chains = json_decode($submission['service_chains'] ?? '[]', true) ?: [];
$enabling_pillars = json_decode($submission['enabling_pillars'] ?? '[]', true) ?: [];
$thematic_categories = json_decode($submission['thematic_categories'] ?? '[]', true) ?: [];

// Fetch thematic category names
$thematic_names = [];
if (!empty($thematic_categories)) {
    $placeholders = implode(',', array_fill(0, count($thematic_categories), '?'));
    $types = str_repeat('i', count($thematic_categories));
    $cat_stmt = $conn->prepare("SELECT id, title FROM categories WHERE id IN ($placeholders)");
    $cat_stmt->bind_param($types, ...$thematic_categories);
    $cat_stmt->execute();
    $cat_result = $cat_stmt->get_result();
    while ($row = $cat_result->fetch_assoc()) {
        $thematic_names[$row['id']] = $row['title'];
    }
}

// Fetch Media Uploads
$media_uploads = [];
$m_stmt = $conn->prepare("SELECT id, title, file_path, media_type, file_size, mime_type, caption, original_filename FROM media_uploads WHERE submission_id = ?");
$m_stmt->bind_param("i", $id);
$m_stmt->execute();
$m_result = $m_stmt->get_result();
while ($row = $m_result->fetch_assoc()) {
    $media_uploads[] = $row;
}

// Fetch rating data
$rating_data = get_item_rating($conn, 'submission', $id);
$r_avg = $rating_data['avg'];
$r_cnt = $rating_data['count'];
$user_rating = $is_logged_in ? get_user_rating($conn, $curr_user_id, 'submission', $id) : 0;
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo htmlspecialchars(html_entity_decode($submission['title'], ENT_QUOTES | ENT_HTML5)); ?> | SaniBook
        Kenya
    </title>
    <script src="https://cdn.tailwindcss.com?plugins=typography"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <link rel="icon" href="images/saniBook logo.png" type="image/png">
    <style>
        .star-rating-widget {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .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;
        }

        /* Larger version for the bottom widget */
        .rating-section .star-rating-stars .star {
            font-size: 28px;
        }

        .rating-section .star-rating-info {
            font-size: 14px;
        }

        /* Hero version */
        .hero-rating .star-rating-stars .star {
            font-size: 16px;
            color: rgba(255, 255, 255, 0.3);
        }

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

        .hero-rating .star-rating-info {
            color: rgba(255, 255, 255, 0.6);
            font-size: 13px;
        }
    </style>
    <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>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Space+Grotesk:wght@500;700&display=swap"
        rel="stylesheet">
</head>

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

    <?php include 'navbar.php'; ?>
    <?php
    $breadcrumbs = [
        ['label' => 'Home', 'url' => '/'],
        ['label' => 'Submitted Works', 'url' => '/submitted.php'],
        ['label' => htmlspecialchars(html_entity_decode($submission['title'] ?? 'Submission', ENT_QUOTES | ENT_HTML5))]
    ];
    include 'breadcrumbs.php';
    ?>

    <div class="max-w-4xl mx-auto p-6">

        <!-- Header Bar -->
        <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-4">
                <a href="submitted.php" class="text-slate-500 hover:text-blue-600 text-sm">
                    <i class="fa-solid fa-arrow-left mr-1"></i> Back to Submitted Works
                </a>
            </div>
            <?php if ($role === 'admin'): ?>
                <div class="flex items-center gap-2">
                    <a href="/admin/submission-form.php?id=<?= $id ?>"
                        class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-bold rounded-lg transition-colors shadow-sm">
                        <i class="fa-solid fa-pen-to-square"></i> Edit Submission
                    </a>
                </div>
            <?php elseif (isset($curr_user_id) && $check['user_id'] == $curr_user_id): ?>
                <div class="flex items-center gap-2">
                    <a href="/submit-data.php?edit=<?= $id ?>"
                        class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-bold rounded-lg transition-colors shadow-sm">
                        <i class="fa-solid fa-pen-to-square"></i> Edit Submission
                    </a>
                </div>
            <?php endif; ?>
        </div>

        <!-- Main Content Card -->
        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">

            <div class="bg-gradient-to-r from-brand-dark to-slate-800 p-8 text-white relative overflow-hidden">
                <div class="absolute top-0 right-0 p-6 opacity-5">
                    <i class="fa-solid fa-file-lines text-[120px]"></i>
                </div>
                <div class="relative z-10">
                    <div class="flex justify-between items-start mb-2">
                        <p class="text-slate-400 text-sm uppercase tracking-wider font-bold mt-1">
                            Submission Details
                        </p>
                        <!-- Top Right: Sub-Categories -->
                        <div class="flex flex-wrap gap-2 justify-end max-w-[60%]">
                            <?php
                            // Pillar Slug Map
                            $pillar_slugs = [
                                'Financing' => 'financing',
                                'Governance' => 'governance',
                                'Research & Learning' => 'research',
                                'Collaboration' => 'collaboration',
                                'Menstrual Health Management' => 'mhm',
                                'Capacity Building' => 'capacity-building'
                            ];

                            // 1. Service Chains
                            if (!empty($service_chains)) {
                                foreach ($service_chains as $chain) {
                                    echo "<a href='service-chain.php' class='px-2 py-1 bg-blue-500/20 text-blue-100 border border-blue-400/30 rounded text-[10px] font-bold hover:bg-blue-500/40 transition-colors uppercase tracking-wider'>" . htmlspecialchars(html_entity_decode($chain)) . "</a>";
                                }
                            }
                            // 2. Pillars
                            if (!empty($enabling_pillars)) {
                                foreach ($enabling_pillars as $pillar) {
                                    $slug = $pillar_slugs[$pillar] ?? 'financing';
                                    echo "<a href='enabling-pillars.php?pillar=$slug' class='px-2 py-1 bg-orange-500/20 text-orange-100 border border-orange-400/30 rounded text-[10px] font-bold hover:bg-orange-500/40 transition-colors uppercase tracking-wider'>" . htmlspecialchars(html_entity_decode($pillar)) . "</a>";
                                }
                            }
                            // 3. Thematic
                            if (!empty($thematic_names)) {
                                foreach ($thematic_names as $tid => $tname) {
                                    echo "<a href='thematic-repositories.php?id=$tid' class='px-2 py-1 bg-teal-500/20 text-teal-100 border border-teal-400/30 rounded text-[10px] font-bold hover:bg-teal-500/40 transition-colors uppercase tracking-wider'>" . htmlspecialchars(html_entity_decode($tname)) . "</a>";
                                }
                            }
                            ?>
                        </div>
                    </div>

                    <h1 class="text-2xl md:text-3xl font-display font-bold mb-3">
                        <?php echo htmlspecialchars(html_entity_decode($submission['title'] ?? $submission['org_name'], ENT_QUOTES | ENT_HTML5)); ?>
                    </h1>

                    <!-- Average Rating in Hero -->
                    <div class="hero-rating mb-2">
                        <div class="star-rating-widget">
                            <div class="star-rating-stars">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <span class="star <?php echo $i <= round($r_avg) ? 'filled' : ''; ?>">
                                        <i class="<?php echo $i <= round($r_avg) ? 'fas' : 'far'; ?> fa-star"></i>
                                    </span>
                                <?php endfor; ?>
                            </div>
                            <span class="star-rating-info">
                                <?php echo $r_avg; ?> (<?php echo $r_cnt; ?>
                                rating<?php echo $r_cnt !== 1 ? 's' : ''; ?>)
                            </span>
                        </div>
                    </div>

                    <!-- Role above date -->
                    <?php if (!empty($submission['role'])): ?>
                        <div class="mb-3">
                            <span
                                class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded bg-slate-700/50 text-slate-300 text-xs font-bold uppercase tracking-wider border border-slate-600">
                                <i class="fa-solid fa-tag text-[10px]"></i>
                                <?php echo htmlspecialchars(html_entity_decode($submission['role'])); ?>
                            </span>
                        </div>
                    <?php endif; ?>

                    <p class="text-slate-300 mt-2 text-sm">
                        by <a href="profile.php?user_id=<?= $submission['user_id'] ?>"
                            class="text-white hover:text-blue-200 transition-colors hover:underline">
                            <strong>
                                <?php echo htmlspecialchars(html_entity_decode($submission['org_name'], ENT_QUOTES | ENT_HTML5)); ?>
                            </strong>
                        </a>
                        &bull;
                        <?php echo date('F j, Y', strtotime($submission['created_at'])); ?>
                        &bull;
                        <i class="fa-solid fa-eye text-slate-400"></i>
                        <?php echo number_format($submission['view_count'] ?? 0); ?> views
                    </p>

                    <!-- Verified Badge (Bottom Right) -->
                    <div class="absolute bottom-6 right-6 hidden md:block">
                        <span
                            class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-teal-500/20 text-teal-100 text-xs font-bold uppercase tracking-wider border border-teal-400/30 backdrop-blur-sm shadow-lg">
                            <i class="fa-solid fa-check-circle"></i> Verified Submission
                        </span>
                    </div>
                </div>
            </div>

            <div class="p-8 space-y-8">

                <!-- Category Badges -->
                <div class="space-y-3">
                    <?php if (!empty($service_chains)): ?>
                        <div class="flex flex-wrap items-center gap-2">
                            <span class="text-xs font-bold text-slate-400 uppercase tracking-wider w-full mb-1">Service
                                Chains</span>
                            <?php foreach ($service_chains as $chain): ?>
                                <span
                                    class="px-3 py-1 bg-blue-50 text-blue-700 border border-blue-200 text-xs font-bold rounded-full">
                                    <i class="fa-solid fa-link mr-1"></i>
                                    <?php echo htmlspecialchars(html_entity_decode($chain, ENT_QUOTES | ENT_HTML5)); ?>
                                </span>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($enabling_pillars)): ?>
                        <div class="flex flex-wrap items-center gap-2">
                            <span class="text-xs font-bold text-slate-400 uppercase tracking-wider w-full mb-1">Enabling
                                Pillars</span>
                            <?php foreach ($enabling_pillars as $pillar): ?>
                                <span
                                    class="px-3 py-1 bg-orange-50 text-orange-700 border border-orange-200 text-xs font-bold rounded-full">
                                    <i class="fa-solid fa-chart-pie mr-1"></i>
                                    <?php echo htmlspecialchars(html_entity_decode($pillar, ENT_QUOTES | ENT_HTML5)); ?>
                                </span>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($thematic_names)): ?>
                        <div class="flex flex-wrap items-center gap-2">
                            <span class="text-xs font-bold text-slate-400 uppercase tracking-wider w-full mb-1">Thematic
                                Repositories</span>
                            <?php foreach ($thematic_names as $t_id => $t_name): ?>
                                <span
                                    class="px-3 py-1 bg-teal-50 text-teal-700 border border-teal-200 text-xs font-bold rounded-full">
                                    <i class="fa-solid fa-book mr-1"></i>
                                    <?php echo htmlspecialchars(html_entity_decode($t_name, ENT_QUOTES | ENT_HTML5)); ?>
                                </span>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Brief Description (Preserved Custom Public Style) -->
                <?php if (!empty($submission['description'])): ?>
                    <div
                        class="bg-slate-50 rounded-xl p-6 border-l-4 border-brand-gold italic text-slate-700 leading-relaxed shadow-sm">
                        <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-2 not-italic">Brief Summary
                        </h3>
                        <?php echo htmlspecialchars(html_entity_decode($submission['description'], ENT_QUOTES | ENT_HTML5)); ?>
                    </div>
                <?php endif; ?>

                <!-- Data Content (Admin Style Container) -->
                <div>
                    <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-3">Full Data</h3>
                    <div class="prose prose-slate max-w-none leading-relaxed">
                        <?php echo html_entity_decode($submission['story'] ?? '<p class="text-slate-400 italic">No Data Content available.</p>'); ?>
                    </div>
                </div>

                <?php if (!empty($media_uploads)):
                    // Group media by type for display
                    $images = array_filter($media_uploads, fn($f) => $f['media_type'] === 'image');
                    $videos = array_filter($media_uploads, fn($f) => $f['media_type'] === 'video');
                    $audios = array_filter($media_uploads, fn($f) => $f['media_type'] === 'audio');
                    $pdfs = array_filter($media_uploads, fn($f) => $f['media_type'] === 'pdf');
                    ?>
                    <div class="space-y-6">
                        <div class="flex items-center justify-between">
                            <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider">Media Contents</h3>
                            <div class="flex gap-2">
                                <?php if (!empty($images)): ?><span
                                        class="inline-flex items-center gap-1 px-2 py-1 bg-green-50 text-green-700 text-[10px] font-bold rounded-full border border-green-200"><i
                                            class="fa-solid fa-image"></i> <?php echo count($images); ?>
                                        Image<?php echo count($images) > 1 ? 's' : ''; ?></span><?php endif; ?>
                                <?php if (!empty($videos)): ?><span
                                        class="inline-flex items-center gap-1 px-2 py-1 bg-red-50 text-red-700 text-[10px] font-bold rounded-full border border-red-200"><i
                                            class="fa-solid fa-video"></i> <?php echo count($videos); ?>
                                        Video<?php echo count($videos) > 1 ? 's' : ''; ?></span><?php endif; ?>
                                <?php if (!empty($audios)): ?><span
                                        class="inline-flex items-center gap-1 px-2 py-1 bg-yellow-50 text-yellow-700 text-[10px] font-bold rounded-full border border-yellow-200"><i
                                            class="fa-solid fa-microphone"></i> <?php echo count($audios); ?>
                                        Audio</span><?php endif; ?>
                                <?php if (!empty($pdfs)): ?><span
                                        class="inline-flex items-center gap-1 px-2 py-1 bg-blue-50 text-blue-700 text-[10px] font-bold rounded-full border border-blue-200"><i
                                            class="fa-solid fa-file-pdf"></i> <?php echo count($pdfs); ?>
                                        PDF<?php echo count($pdfs) > 1 ? 's' : ''; ?></span><?php endif; ?>
                            </div>
                        </div>

                        <?php /* === IMAGE GALLERY === */ ?>
                        <?php if (!empty($images)): ?>
                            <div class="grid gap-4 <?php echo count($images) === 1 ? '' : 'md:grid-cols-2'; ?>">
                                <?php foreach ($images as $img): ?>
                                    <figure class="relative group rounded-xl overflow-hidden border border-slate-200 shadow-sm">
                                        <img src="serve_file.php?id=<?php echo $img['id']; ?>"
                                            alt="<?php echo htmlspecialchars($img['caption'] ?? $img['original_filename'] ?? 'Image'); ?>"
                                            class="w-full h-auto object-cover" loading="lazy" oncontextmenu="return false;">
                                        <?php if (!empty($img['caption'])): ?>
                                            <figcaption
                                                class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4 pt-8">
                                                <p class="text-white text-sm font-medium">
                                                    <?php echo htmlspecialchars($img['caption']); ?>
                                                </p>
                                            </figcaption>
                                        <?php endif; ?>
                                    </figure>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <?php /* === PDF VIEWERS === */ ?>
                        <?php foreach ($pdfs as $pdf): ?>
                            <div class="border border-slate-200 rounded-xl overflow-hidden">
                                <div class="flex items-center justify-between bg-slate-50 px-4 py-3 border-b border-slate-200">
                                    <div class="flex items-center gap-3">
                                        <div class="bg-red-100 text-red-600 p-2 rounded-lg"><i
                                                class="fa-solid fa-file-pdf text-lg"></i></div>
                                        <div>
                                            <h4 class="text-sm font-bold text-slate-800">
                                                <?php echo htmlspecialchars($pdf['original_filename'] ?? $pdf['title'] ?? 'Document'); ?>
                                            </h4>
                                            <p class="text-[10px] text-slate-400 uppercase">
                                                <?php echo $pdf['file_size'] ? round($pdf['file_size'] / 1024 / 1024, 2) . ' MB' : 'PDF Document'; ?>
                                            </p>
                                        </div>
                                    </div>
                                    <a href="serve_file.php?id=<?php echo $pdf['id']; ?>&download=1"
                                        class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-xs font-bold rounded-lg hover:bg-blue-700 transition-colors shadow-sm"><i
                                            class="fa-solid fa-download"></i> Download</a>
                                </div>
                                <iframe src="serve_file.php?id=<?php echo $pdf['id']; ?>" class="w-full border-0"
                                    style="height: 600px;" title="PDF Viewer"></iframe>
                            </div>
                        <?php endforeach; ?>

                        <?php /* === VIDEO PLAYERS === */ ?>
                        <?php foreach ($videos as $vid): ?>
                            <div class="border border-slate-200 rounded-xl overflow-hidden">
                                <div class="flex items-center gap-3 bg-slate-50 px-4 py-3 border-b border-slate-200">
                                    <div class="bg-red-100 text-red-600 p-2 rounded-lg"><i
                                            class="fa-solid fa-video text-lg"></i></div>
                                    <h4 class="text-sm font-bold text-slate-800">
                                        <?php echo htmlspecialchars($vid['original_filename'] ?? $vid['title'] ?? 'Video'); ?>
                                    </h4>
                                </div>
                                <video controls controlsList="nodownload" disablePictureInPicture oncontextmenu="return false;"
                                    class="w-full bg-black" preload="metadata">
                                    <source src="serve_file.php?id=<?php echo $vid['id']; ?>"
                                        type="<?php echo htmlspecialchars($vid['mime_type'] ?? 'video/mp4'); ?>">
                                    Your browser does not support the video tag.
                                </video>
                            </div>
                        <?php endforeach; ?>

                        <?php /* === AUDIO PLAYERS === */ ?>
                        <?php foreach ($audios as $aud): ?>
                            <div class="flex items-center gap-4 bg-slate-50 border border-slate-200 rounded-xl p-4">
                                <div class="bg-yellow-100 text-yellow-700 p-3 rounded-lg"><i
                                        class="fa-solid fa-microphone text-lg"></i></div>
                                <div class="flex-1 min-w-0">
                                    <h4 class="text-sm font-bold text-slate-800 truncate">
                                        <?php echo htmlspecialchars($aud['original_filename'] ?? $aud['title'] ?? 'Audio'); ?>
                                    </h4>
                                    <?php if (!empty($aud['caption'])): ?>
                                        <p class="text-xs text-slate-500 mt-0.5"><?php echo htmlspecialchars($aud['caption']); ?>
                                        </p><?php endif; ?>
                                    <audio controls controlsList="nodownload" oncontextmenu="return false;" class="w-full mt-2"
                                        preload="metadata">
                                        <source src="serve_file.php?id=<?php echo $aud['id']; ?>"
                                            type="<?php echo htmlspecialchars($aud['mime_type'] ?? 'audio/mpeg'); ?>">
                                        Your browser does not support the audio tag.
                                    </audio>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <hr class="border-slate-200">

                <!-- Meta Info Grid (Admin Style) -->
                <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div class="bg-slate-50 rounded-lg p-4 border border-slate-100">
                        <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Organization</p>
                        <p class="font-semibold text-slate-800">
                            <?php echo htmlspecialchars(html_entity_decode($submission['org_name'], ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                    </div>
                    <div class="bg-slate-50 rounded-lg p-4 border border-slate-100">
                        <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Contact Person</p>
                        <p class="font-semibold text-slate-800">
                            <?php echo htmlspecialchars(html_entity_decode($submission['contact_person'] ?? 'N/A', ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                        <?php if (!empty($submission['contact_role'])): ?>
                            <p class="text-xs text-slate-500">
                                <?php echo htmlspecialchars(html_entity_decode($submission['contact_role'], ENT_QUOTES | ENT_HTML5)); ?>
                            </p>
                        <?php endif; ?>
                    </div>
                    <div class="bg-slate-50 rounded-lg p-4 border border-slate-100">
                        <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Email</p>
                        <p class="font-semibold text-slate-800">
                            <?php echo htmlspecialchars(html_entity_decode($submission['email'], ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                    </div>
                    <div class="bg-slate-50 rounded-lg p-4 border border-slate-100">
                        <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Mobile</p>
                        <p class="font-semibold text-slate-800">
                            <?php echo htmlspecialchars(html_entity_decode($submission['mobile'] ?? 'N/A', ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                    </div>
                    <div class="bg-slate-50 rounded-lg p-4 border border-slate-100">
                        <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Role / Category
                        </p>
                        <p class="font-semibold text-slate-800">
                            <?php echo htmlspecialchars(html_entity_decode($submission['role'] ?? 'N/A', ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                    </div>
                    <div class="bg-slate-50 rounded-lg p-4 border border-slate-100">
                        <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Location</p>
                        <p class="font-semibold text-slate-800">
                            <?php echo htmlspecialchars(html_entity_decode($submission['county'] ?? 'N/A', ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                    </div>
                </div>

            </div>

            <!-- Rating Section at bottom (logged-in users only) -->
            <?php if ($is_logged_in): ?>
                <div class="rating-section border-t border-slate-200 p-8 bg-gradient-to-b from-slate-50 to-white">
                    <div class="text-center">
                        <h3 class="text-lg font-bold text-slate-800 mb-1">
                            <i class="fa-solid fa-star text-amber-400 mr-2"></i>Rate this Submission
                        </h3>
                        <p class="text-sm text-slate-500 mb-4">How would you rate the quality and usefulness of this data?
                        </p>
                        <div class="flex justify-center">
                            <?php echo render_stars($r_avg, $r_cnt, 'submission', $id, $user_rating, true); ?>
                        </div>
                        <?php if ($user_rating > 0): ?>
                            <p class="text-xs text-slate-400 mt-2">You rated this <?php echo $user_rating; ?>
                                star<?php echo $user_rating > 1 ? 's' : ''; ?>. Click to update.</p>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

        </div>
    </div>

    <!-- Comments Section -->
    <div class="max-w-4xl mx-auto p-6 mt-0">
        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
            <div class="p-6 border-b border-slate-100">
                <h3 class="text-lg font-bold text-slate-800 flex items-center gap-2">
                    <i class="fa-solid fa-comments text-blue-500"></i> Comments
                    <?php
                    $count_stmt = $conn->prepare("SELECT COUNT(*) as cnt FROM submission_comments WHERE submission_id = ?");
                    $count_stmt->bind_param("i", $id);
                    $count_stmt->execute();
                    $comment_count = $count_stmt->get_result()->fetch_assoc()['cnt'] ?? 0;
                    $count_stmt->close();
                    ?>
                    <span class="text-sm font-normal text-slate-400">(<?= $comment_count ?>)</span>
                </h3>
            </div>

            <!-- Existing Comments -->
            <div id="comments-list" class="divide-y divide-slate-100">
                <?php
                $comments_stmt = $conn->prepare("SELECT c.id, c.comment_text, c.created_at, u.organization_name, u.email
                                                  FROM submission_comments c
                                                  JOIN users u ON c.user_id = u.id
                                                  WHERE c.submission_id = ?
                                                  ORDER BY c.created_at ASC");
                $comments_stmt->bind_param("i", $id);
                $comments_stmt->execute();
                $comments_result = $comments_stmt->get_result();

                if ($comments_result->num_rows === 0): ?>
                    <div id="no-comments-msg" class="p-8 text-center text-slate-400">
                        <i class="fa-regular fa-comment-dots text-3xl mb-2 opacity-50 block"></i>
                        <p class="text-sm">No comments yet. Be the first to share your thoughts.</p>
                    </div>
                <?php else: ?>
                    <?php while ($c = $comments_result->fetch_assoc()):
                        $c_author = !empty($c['organization_name']) ? htmlspecialchars($c['organization_name']) : htmlspecialchars(explode('@', $c['email'])[0]);
                    ?>
                        <div class="p-5 hover:bg-slate-50/50 transition-colors">
                            <div class="flex items-start gap-3">
                                <div class="w-9 h-9 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                                    <i class="fa-solid fa-user text-blue-500 text-xs"></i>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1">
                                        <span class="font-semibold text-sm text-slate-800"><?= $c_author ?></span>
                                        <span class="text-xs text-slate-400"><?= date('M j, Y g:i A', strtotime($c['created_at'])) ?></span>
                                    </div>
                                    <p class="text-sm text-slate-600 leading-relaxed"><?= nl2br($c['comment_text']) ?></p>
                                </div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php endif;
                $comments_stmt->close();
                ?>
            </div>

            <!-- Post Comment Form (logged-in only) -->
            <?php if ($is_logged_in): ?>
                <?php if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); ?>
                <div class="p-5 bg-slate-50 border-t border-slate-100">
                    <form id="comment-form" class="flex gap-3">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                        <input type="hidden" name="submission_id" value="<?= $id ?>">
                        <div class="flex-1">
                            <textarea name="comment_text" rows="2" required
                                placeholder="Share your thoughts on this submission..."
                                class="w-full px-4 py-2.5 text-sm border border-slate-200 rounded-lg focus:border-blue-400 focus:ring-1 focus:ring-blue-400 outline-none transition-colors resize-none"></textarea>
                        </div>
                        <button type="submit"
                            class="self-end px-5 py-2.5 bg-blue-600 text-white text-sm font-bold rounded-lg hover:bg-blue-700 transition-colors whitespace-nowrap">
                            <i class="fa-solid fa-paper-plane mr-1"></i> Post
                        </button>
                    </form>
                </div>
            <?php else: ?>
                <div class="p-5 bg-slate-50 border-t border-slate-100 text-center">
                    <p class="text-sm text-slate-500"><a href="/signup.php" class="text-blue-600 font-semibold hover:underline">Log in</a> to leave a comment.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Comment AJAX Script -->
    <script>
    (function() {
        const form = document.getElementById('comment-form');
        if (!form) return;
        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            const btn = form.querySelector('button[type="submit"]');
            const orig = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i>';

            try {
                const fd = new FormData(form);
                const res = await fetch('/api/post-comment.php', { method: 'POST', body: fd });
                const data = await res.json();
                if (data.ok) {
                    // Remove "no comments" message
                    const noMsg = document.getElementById('no-comments-msg');
                    if (noMsg) noMsg.remove();

                    // Append new comment
                    const list = document.getElementById('comments-list');
                    const div = document.createElement('div');
                    div.className = 'p-5 hover:bg-slate-50/50 transition-colors';
                    div.innerHTML = `
                        <div class="flex items-start gap-3">
                            <div class="w-9 h-9 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                                <i class="fa-solid fa-user text-blue-500 text-xs"></i>
                            </div>
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-2 mb-1">
                                    <span class="font-semibold text-sm text-slate-800">${data.comment.author}</span>
                                    <span class="text-xs text-slate-400">${data.comment.created_at}</span>
                                </div>
                                <p class="text-sm text-slate-600 leading-relaxed">${data.comment.text.replace(/\n/g, '<br>')}</p>
                            </div>
                        </div>`;
                    list.appendChild(div);
                    form.querySelector('textarea').value = '';
                } else {
                    alert(data.error || 'Failed to post comment.');
                }
            } catch(err) {
                alert('Error posting comment.');
            } finally {
                btn.disabled = false;
                btn.innerHTML = orig;
            }
        });
    })();
    </script>

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

    <!-- Star Rating JS -->
    <script>
        document.querySelectorAll('.star-rating-widget .star.clickable').forEach(star => {
            star.addEventListener('click', function () {
                const widget = this.closest('.star-rating-widget');
                const itemType = widget.dataset.itemType;
                const itemId = widget.dataset.itemId;
                const rating = this.dataset.value;

</div >

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

                    < !--Star Rating JS-- >
                        <script>
    document.querySelectorAll('.star-rating-widget .star.clickable').forEach(star => {
                                star.addEventListener('click', function () {
                                    const widget = this.closest('.star-rating-widget');
                                    const itemType = widget.dataset.itemType;
                                    const itemId = widget.dataset.itemId;
                                    const rating = this.dataset.value;

                                    fetch('rate_item.php', {
                                        method: 'POST',
                                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                                        body: `item_type=${encodeURIComponent(itemType)}&item_id=${encodeURIComponent(itemId)}&rating=${encodeURIComponent(rating)}`
                                    })
                                        .then(r => {
                                            if (!r.ok) throw new Error('Server returned ' + r.status);
                                            return r.json();
                                        })
                                        .then(data => {
                                            if (data.success) {
                                                // Update ALL star widgets on the page (hero + bottom)
                                                document.querySelectorAll('.star-rating-widget').forEach(w => {
                                                    const stars = w.querySelectorAll('.star');
                                                    const info = w.querySelector('.star-rating-info');
                                                    stars.forEach(s => {
                                                        const v = parseInt(s.dataset.value);
                                                        if (isNaN(v)) return; // skip hero stars without data-value
                                                        const icon = s.querySelector('i');
                                                        if (s.classList.contains('clickable')) {
                                                            s.classList.toggle('user-rated', v <= data.user_rating);
                                                        }
                                                        s.classList.toggle('filled', v <= Math.round(data.avg_rating));
                                                        icon.className = (s.classList.contains('clickable') && v <= data.user_rating)
                                                            ? 'fas fa-star'
                                                            : (v <= Math.round(data.avg_rating) ? 'fas fa-star' : 'far fa-star');
                                                    });
                                                    if (info) {
                                                        info.textContent = data.avg_rating + ' (' + data.total_ratings + ' rating' + (data.total_ratings !== 1 ? 's' : '') + ')';
                                                    }
                                                });
                                            } else {
                                                alert(data.message || 'Rating failed.');
                                            }
                                        })
                                        .catch(err => { alert('Rating error: ' + err.message); });
                                });
    });
    </script>

</body>

</html>