<?php
// hub/notes.php

// --- ENABLE CONTENT SECURITY POLICY FOR TAILWIND ---
$enable_tailwind = true;

// --- SEO META TAGS FOR THIS PAGE ---
$page_title = 'Browse Notes';
$page_meta_description = 'Find, search, and download a vast collection of kmtc notes, past papers, and study materials shared by students and faculty.';

require_once __DIR__ . '/../partials/header.php';
require_once __DIR__ . '/../core/db_connect.php';
require_once __DIR__ . '/../core/functions.php';
require_once __DIR__ . '/../core/gemini_helper.php';

// --- PHP LOGIC FOR INITIAL LOAD ---
$search_term = $_GET['search'] ?? '';
$sort_order  = $_GET['sort'] ?? 'newest';
$page        = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit       = 12;
$offset      = ($page - 1) * $limit;

// BASE QUERY
$sql = "SELECT
            doc.*,
            s.name  AS school_name,
            dept.name AS department_name,
            c.name  AS course_name
        FROM documents AS doc
        LEFT JOIN schools      AS s    ON doc.school_id     = s.id
        LEFT JOIN departments  AS dept ON doc.department_id = dept.id
        LEFT JOIN courses      AS c    ON doc.course_id     = c.id
        WHERE doc.status = 'approved'";

$count_sql = "SELECT COUNT(*) FROM documents AS doc WHERE doc.status = 'approved'";

$params       = [];
$types        = '';
$count_params = [];
$count_types  = '';

if (!empty($search_term)) {
    $similar_document_ids = find_similar_documents($search_term, $conn);
    if (!empty($similar_document_ids)) {
        $id_placeholders = implode(',', array_fill(0, count($similar_document_ids), '?'));
        $sql       .= " AND doc.id IN (" . $id_placeholders . ")";
        $count_sql .= " AND doc.id IN (" . $id_placeholders . ")";

        $params       = array_merge($params, $similar_document_ids);
        $types       .= str_repeat('i', count($similar_document_ids));
        $count_params = array_merge($count_params, $similar_document_ids);
        $count_types .= str_repeat('i', count($similar_document_ids));

        $sql .= " ORDER BY FIELD(doc.id, " . $id_placeholders . ")";
        $params = array_merge($params, $similar_document_ids);
        $types .= str_repeat('i', count($similar_document_ids));
    } else {
        $sql       .= " AND 1=0";
        $count_sql .= " AND 1=0";
    }
} else {
    switch ($sort_order) {
        case 'oldest':
            $sql .= " ORDER BY doc.uploaded_at ASC";
            break;
        case 'downloads':
            $sql .= " ORDER BY doc.download_count DESC, doc.uploaded_at DESC";
            break;
        case 'newest':
        default:
            $sql .= " ORDER BY doc.uploaded_at DESC";
            break;
    }
}

$sql .= " LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$types   .= 'ii';

