<?php
require_once 'vendor/autoload.php';
require_once 'pdf_search.php';

// Récupération des fichiers PDF
$pdf_dir = __DIR__ . '/pdfs';
$files = array_filter(scandir($pdf_dir), function ($file) use ($pdf_dir) {
    return pathinfo($file, PATHINFO_EXTENSION) === 'pdf';
});
sort($files, SORT_NATURAL | SORT_FLAG_CASE);
?>

<!DOCTYPE html>
<html lang="fr">

<head>
    <meta charset="UTF-8">
    <title>Documentation & Recherche PDF</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            display: flex;
            gap: 20px;
            margin: 0 auto;
            height: calc(100vh - 40px);
        }

        .panel {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .left {
            flex: 1;
            min-width: 300px;
        }

        .right {
            flex: 2;
            min-width: 600px;
        }

        .panel-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 16px 20px;
            font-weight: 600;
            font-size: 16px;
        }

        .panel-content {
            padding: 20px;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .search-container {
            margin-bottom: 16px;
        }

        .left .search-container {
            display: flex;
            gap: 8px;
            align-items: center;
            width: 100%;
        }

        .left .search-wrapper {
            flex: 1;
            position: relative;
            display: flex;
            align-items: center;
            width: 100%;
        }

        .left .search-input {
            width: 100%;
            padding: 12px 40px 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.2s ease;
            box-sizing: border-box;
        }

        .right .search-container {
            position: relative;
        }

        .right .search-input {
            width: 100%;
            padding: 12px 40px 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.2s ease;
            box-sizing: border-box;
        }

        .search-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .left .search-controls {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
        }

        .right .search-controls {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            gap: 4px;
        }

        .sort-controls {
            display: flex;
            gap: 4px;
        }

        .control-btn {
            width: 24px;
            height: 24px;
            border: none;
            background: #f8f9fa;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #6c757d;
            transition: all 0.2s ease;
        }

        .control-btn:hover {
            background: #e9ecef;
            color: #495057;
        }

        .clear-btn {
            color: #dc3545;
        }

        .clear-btn:hover {
            background: #f8d7da;
            color: #721c24;
        }

        .scroll-list {
            flex: 1;
            overflow-y: auto;
            max-height: 93%;
            /* max-height: calc(100vh - 40px); */
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            background: #fafbfc;
        }

        .scroll-list::-webkit-scrollbar {
            width: 8px;
        }

        .scroll-list::-webkit-scrollbar-track {
            background: #f1f3f4;
        }

        .scroll-list::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .scroll-list::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        .pdf-item {
            display: block;
            padding: 12px 16px;
            border-bottom: 1px solid #e9ecef;
            transition: background-color 0.2s ease;
            font-size: 14px;
            line-height: 1.4;
            text-decoration: none;
            color: #495057;
        }

        .pdf-item:last-child {
            border-bottom: none;
        }

        .pdf-item:hover {
            background: #f8f9fa;
            text-decoration: none;
            color: #2196f3;
        }

        .result-container {
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            background: #fafbfc;
            flex: 1;
            max-height: 93%;
            overflow-y: auto;
        }

        .result-item {
            padding: 16px;
            border-bottom: 1px solid #e9ecef;
        }

        .result-item:last-child {
            border-bottom: none;
        }

        .result-file {
            font-weight: 600;
            color: #2196f3;
            text-decoration: none;
            margin-bottom: 8px;
            display: block;
        }

        .result-file:hover {
            text-decoration: underline;
        }

        .result-snippet {
            color: #6c757d;
            font-style: italic;
            font-size: 13px;
            line-height: 1.4;
        }

        .no-results {
            padding: 40px 20px;
            text-align: center;
            color: #6c757d;
            font-style: italic;
        }

        .results-header {
            padding: 16px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            font-weight: 600;
            color: #495057;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- Partie gauche -->
        <div class="left panel">
            <div class="panel-header">Filtrage des fichiers</div>
            <div class="panel-content">
                <div class="search-container">
                    <div class="search-wrapper">
                        <input type="text" id="filterInput" class="search-input" placeholder="Filtrer les titres PDF... (^ pour début, * pour joker)">
                        <div class="search-controls">
                            <button type="button" class="control-btn clear-btn" onclick="resetFilter()" title="Effacer">×</button>
                        </div>
                    </div>
                    <div class="sort-controls">
                        <button type="button" class="control-btn" onclick="sortList('asc')" title="Tri croissant">↑</button>
                        <button type="button" class="control-btn" onclick="sortList('desc')" title="Tri décroissant">↓</button>
                    </div>
                </div>
                <div class="scroll-list" id="pdfList">
                    <?php foreach ($files as $file): ?>
                        <a href="pdfs/<?= rawurlencode($file) ?>" target="_blank" class="pdf-item" data-title="<?= htmlspecialchars($file) ?>">
                            <?= htmlspecialchars($file) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Partie droite -->
        <div class="right panel">
            <div class="panel-header">Recherche dans le contenu des fichiers filtrés</div>
            <div class="panel-content">
                <div class="search-container">
                    <input type="text" id="searchInput" class="search-input" placeholder="Recherche dans les PDF filtrés...">
                    <div class="search-controls">
                        <button type="button" class="control-btn clear-btn" onclick="resetSearch()" title="Effacer">×</button>
                    </div>
                </div>
                <div class="result-container" id="searchResult"></div>
            </div>
        </div>
    </div>

    <script>
        // JS pour filtrer la liste des PDF par titre
        const pdfItems = Array.from(document.querySelectorAll('.pdf-item'));
        const pdfList = document.getElementById('pdfList');
        const filterInput = document.getElementById('filterInput');
        const searchInput = document.getElementById('searchInput');
        const searchResult = document.getElementById('searchResult');
        let filteredFiles = pdfItems.map(item => item.dataset.title);

        // Fonction pour convertir le pattern de filtre en regex
        function createFilterRegex(pattern) {
            if (!pattern) return null;

            // Échapper les caractères spéciaux sauf ^ et *
            let regexPattern = pattern.replace(/[.+?{}()|[\]\\]/g, '\\$&');

            // Gérer ^ pour début de titre
            if (regexPattern.startsWith('^')) {
                regexPattern = '^' + regexPattern.slice(1);
            }

            // Gérer * pour n'importe quel nombre de caractères
            regexPattern = regexPattern.replace(/\*/g, '.*');

            try {
                return new RegExp(regexPattern, 'i');
            } catch (e) {
                // Si la regex est invalide, utiliser une recherche simple
                return new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
            }
        }

        filterInput.addEventListener('input', function() {
            const val = this.value.trim();
            filteredFiles = [];

            if (!val) {
                // Si pas de filtre, afficher tous les fichiers
                pdfItems.forEach(item => {
                    item.style.display = '';
                    filteredFiles.push(item.dataset.title);
                });
            } else {
                const regex = createFilterRegex(val);
                pdfItems.forEach(item => {
                    const title = item.dataset.title;
                    if (regex && regex.test(title)) {
                        item.style.display = '';
                        filteredFiles.push(title);
                    } else {
                        item.style.display = 'none';
                    }
                });
            }
            clearSearchResult();
        });

        function resetFilter() {
            filterInput.value = '';
            pdfItems.forEach(item => item.style.display = '');
            filteredFiles = pdfItems.map(item => item.dataset.title);
            // clearSearchResult();
            resetSearch();
        }

        function sortList(order) {
            const visibleItems = pdfItems.filter(item => item.style.display !== 'none');
            visibleItems.sort((a, b) => {
                if (order === 'asc') {
                    return a.dataset.title.localeCompare(b.dataset.title, undefined, {
                        sensitivity: 'base'
                    });
                } else {
                    return b.dataset.title.localeCompare(a.dataset.title, undefined, {
                        sensitivity: 'base'
                    });
                }
            });
            visibleItems.forEach(item => pdfList.appendChild(item));
        }

        // JS pour recherche dans les PDF filtrés
        searchInput.addEventListener('input', function() {
            const val = this.value.trim();
            if (val.length < 2) {
                clearSearchResult();
                return;
            }
            // AJAX vers pdf_search.php
            fetch('pdf_search.php?q=' + encodeURIComponent(val))
                .then(res => res.json())
                .then(data => {
                    // Filtrer les résultats selon filteredFiles
                    const filteredResults = data.filter(r => filteredFiles.includes(r.file));
                    showResults(filteredResults);
                });
        });

        function resetSearch() {
            searchInput.value = '';
            clearSearchResult();
        }

        function clearSearchResult() {
            searchResult.innerHTML = '';
        }

        function showResults(results) {
            if (results.length === 0) {
                searchResult.innerHTML = '<div class="no-results">Aucun résultat trouvé.</div>';
                return;
            }
            let html = '<div class="results-header">Résultats (' + results.length + ')</div>';
            results.forEach(r => {
                html += `<div class="result-item">
                    <a href="pdfs/${encodeURIComponent(r.file)}" target="_blank" class="result-file">${r.file}</a>
                    <div class="result-snippet">... ${r.snippet} ...</div>
                </div>`;
            });
            searchResult.innerHTML = html;
        }
    </script>
</body>

</html>