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

// Auth check handled by auth_check.php

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

// Fetch full submission
$stmt = $conn->prepare("SELECT * FROM submissions WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$submission = $stmt->get_result()->fetch_assoc();

if (!$submission) {
    header("Location: user_dashboard.php");
    exit;
}

// Auth: must be admin OR the submission owner
$is_admin = (($_SESSION['user_role'] ?? '') === 'admin' && ($_SESSION['admin_logged_in'] ?? false) === true);
$is_owner = (isset($submission['user_id']) && intval($submission['user_id']) === intval($_SESSION['user_id']));

if (!$is_admin && !$is_owner) {
    header("Location: user_dashboard.php");
    exit;
}

// Determine edit URL and back link based on role
$edit_url = $is_admin
    ? "admin_submission_form.php?id={$id}"
    : "../submit-data.php?edit={$id}";
$back_url = $is_admin ? "admin_submissions.php" : "user_dashboard.php";
$back_label = $is_admin ? "Back to Submissions" : "Back to Dashboard";

// 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 user token balance
$user_tokens = 0;
if (!empty($submission['user_id'])) {
    $tok_stmt = $conn->prepare("SELECT tokens_remaining FROM user_subscriptions WHERE user_id = ? AND status = 'active' LIMIT 1");
    $tok_stmt->bind_param("i", $submission['user_id']);
    $tok_stmt->execute();
    $tok_stmt->bind_result($user_tokens);
    $tok_stmt->fetch();
    $tok_stmt->close();
}
$tokens_msg = number_format($user_tokens) . " Tokens";

// Status styling
$status = $submission['status'] ?? 'pending';
$status_config = match ($status) {
    'approved' => ['class' => 'bg-green-100 text-green-700 border-green-200', 'icon' => 'fa-check-circle', 'label' => 'Approved'],
    'rejected' => ['class' => 'bg-red-100 text-red-700 border-red-200', 'icon' => 'fa-times-circle', 'label' => 'Rejected'],
    default => ['class' => 'bg-amber-100 text-amber-700 border-amber-200', 'icon' => 'fa-clock', 'label' => 'Pending Review']
};
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Submission #
        <?php echo $id; ?> - SaniBook Admin
    </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">
    <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>
</head>

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

    <?php include 'navbar.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="<?php echo $back_url; ?>" class="text-slate-500 hover:text-blue-600 text-sm">
                    <i class="fa-solid fa-arrow-left mr-1"></i> <?php echo $back_label; ?>
                </a>
                <span class="px-3 py-1 rounded-full text-xs font-bold border <?php echo $status_config['class']; ?>">
                    <i class="fa-solid <?php echo $status_config['icon']; ?> mr-1"></i>
                    <?php echo $status_config['label']; ?>
                </span>
                <span
                    class="px-3 py-1 rounded-full text-xs font-bold border bg-blue-100 text-brand-blue border-blue-200">
                    <i class="fa-solid fa-coins mr-1"></i>
                    <?php echo $tokens_msg; ?>
                </span>
            </div>
            <a href="<?php echo $edit_url; ?>"
                class="px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-lg shadow-sm transition-all text-sm flex items-center gap-2">
                <i class="fa-solid fa-pen"></i> Edit Submission
            </a>
        </div>

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

            <!-- Title Banner -->
            <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">
                    <p class="text-slate-400 text-sm mb-1 uppercase tracking-wider font-bold">Submission #
                        <?php echo $id; ?>
                    </p>
                    <h1 class="text-2xl md:text-3xl font-display font-bold">
                        <?php echo htmlspecialchars(html_entity_decode($submission['title'] ?? $submission['org_name'], ENT_QUOTES | ENT_HTML5)); ?>
                    </h1>
                    <p class="text-slate-300 mt-2 text-sm">
                        by <strong class="text-white">
                            <?php echo htmlspecialchars(html_entity_decode($submission['org_name'], ENT_QUOTES | ENT_HTML5)); ?>
                        </strong>
                        &bull;
                        <?php echo date('F j, Y', strtotime($submission['created_at'])); ?>
                    </p>
                </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 -->
                <?php if (!empty($submission['description'])): ?>
                    <div class="bg-slate-50 rounded-xl p-5 border border-slate-200">
                        <h3 class="text-xs font-bold text-slate-400 uppercase tracking-wider mb-2">Brief Description</h3>
                        <p class="text-slate-700 leading-relaxed">
                            <?php echo htmlspecialchars(html_entity_decode($submission['description'], ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                    </div>
                <?php endif; ?>

                <!-- Data Content -->
                <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['Data'] ?? '<p class="text-slate-400 italic">No Data Content.</p>'); ?>
                    </div>
                </div>

                <?php if (!empty($media_uploads)):
                    $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 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">
                                        <?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 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 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 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 -->
                <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>

                <!-- Admin Notes -->
                <?php if (!empty($submission['admin_notes'])): ?>
                    <div class="bg-amber-50 rounded-xl p-5 border border-amber-200">
                        <h3 class="text-xs font-bold text-amber-700 uppercase tracking-wider mb-2">
                            <i class="fa-solid fa-sticky-note mr-1"></i>Admin Notes
                        </h3>
                        <p class="text-amber-900 text-sm leading-relaxed">
                            <?php echo htmlspecialchars(html_entity_decode($submission['admin_notes'], ENT_QUOTES | ENT_HTML5)); ?>
                        </p>
                    </div>
                <?php endif; ?>

            </div>
        </div>

        <!-- Bottom Action Bar -->
        <div class="flex justify-between items-center mt-6">
            <a href="<?php echo $back_url; ?>" class="text-slate-500 hover:text-slate-700 text-sm">
                <i class="fa-solid fa-arrow-left mr-1"></i> <?php echo $back_label; ?>
            </a>
            <a href="<?php echo $edit_url; ?>"
                class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-lg shadow-lg transition-all text-sm">
                <i class="fa-solid fa-pen mr-2"></i> Edit This Submission
            </a>
        </div>
    </div>

</body>

</html>
