<?php
// Set page title before including header
$pageTitle = "Search Site - E&SE Kotli";
include_once 'header_new.php';

// Get and sanitize the search query
$searchQuery = isset($_GET['query']) ? trim(htmlspecialchars($_GET['query'])) : '';

/**
 * Highlights multiple search terms in text
 * @param string $text The original text
 * @param string $query The search query
 * @return string Highlighted text
 */
function highlightSearchTerm($text, $query) {
    if (empty($query)) return $text;
    
    // Split query into words (minimum 3 characters)
    $words = array_filter(
        explode(' ', $query),
        function($word) { return strlen($word) > 2; }
    );
    
    // Highlight each word
    foreach ($words as $word) {
        $text = preg_replace(
            "/(" . preg_quote($word, '/') . ")/i", 
            "<mark class='highlight'>$1</mark>", 
            $text
        );
    }
    return $text;
}

/**
 * Extracts clean text content from files (optimized)
 * @param string $filename File to read
 * @return string Clean text content
 */
function getCleanPageContent($filename) {
    if (!file_exists($filename)) return '';
    
    // Read first 50KB (optimal balance between content and performance)
    $content = @file_get_contents($filename, false, null, 0, 50000);
    if ($content === false) return '';
    
    // Remove unwanted content
    $content = preg_replace([
        '/<\?php.*?\?>/s',    // PHP code
        '/<!--.*?-->/s',      // HTML comments
        '/<script.*?<\/script>/is', // JavaScript
        '/<style.*?<\/style>/is'   // CSS
    ], '', $content);
    
    // Convert HTML entities and remove tags
    $content = html_entity_decode(strip_tags($content));
    $content = preg_replace('/\s+/', ' ', $content); // Normalize whitespace
    return trim($content);
}

/**
 * Performs intelligent search with relevance ranking
 * @param string $query Search term
 * @return array Sorted results
 */
function searchSite($query) {
    if (empty($query)) return [];
    
    // Pages with their display titles
    $pagesToSearch = [
        'index.php' => 'E&SE Kotli',
        'schools_info.php' => 'Schools Information',
        'teacher&staff_info.php' => 'Teachers & Staff',
        'students_info.php' => 'Student Information',
        'overall_info.php' => 'Overall Information',
        'org_chart.php' => 'Organizational Chart',
        'reg_schools.php' => 'Registered Private Schools',
        'unreg_schools.php' => 'Unregistered Private Schools',
        'blacklist_schools.php' => 'Blacklisted Schools',
        'reg_procedure.php' => 'Registration Procedure',
        'notification_show.php' => 'Notifications',
        'gallery_show.php' => 'Gallery',
        'contact_us.php' => 'Contact Us'
    ];
    
    $results = [];
    $queryWords = array_filter(
        explode(' ', strtolower($query)),
        function($word) { return strlen($word) > 2; }
    );
    
    foreach ($pagesToSearch as $page => $title) {
        $content = getCleanPageContent($page);
        if (empty($content)) continue;
        
        $lowerContent = strtolower($content);
        $lowerTitle = strtolower($title);
        
        // Calculate relevance score
        $titleMatches = 0;
        $contentMatches = 0;
        
        foreach ($queryWords as $word) {
            $titleMatches += substr_count($lowerTitle, $word);
            $contentMatches += substr_count($lowerContent, $word);
        }
        
        $totalMatches = $titleMatches + $contentMatches;
        
        if ($totalMatches > 0) {
            // Weighted scoring (title matches more important)
            $score = ($titleMatches * 10) + $contentMatches;
            
            // Find best excerpt position
            $positions = [];
            foreach ($queryWords as $word) {
                if (($pos = stripos($content, $word)) !== false) {
                    $positions[] = $pos;
                }
            }
            
            $startPos = !empty($positions) ? min($positions) : 0;
            
            // Generate intelligent excerpt
            $start = max(0, $startPos - 50);
            $excerpt = substr($content, $start, 300);
            
            if ($start > 0) $excerpt = '...' . $excerpt;
            if (strlen($content) > $start + 300) $excerpt .= '...';
            
            $results[] = [
                'title' => $title,
                'url' => $page,
                'excerpt' => $excerpt,
                'score' => $score,
                'matches' => $totalMatches,
                'title_matches' => $titleMatches
            ];
        }
    }
    
    // Sort by score (desc), then matches (desc), then title matches (desc)
    usort($results, function($a, $b) {
        return [$b['score'], $b['matches'], $b['title_matches']] 
               <=> [$a['score'], $a['matches'], $a['title_matches']];
    });
    
    return $results;
}

