<?php
$resourceDir = __DIR__;

function isHtmlFile(string $filePath): bool
{
    $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    if ($ext === 'html' || $ext === 'htm') {
        return true;
    }
    if ($ext === 'php' && !in_array(basename($filePath), ['index.php', 'resources-site-config.php'])) {
        return true;
    }
    if ($ext === '' && is_readable($filePath) && filesize($filePath) > 0) {
        $handle = @fopen($filePath, 'r');
        if ($handle) {
            $firstBytes = fread($handle, 256);
            fclose($handle);
            if (stripos($firstBytes, '<!doctype html') !== false || stripos($firstBytes, '<html') !== false) {
                return true;
            }
        }
    }
    return false;
}

$allFiles = glob($resourceDir . '/*') ?: [];
$htmlFiles = array_filter($allFiles, function ($file) {
    if (!is_file($file)) return false;
    return isHtmlFile($file);
});
sort($htmlFiles, SORT_NATURAL | SORT_FLAG_CASE);

function prettyLabel(string $file): string
{
    $label = pathinfo($file, PATHINFO_FILENAME);
    $label = preg_replace('/[-_]+/', ' ', $label);
    return ucwords(strtolower($label));
}

function formatBytes(int $bytes): string
{
    if ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 1) . ' MB';
    }
    if ($bytes >= 1024) {
        return number_format($bytes / 1024, 1) . ' KB';
    }
    return $bytes . ' B';
}

function getFileExtensionIcon(string $filename): string
{
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if ($ext === 'html' || $ext === 'htm') return 'fa-html5';
    if ($ext === 'php') return 'fa-php';
    return 'fa-file-code';
}

function getFileTypeLabel(string $filename): string
{
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if ($ext === 'html' || $ext === 'htm') return 'HTML';
    if ($ext === 'php') return 'PHP';
    return 'HTML';
}

function getFileExtension(string $filename): string
{
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if ($ext === '') return 'html';
    return $ext;
}

function getGradientClass(string $filename): string
{
    $hash = crc32($filename);
    $gradients = [
        'from-indigo-500 to-blue-600',
        'from-emerald-500 to-teal-600',
        'from-amber-500 to-orange-500',
        'from-rose-500 to-pink-600',
        'from-purple-500 to-indigo-600',
        'from-cyan-500 to-blue-500',
        'from-violet-500 to-purple-600',
        'from-teal-500 to-cyan-600',
    ];
    return $gradients[abs($hash) % count($gradients)];
}

function getBadgeClass(string $filename): string
{
    $hash = crc32($filename);
    $badges = [
        'bg-indigo-50 text-indigo-700 border-indigo-100',
        'bg-emerald-50 text-emerald-700 border-emerald-100',
        'bg-amber-50 text-amber-700 border-amber-100',
        'bg-rose-50 text-rose-700 border-rose-100',
        'bg-purple-50 text-purple-700 border-purple-100',
        'bg-cyan-50 text-cyan-700 border-cyan-100',
        'bg-violet-50 text-violet-700 border-violet-100',
        'bg-teal-50 text-teal-700 border-teal-100',
    ];
    return $badges[abs($hash) % count($badges)];
}

$pageTitle = 'Resources';
$base_url = '../';
?>
<?php require_once __DIR__ . '/../includes/header.php'; ?>

<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

<script>
    tailwind.config = {
        theme: {
            extend: {
                colors: {
                    'primary': '#1E3A8A',
                    'primary-light': '#3B82F6',
                    'surface': '#F8FAFC',
                },
                fontFamily: {
                    sans: ['Inter', 'sans-serif'],
                },
            }
        }
    }
</script>