// Fetch documents
$stmt = $conn->prepare($sql);
if ($stmt && !empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$documents = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Total count for pagination
$count_stmt = $conn->prepare($count_sql);
if (!empty($count_types)) {
    $count_stmt->bind_param($count_types, ...$count_params);
}
$count_stmt->execute();
$total_docs  = $count_stmt->get_result()->fetch_row()[0];
$total_pages = ceil($total_docs / $limit);
$count_stmt->close();

$conn->close();

// Helper to build query string for pagination links
function paginate_url(int $p, string $search, string $sort): string
{
    $qs = http_build_query(array_filter([
        'search' => $search,
        'sort'   => ($sort !== 'newest') ? $sort : '',
        'page'   => $p > 1 ? $p : null,
    ]));
    return '/notes/' . ($qs ? '?' . $qs : '');
}
?>

<div class="min-h-screen bg-gray-50 dark:bg-gray-900 pb-5 font-sans transition-colors duration-300">

    <!-- Hero Section -->
    <div class="relative bg-gradient-to-br from-indigo-50/50 via-white to-sky-50/50 dark:from-slate-900 dark:via-slate-900 dark:to-slate-800 border-b border-indigo-100 dark:border-slate-800">
        <div class="absolute inset-0 overflow-hidden pointer-events-none">
            <div class="absolute top-0 right-0 -mr-20 -mt-20 w-96 h-96 bg-indigo-500/5 rounded-full blur-3xl"></div>
            <div class="absolute bottom-0 left-0 -ml-20 -mb-20 w-80 h-80 bg-sky-500/5 rounded-full blur-3xl"></div>
        </div>

        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 md:py-16 relative z-10 flex flex-col items-center">
            <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 text-xs font-semibold uppercase tracking-wider mb-6">
                <span class="w-2 h-2 rounded-full bg-indigo-500 animate-pulse"></span>
                StudoKe Library
            </div>
            <h1 class="text-4xl md:text-5xl lg:text-6xl font-extrabold text-slate-900 dark:text-white tracking-tight leading-tight mb-6 text-center">
                Browse <span class="text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-sky-600">Notes & Papers</span>
            </h1>
            <p class="text-lg md:text-xl text-slate-600 dark:text-slate-400 max-w-2xl mx-auto leading-relaxed mb-10">
                Find resources shared by the community.
            </p>
        </div>
    </div>

    <!-- Main Content -->
    <div class="px-2 sm:px-4 lg:px-6 py-12">

        <!-- Flash Messages -->
        <?php if (isset($_SESSION['flash_message'])): ?>
            <div class="mb-6 px-4 py-3 rounded-lg text-sm font-medium <?= $_SESSION['flash_message']['type'] === 'success' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400' : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400' ?>">
                <?= htmlspecialchars($_SESSION['flash_message']['text']) ?>
            </div>
            <?php unset($_SESSION['flash_message']); ?>
        <?php endif; ?>

        <!-- Sort Controls -->
        <div class="flex items-center justify-between mb-8 flex-wrap gap-4">
            <h2 class="text-xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
                <span class="material-symbols-outlined text-indigo-500">list_alt</span>
                <?php if ($search_term): ?>
                    Search Results: "<?= htmlspecialchars($search_term) ?>"
                <?php else: ?>
                    All Notes
                <?php endif; ?>
            </h2>
            <div class="flex items-center gap-3">
                <?php if (!$search_term): ?>
                    <form action="/notes/" method="GET" id="sort-form">
                        <?php if ($search_term): ?>
                            <input type="hidden" name="search" value="<?= htmlspecialchars($search_term) ?>">
                        <?php endif; ?>
                        <select name="sort" onchange="this.form.submit()"
                            class="px-3 py-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg text-slate-700 dark:text-slate-300 focus:outline-none focus:border-indigo-500 text-sm">
                            <option value="newest" <?= ($sort_order === 'newest')    ? 'selected' : '' ?>>Newest</option>
                            <option value="oldest" <?= ($sort_order === 'oldest')    ? 'selected' : '' ?>>Oldest</option>
                            <option value="downloads" <?= ($sort_order === 'downloads') ? 'selected' : '' ?>>Most Downloaded</option>
                        </select>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <!-- Document Grid -->
        <div id="document-list" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            <?php if (count($documents) > 0): ?>
                <?php foreach ($documents as $doc): ?>
                    <a href="/details/<?= $doc['id'] ?>/" class="group flex flex-col bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm hover:shadow-xl hover:-translate-y-1 transition-all duration-300 overflow-hidden">
                        <div class="p-5 flex flex-col h-full">
                            <div class="flex items-start justify-between mb-4">
                                <div class="w-12 h-12 rounded-xl bg-indigo-50 dark:bg-indigo-900/30 flex items-center justify-center text-indigo-600 dark:text-indigo-400 group-hover:scale-110 transition-transform">
                                    <span class="material-symbols-outlined text-2xl"><?= get_file_icon($doc['file_type']) ?></span>
                                </div>
                                <span class="px-2.5 py-1 bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 text-xs font-medium rounded-full">
                                    <?= formatBytes($doc['file_size']) ?>
                                </span>
                            </div>
                            <h3 class="text-lg font-bold text-slate-900 dark:text-white mb-2 line-clamp-2 group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors">
                                <?= htmlspecialchars($doc['title']) ?>
                            </h3>
                            <p class="text-sm text-slate-500 dark:text-slate-400 mb-4 line-clamp-2">
                                <?= htmlspecialchars($doc['description']) ?>
                            </p>
                            <div class="mt-auto flex flex-col gap-1.5 text-xs text-slate-500 dark:text-slate-400">
                                <?php if ($doc['course_name']): ?>
                                    <div class="flex items-center gap-1.5"><span class="material-symbols-outlined text-[14px]">school</span> <span class="truncate"><?= htmlspecialchars($doc['course_name']) ?></span></div>
                                <?php endif; ?>
                                <?php if ($doc['department_name']): ?>
                                    <div class="flex items-center gap-1.5"><span class="material-symbols-outlined text-[14px]">corporate_fare</span> <span class="truncate"><?= htmlspecialchars($doc['department_name']) ?></span></div>
                                <?php endif; ?>
                                <div class="flex items-center gap-1.5"><span class="material-symbols-outlined text-[14px]">calendar_today</span> <?= htmlspecialchars($doc['year_of_study']) ?></div>
                            </div>
                        </div>
                        <div class="px-5 py-3 border-t border-slate-100 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50 flex justify-between items-center text-xs text-slate-500 dark:text-slate-400">
                            <span>Uploaded <?= date('M j, Y', strtotime($doc['uploaded_at'])) ?></span>
                            <span class="flex items-center gap-1 text-indigo-600 dark:text-indigo-400 font-medium group-hover:translate-x-1 transition-transform">View <span class="material-symbols-outlined text-sm">arrow_forward</span></span>
                        </div>
                    </a>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col-span-full flex flex-col items-center justify-center py-20 text-center">
                    <div class="w-24 h-24 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mb-6 shadow-inner">
                        <span class="material-symbols-outlined text-5xl text-slate-400 dark:text-slate-500">search_off</span>
                    </div>
                    <h3 class="text-2xl font-bold text-slate-900 dark:text-white mb-3">No Documents Found</h3>
                    <p class="text-slate-500 dark:text-slate-400 max-w-md mx-auto mb-8 text-lg">
                        <?php if ($search_term): ?>
                            We couldn't find any documents matching "<?= htmlspecialchars($search_term) ?>". Try different keywords.
                        <?php else: ?>
                            No documents are available right now. Please check back soon.
                        <?php endif; ?>
                    </p>
                    <?php if ($search_term): ?>
                        <a href="/notes/" class="inline-flex items-center gap-2 px-6 py-3 rounded-full bg-indigo-600 text-white font-semibold hover:bg-indigo-700 transition-colors shadow-lg shadow-indigo-500/20">
                            <span class="material-symbols-outlined">restart_alt</span>
                            Clear Search
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="mt-12 flex justify-center">
                <nav class="flex items-center gap-1 p-1 rounded-full bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 shadow-sm" aria-label="Pagination">

                    <?php if ($page > 1): ?>
                        <a href="<?= paginate_url($page - 1, $search_term, $sort_order) ?>"
                            class="w-10 h-10 flex items-center justify-center rounded-full text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors">
                            <span class="material-symbols-outlined text-lg">chevron_left</span>
                        </a>
                    <?php endif; ?>

                    <?php
                    $range = 2;
                    $start = max(1, $page - $range);
                    $end   = min($total_pages, $page + $range);

                    if ($start > 1): ?>
                        <a href="<?= paginate_url(1, $search_term, $sort_order) ?>"
                            class="w-10 h-10 flex items-center justify-center rounded-full text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors">1</a>
                        <?php if ($start > 2): ?>
                            <span class="w-10 h-10 flex items-center justify-center text-slate-400">...</span>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php for ($i = $start; $i <= $end; $i++): ?>
                        <a href="<?= paginate_url($i, $search_term, $sort_order) ?>"
                            class="w-10 h-10 flex items-center justify-center rounded-full font-bold transition-all <?= $i === $page ? 'bg-indigo-600 text-white shadow-md' : 'text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700' ?>">
                            <?= $i ?>
                        </a>
                    <?php endfor; ?>

                    <?php if ($end < $total_pages): ?>
                        <?php if ($end < $total_pages - 1): ?>
                            <span class="w-10 h-10 flex items-center justify-center text-slate-400">...</span>
                        <?php endif; ?>
                        <a href="<?= paginate_url($total_pages, $search_term, $sort_order) ?>"
                            class="w-10 h-10 flex items-center justify-center rounded-full text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"><?= $total_pages ?></a>
                    <?php endif; ?>

                    <?php if ($page < $total_pages): ?>
                        <a href="<?= paginate_url($page + 1, $search_term, $sort_order) ?>"
                            class="w-10 h-10 flex items-center justify-center rounded-full text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors">
                            <span class="material-symbols-outlined text-lg">chevron_right</span>
                        </a>
                    <?php endif; ?>

                </nav>
            </div>
        <?php endif; ?>

    </div>
</div>

<?php require_once __DIR__ . '/../partials/footer.php'; ?>