// Perform the search
$searchResults = searchSite($searchQuery);
?>

<!-- ====================== -->
<!-- ENHANCED CSS (OPTIMIZED) -->
<!-- ====================== -->
<style>
    :root {
        --highlight-color: #FFEB3B;
        --primary-color: #2C3E50;
        --secondary-color: #E74C3C;
        --accent-color: #3498DB;
    }
    
    .search-container {
        background: white;
        border-radius: 10px;
        box-shadow: 0 3px 15px rgba(0,0,0,0.1);
        padding: 2rem;
        margin: 2rem auto;
        max-width: 1200px;
        animation: fadeIn 0.5s ease;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .search-header {
        text-align: center;
        margin-bottom: 2rem;
        position: relative;
    }
    
    .search-header:after {
        content: '';
        display: block;
        width: 100px;
        height: 3px;
        background: var(--accent-color);
        margin: 1rem auto 0;
    }
    
    .search-meta {
        color: #666;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid #EEE;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .result-item {
        margin-bottom: 1.5rem;
        padding: 1.5rem;
        border-radius: 8px;
        border: 1px solid #EEE;
        background: white;
        transition: all 0.3s ease;
        animation: slideUp 0.5s ease;
        position: relative;
        overflow: hidden;
    }
    
    @keyframes slideUp {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .result-item:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        border-color: var(--accent-color);
    }
    
    .result-item h3 {
        color: var(--primary-color);
        margin-bottom: 0.5rem;
        font-size: 1.2rem;
    }
    
    .result-item h3 a {
        color: inherit;
        text-decoration: none;
    }
    
    .result-item h3 a:hover {
        color: var(--accent-color);
    }
    
    .result-url {
        color: #27AE60;
        font-size: 0.85rem;
        display: block;
        margin-bottom: 0.5rem;
        word-break: break-all;
    }
    
    .result-excerpt {
        color: #555;
        line-height: 1.6;
        margin: 0.5rem 0 1rem;
    }
    
    .result-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .relevance-badge {
        background: var(--primary-color);
        color: white;
        padding: 0.25rem 0.75rem;
        border-radius: 50px;
        font-size: 0.75rem;
        font-weight: bold;
    }
    
    .view-btn {
        background: var(--accent-color);
        color: white;
        padding: 0.4rem 1rem;
        border-radius: 4px;
        text-decoration: none;
        font-size: 0.9rem;
        transition: all 0.3s ease;
    }
    
    .view-btn:hover {
        background: var(--primary-color);
        color: white;
        transform: translateY(-2px);
    }
    
    .highlight {
        background-color: var(--highlight-color);
        color: #000;
        padding: 0 2px;
        border-radius: 3px;
        font-weight: bold;
    }
    
    .no-results {
        text-align: center;
        padding: 3rem 2rem;
        background: #F8F9FA;
        border-radius: 8px;
        animation: fadeIn 0.5s ease;
    }
    
    .no-results-icon {
        font-size: 3rem;
        color: var(--accent-color);
        margin-bottom: 1rem;
    }
    
    .search-tips {
        max-width: 600px;
        margin: 2rem auto 0;
        text-align: left;
    }
    
    .search-tips li {
        margin-bottom: 0.5rem;
    }
    
    .popular-searches {
        margin-top: 2rem;
    }
    
    .search-tag {
        display: inline-block;
        margin: 0.25rem;
        padding: 0.35rem 0.8rem;
        background: #EEE;
        border-radius: 50px;
        color: #333;
        text-decoration: none;
        transition: all 0.3s ease;
        font-size: 0.85rem;
    }
    
    .search-tag:hover {
        background: var(--accent-color);
        color: white;
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
        .search-container {
            padding: 1.5rem;
        }
        
        .result-item {
            padding: 1.25rem;
        }
        
        .result-actions {
            flex-direction: column;
            align-items: flex-start;
            gap: 0.5rem;
        }
        
        .relevance-badge {
            margin-bottom: 0.5rem;
        }
    }
</style>

<main>
    <div class="search-container">
        <div class="search-header">
            <h1>
                <?php if (empty($searchQuery)): ?>
                    Site Search
                <?php else: ?>
                    Results for: <span class="text-primary">"<?php echo $searchQuery; ?>"</span>
                <?php endif; ?>
            </h1>
        </div>
        
        <?php if (!empty($searchQuery)): ?>
            <div class="search-meta">
                <div>
                    <strong><?php echo count($searchResults); ?></strong> result(s) found
                    <?php if (!empty($searchResults)): ?>
                        <span class="text-muted ms-2">(sorted by relevance)</span>
                    <?php endif; ?>
                </div>
                <div>
                    <a href="?query=<?php echo urlencode($searchQuery); ?>" class="text-muted">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </a>
                </div>
            </div>
            
            <?php if (empty($searchResults)): ?>
                <div class="no-results">
                    <div class="no-results-icon">
                        <i class="fas fa-search-minus"></i>
                    </div>
                    <h3>No matches found</h3>
                    <p class="lead">We couldn't find any pages matching your search</p>
                    
                    <div class="search-tips">
                        <h5>Search tips:</h5>
                        <ul>
                            <li><i class="fas fa-check-circle text-success me-2"></i> Try different keywords</li>
                            <li><i class="fas fa-check-circle text-success me-2"></i> Check your spelling</li>
                            <li><i class="fas fa-check-circle text-success me-2"></i> Use more general terms</li>
                            <li><i class="fas fa-check-circle text-success me-2"></i> Avoid special characters</li>
                        </ul>
                    </div>
                    
                    <div class="popular-searches">
                        <h5>Try these searches:</h5>
                        <div>
                            <a href="?query=school+registration" class="search-tag">
                                <i class="fas fa-search me-1"></i> school registration
                            </a>
                            <a href="?query=teacher+list" class="search-tag">
                                <i class="fas fa-search me-1"></i> teacher list
                            </a>
                            <a href="?query=holidays" class="search-tag">
                                <i class="fas fa-search me-1"></i> holidays
                            </a>
                            <a href="?query=exam+schedule" class="search-tag">
                                <i class="fas fa-search me-1"></i> exam schedule
                            </a>
                            <a href="?query=contact" class="search-tag">
                                <i class="fas fa-search me-1"></i> contact
                            </a>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="search-results">
                    <?php foreach ($searchResults as $result): ?>
                        <div class="result-item" style="animation-delay: <?php echo min(0.3, $index * 0.1); ?>s">
                            <h3>
                                <a href="<?php echo $result['url'] . '?highlight=' . urlencode($searchQuery); ?>">
                                    <?php echo highlightSearchTerm($result['title'], $searchQuery); ?>
                                </a>
                            </h3>
                            
                            <a href="<?php echo $result['url']; ?>" class="result-url">
                                <?php echo $result['url']; ?>
                            </a>
                            
                            <p class="result-excerpt">
                                <?php echo highlightSearchTerm($result['excerpt'], $searchQuery); ?>
                            </p>
                            
                            <div class="result-actions">
                                <span class="relevance-badge">
                                    <?php 
                                    $percentage = min(100, (int)($result['score'] * 2));
                                    echo "$percentage% match";
                                    ?>
                                </span>
                                <a href="<?php echo $result['url'] . '?highlight=' . urlencode($searchQuery); ?>" 
                                   class="view-btn">
                                    View Page <i class="fas fa-arrow-right ms-1"></i>
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="no-results">
                <div class="no-results-icon">
                    <i class="fas fa-search"></i>
                </div>
                <h3>Search Our Website</h3>
                <p class="lead">Find information about schools, teachers, notifications and more</p>
                
                <div class="search-box mt-4" style="max-width: 600px; margin: 0 auto;">
                    <form action="" method="get" class="d-flex">
                        <input type="text" 
                               name="query" 
                               class="form-control form-control-lg" 
                               placeholder="Enter search terms..." 
                               required
                               autofocus>
                        <button class="btn btn-primary btn-lg ms-2" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                </div>
                
                <div class="popular-searches mt-5">
                    <h5>Popular searches:</h5>
                    <div>
                        <a href="?query=school+list" class="search-tag">
                            <i class="fas fa-school me-1"></i> school list
                        </a>
                        <a href="?query=admission" class="search-tag">
                            <i class="fas fa-file-signature me-1"></i> admission
                        </a>
                        <a href="?query=results" class="search-tag">
                            <i class="fas fa-award me-1"></i> results
                        </a>
                        <a href="?query=calendar" class="search-tag">
                            <i class="fas fa-calendar-alt me-1"></i> calendar
                        </a>
                        <a href="?query=staff" class="search-tag">
                            <i class="fas fa-chalkboard-teacher me-1"></i> staff
                        </a>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</main>

<?php include_once 'footer_new.php'; ?>