<style>
    body { font-family: 'Inter', sans-serif; background-color: #F1F5F9; }
    .file-card { transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
    .file-card:hover { transform: translateY(-4px); }
    .search-input:focus { box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15); }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(12px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .animate-fade-in { animation: fadeIn 0.4s ease-out forwards; }
</style>

<div class="min-h-screen">
    <!-- Top Navigation Bar -->
    <nav class="bg-white border-b border-slate-200 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center gap-3">
                    <a href="../dashboard.php" class="flex items-center gap-2 text-slate-600 hover:text-primary transition-colors">
                        <i class="fas fa-arrow-left"></i>
                        <span class="text-sm font-medium hidden sm:inline">Back to Dashboard</span>
                    </a>
                </div>
                <div class="flex items-center gap-3">
                    <span class="text-xs font-medium text-slate-500 bg-slate-100 px-3 py-1.5 rounded-full">
                        <i class="fas fa-folder-open mr-1.5 text-slate-400"></i>
                        <?php echo count($htmlFiles); ?> file<?php echo count($htmlFiles) !== 1 ? 's' : ''; ?> found
                    </span>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        
        <!-- Header Section -->
        <div class="mb-10 animate-fade-in">
            <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-4">
                <div>
                            <h1 class="text-3xl font-extrabold text-slate-900 tracking-tight">Resources</h1>
                            <p class="mt-2 text-slate-500 text-sm max-w-xl">
                                Browse and access all available files in the resources directory. Click any card to open the resource.
                            </p>
                </div>
                
                <!-- Search Bar -->
                <div class="relative w-full md:w-80">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3.5 pointer-events-none text-slate-400">
                        <i class="fas fa-search text-sm"></i>
                    </span>
                    <input 
                        type="text" 
                        id="searchInput" 
                        placeholder="Search resources..." 
                        class="search-input w-full pl-10 pr-4 py-2.5 bg-white border border-slate-200 rounded-xl text-sm text-slate-700 placeholder-slate-400 focus:outline-none focus:border-primary-light transition-all"
                    />
                    <button id="clearSearch" class="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600 hidden">
                        <i class="fas fa-times-circle text-sm"></i>
                    </button>
                </div>
            </div>
        </div>

        <?php if (count($htmlFiles) === 0): ?>
            <!-- Empty State -->
            <div class="bg-white rounded-2xl border border-slate-200 p-12 lg:p-16 text-center animate-fade-in">
                <div class="w-20 h-20 bg-slate-50 rounded-2xl flex items-center justify-center mx-auto mb-6 border border-slate-100">
                    <i class="fas fa-folder-open text-3xl text-slate-300"></i>
                </div>
                <h3 class="text-xl font-bold text-slate-900 mb-2">No resources found</h3>
                <p class="text-slate-500 text-sm max-w-md mx-auto mb-8">
                    The resources directory doesn't contain any files yet. Add some HTML or PHP files to get started.
                </p>
                <div class="flex flex-col sm:flex-row gap-3 justify-center">
                    <button onclick="window.location.reload()" class="inline-flex items-center justify-center gap-2 bg-primary text-white font-semibold text-sm px-5 py-2.5 rounded-xl hover:bg-primary/90 transition-colors shadow-sm">
                        <i class="fas fa-sync-alt text-xs"></i>
                        Refresh Page
                    </button>
                </div>
            </div>
        <?php else: ?>
            <!-- Stats Row -->
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8 animate-fade-in">
                <div class="bg-white rounded-xl border border-slate-200 p-4 flex items-center gap-3">
                    <div class="w-10 h-10 rounded-lg bg-indigo-50 flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-file-code text-indigo-600 text-sm"></i>
                    </div>
                    <div>
                        <span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Total Files</span>
                        <span class="text-lg font-bold text-slate-900"><?php echo count($htmlFiles); ?></span>
                    </div>
                </div>
                <div class="bg-white rounded-xl border border-slate-200 p-4 flex items-center gap-3">
                    <div class="w-10 h-10 rounded-lg bg-emerald-50 flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-hdd text-emerald-600 text-sm"></i>
                    </div>
                    <div>
                        <span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Total Size</span>
                        <span class="text-lg font-bold text-slate-900">
                            <?php
                                $totalSize = 0;
                                foreach ($htmlFiles as $f) $totalSize += filesize($f);
                                echo formatBytes($totalSize);
                            ?>
                        </span>
                    </div>
                </div>
                <div class="bg-white rounded-xl border border-slate-200 p-4 flex items-center gap-3">
                    <div class="w-10 h-10 rounded-lg bg-amber-50 flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-clock text-amber-600 text-sm"></i>
                    </div>
                    <div>
                        <span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Last Modified</span>
                        <span class="text-sm font-bold text-slate-900">
                            <?php
                                $latest = 0;
                                foreach ($htmlFiles as $f) $latest = max($latest, filemtime($f));
                                echo $latest ? date('M j, Y', $latest) : 'N/A';
                            ?>
                        </span>
                    </div>
                </div>
                <div class="bg-white rounded-xl border border-slate-200 p-4 flex items-center gap-3">
                    <div class="w-10 h-10 rounded-lg bg-cyan-50 flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-sort-amount-down text-cyan-600 text-sm"></i>
                    </div>
                    <div>
                        <span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Sort Order</span>
                        <span class="text-sm font-bold text-slate-900">A → Z</span>
                    </div>
                </div>
            </div>

            <!-- Files Grid -->
            <div id="filesGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                <?php foreach ($htmlFiles as $file): ?>
                    <?php
                        $name = basename($file);
                        $size = filesize($file);
                        $modified = filemtime($file);
                        $label = prettyLabel($name);
                        $gradient = getGradientClass($name);
                        $badge = getBadgeClass($name);
                    ?>
                    <a href="<?php echo rawurlencode($name); ?>" class="file-card group bg-white rounded-2xl border border-slate-200 overflow-hidden hover:border-indigo-300 hover:shadow-lg shadow-sm block" data-title="<?php echo htmlspecialchars(strtolower($label), ENT_QUOTES, 'UTF-8'); ?>">
                        <!-- Card Header -->
                        <div class="h-1.5 w-full bg-gradient-to-r <?php echo $gradient; ?>"></div>
                        
                        <div class="p-5">
                            <!-- File Icon & Type -->
                            <div class="flex items-start justify-between mb-4">
                                <div class="w-11 h-11 rounded-xl bg-slate-50 border border-slate-100 flex items-center justify-center flex-shrink-0 group-hover:border-indigo-100 transition-colors">
                                    <i class="fab <?php echo getFileExtensionIcon($name); ?> text-xl text-orange-500"></i>
                                </div>
                                <span class="text-[10px] font-bold uppercase tracking-wider px-2 py-1 rounded-md border <?php echo $badge; ?>">
                                    <?php echo getFileTypeLabel($name); ?>
                                </span>
                            </div>

                            <!-- File Name -->
                            <h3 class="text-sm font-bold text-slate-900 mb-1 group-hover:text-indigo-600 transition-colors line-clamp-2 leading-snug">
                                <?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>
                            </h3>
                            
                            <!-- File Path -->
                            <p class="text-[11px] font-mono text-slate-400 truncate mb-4">
                                /resources/<?php echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); ?>
                            </p>

                            <!-- File Meta -->
                            <div class="flex items-center gap-3 text-[11px] text-slate-500">
                                <span class="flex items-center gap-1.5">
                                    <i class="fas fa-weight-hanging text-slate-400"></i>
                                    <?php echo formatBytes($size); ?>
                                </span>
                                <span class="w-1 h-1 rounded-full bg-slate-300"></span>
                                <span class="flex items-center gap-1.5">
                                    <i class="far fa-calendar text-slate-400"></i>
                                    <?php echo date('M j, Y', $modified); ?>
                                </span>
                            </div>
                        </div>

                        <!-- Card Footer -->
                        <div class="px-5 py-3 bg-slate-50/80 border-t border-slate-100 flex items-center justify-between">
                            <span class="text-[11px] font-medium text-slate-500 flex items-center gap-1.5">
                                <i class="fas fa-external-link-alt text-slate-400 text-[10px]"></i>
                                Open Resource
                            </span>
                            <span class="text-xs font-bold text-indigo-600 group-hover:text-indigo-700 flex items-center gap-1 transition-colors">
                                View
                                <i class="fas fa-arrow-right text-[10px] transform group-hover:translate-x-0.5 transition-transform"></i>
                            </span>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>

            <!-- No Results State (hidden by default) -->
            <div id="noResults" class="hidden bg-white rounded-2xl border border-slate-200 p-12 text-center">
                <div class="w-16 h-16 rounded-full bg-slate-50 flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-search text-2xl text-slate-300"></i>
                </div>
                <h3 class="text-lg font-bold text-slate-900 mb-1">No matches found</h3>
                <p class="text-slate-500 text-sm">Try adjusting your search query</p>
            </div>
        <?php endif; ?>
    </main>

    <!-- Footer -->
    <footer class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 mt-8">
        <div class="border-t border-slate-200 pt-6 flex flex-col sm:flex-row items-center justify-between gap-3">
            <p class="text-xs text-slate-400">
                Resource directory scanner active &mdash; Monitoring <code class="bg-slate-100 px-1.5 py-0.5 rounded text-[11px] font-mono">/resources</code>
            </p>
            <p class="text-[11px] text-slate-400 font-mono">
                <?php echo date('Y-m-d H:i'); ?> &bull; System OK
            </p>
        </div>
    </footer>
</div>

<script>
    const searchInput = document.getElementById('searchInput');
    const clearBtn = document.getElementById('clearSearch');
    const cards = document.querySelectorAll('.file-card');
    const noResults = document.getElementById('noResults');

    if (searchInput) {
        searchInput.addEventListener('input', function () {
            const query = this.value.toLowerCase().trim();
            
            if (query.length > 0) {
                clearBtn.classList.remove('hidden');
            } else {
                clearBtn.classList.add('hidden');
            }

            let visibleCount = 0;
            cards.forEach(card => {
                const title = card.getAttribute('data-title') || '';
                if (title.includes(query)) {
                    card.classList.remove('hidden');
                    card.style.animation = 'none';
                    card.offsetHeight;
                    card.style.animation = 'fadeIn 0.3s ease-out forwards';
                    visibleCount++;
                } else {
                    card.classList.add('hidden');
                }
            });

            if (noResults) {
                if (visibleCount === 0 && query.length > 0) {
                    noResults.classList.remove('hidden');
                } else {
                    noResults.classList.add('hidden');
                }
            }
        });
    }

    if (clearBtn) {
        clearBtn.addEventListener('click', function () {
            searchInput.value = '';
            clearBtn.classList.add('hidden');
            searchInput.dispatchEvent(new Event('input'));
            searchInput.focus();
        });
    }
</script>

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