<?php
// Start session for navbar
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Get search query
$search_query = trim($_GET['q'] ?? '');
$active_tab = $_GET['tab'] ?? 'all'; // Default to 'all' if no tab specified

// Initialize results
$programs = [];
$universities = [];
$blog_posts = [];
$students = [];

// Perform search if query is not empty
if (!empty($search_query)) {
    try {
        // Search programs (only if active tab is 'all' or 'programs')
        if ($active_tab === 'all' || $active_tab === 'programs') {
            $stmt = $pdo->prepare("SELECT p.*, u.name as university_name, u.logo as university_logo, 
                                  c.name as country_name
                                  FROM programs p
                                  JOIN universities u ON p.university_id = u.id
                                  JOIN countries c ON u.country_id = c.id
                                  WHERE p.name LIKE ? OR u.name LIKE ? OR c.name LIKE ? OR p.program_description LIKE ?
                                  ORDER BY p.created_at DESC
                                  LIMIT 10");
            $stmt->execute(["%$search_query%", "%$search_query%", "%$search_query%", "%$search_query%"]);
            $programs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        // Search universities (only if active tab is 'all' or 'universities')
        if ($active_tab === 'all' || $active_tab === 'universities') {
            $stmt = $pdo->prepare("SELECT u.*, c.name as country_name, 
                                  (SELECT COUNT(*) FROM programs p WHERE p.university_id = u.id) as program_count
                                  FROM universities u
                                  JOIN countries c ON u.country_id = c.id
                                  WHERE u.name LIKE ? OR c.name LIKE ? OR u.description LIKE ?
                                  ORDER BY u.created_at DESC
                                  LIMIT 10");
            $stmt->execute(["%$search_query%", "%$search_query%", "%$search_query%"]);
            $universities = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        // Search blog posts (only if active tab is 'all' or 'blog')
        if ($active_tab === 'all' || $active_tab === 'blog') {
            $stmt = $pdo->prepare("SELECT bp.*, c.name as category_name
                                  FROM blog_posts bp
                                  JOIN categories c ON bp.category_id = c.id
                                  WHERE bp.title LIKE ? OR bp.excerpt LIKE ? OR bp.content LIKE ?
                                  AND bp.status = 'published'
                                  ORDER BY bp.created_at DESC
                                  LIMIT 10");
            $stmt->execute(["%$search_query%", "%$search_query%", "%$search_query%"]);
            $blog_posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        // Search students (admin only, only if active tab is 'all' or 'students')
        if (isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'admin' && 
            ($active_tab === 'all' || $active_tab === 'students')) {
            $stmt = $pdo->prepare("SELECT s.*, u.email, u.last_login,
                                  CONCAT(s.first_name, ' ', s.last_name) as full_name
                                  FROM students s
                                  JOIN users u ON s.id = u.id
                                  WHERE s.first_name LIKE ? OR s.last_name LIKE ? OR u.email LIKE ? OR s.phone LIKE ?
                                  ORDER BY s.created_at DESC
                                  LIMIT 10");
            $stmt->execute(["%$search_query%", "%$search_query%", "%$search_query%", "%$search_query%"]);
            $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
    } catch (PDOException $e) {
        // Handle database errors gracefully
        error_log("Search error: " . $e->getMessage());
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Search Results for "<?= htmlspecialchars($search_query) ?>" - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .search-header {
            background: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url('img/search-bg.jpg');
            background-size: cover;
            background-position: center;
            color: white;
            padding: 80px 0;
            margin-bottom: 30px;
        }
        .search-result {
            border-bottom: 1px solid #eee;
            padding: 20px 0;
            transition: all 0.3s;
        }
        .search-result:hover {
            background: #f8f9fa;
            border-radius: 5px;
        }
        .search-result:last-child {
            border-bottom: none;
        }
        .search-result-img {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 5px;
        }
        .search-result-title {
            font-size: 1.2em;
            margin-bottom: 5px;
        }
        .search-result-meta {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 10px;
        }
        .search-result-excerpt {
            color: #555;
            line-height: 1.5;
        }
        .search-result-highlight {
            background-color: #fff3cd;
            padding: 2px 4px;
            border-radius: 3px;
            font-weight: 600;
        }
        .search-tabs {
            border-bottom: 2px solid #eee;
            margin-bottom: 30px;
        }
        .search-tabs .nav-link {
            color: #666;
            border: none;
            padding: 15px 20px;
            font-weight: 600;
        }
        .search-tabs .nav-link.active {
            color: #3FB7FE;
            border-bottom: 3px solid #3FB7FE;
        }
        .no-results {
            text-align: center;
            padding: 50px 0;
            color: #666;
        }
        .no-results i {
            font-size: 4em;
            color: #ddd;
            margin-bottom: 20px;
        }
        .search-stats {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 30px;
        }
        .search-query {
            font-weight: 600;
            color: #3FB7FE;
        }
    </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<!-- Search Header -->
<div class="search-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-8">
                <h1 class="display-4">Search Results</h1>
                <p class="lead">Found results for: <span class="search-query">"<?= htmlspecialchars($search_query) ?>"</span></p>
                <?php if (!empty($search_query)): ?>
                <p><?= array_sum([
                    count($programs), 
                    count($universities), 
                    count($blog_posts), 
                    (isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'admin') ? count($students) : 0
                ]) ?> results found</p>
                <?php endif; ?>
            </div>
            <div class="col-lg-4">
                <!-- Search Form -->
                <form method="GET" class="bg-white p-4 rounded">
                    <div class="input-group">
                        <input type="text" name="q" class="form-control border-0" placeholder="Search courses, universities, or articles..." value="<?= htmlspecialchars($search_query) ?>" required>
                        <div class="input-group-append">
                            <button class="btn btn-primary" type="submit">
                                <i class="fa fa-search"></i>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="container py-5">
    <?php if (empty($search_query)): ?>
    <!-- No search query provided -->
    <div class="text-center py-5">
        <i class="fa fa-search fa-5x text-muted mb-4"></i>
        <h2>What are you looking for?</h2>
        <p class="text-muted">Enter a search term to find programs, universities, blog posts, and more.</p>
        <form method="GET" class="mt-4">
            <div class="input-group input-group-lg" style="max-width: 600px; margin: 0 auto;">
                <input type="text" name="q" class="form-control" placeholder="Search courses, universities, or articles..." required>
                <div class="input-group-append">
                    <button class="btn btn-primary" type="submit">Search</button>
                </div>
            </div>
        </form>
    </div>
    
    <?php else: ?>
    <!-- Search results with tabs -->
    <div class="search-stats">
        <div class="row">
            <div class="col-md-3 col-6 mb-2 mb-md-0">
                <strong><?= count($programs) ?></strong> Programs
            </div>
            <div class="col-md-3 col-6 mb-2 mb-md-0">
                <strong><?= count($universities) ?></strong> Universities
            </div>
            <div class="col-md-3 col-6">
                <strong><?= count($blog_posts) ?></strong> Blog Posts
            </div>
            <?php if (isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'admin'): ?>
            <div class="col-md-3 col-6">
                <strong><?= count($students) ?></strong> Students
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Search Tabs -->
    <ul class="nav nav-tabs search-tabs" id="searchTabs" role="tablist">
        <li class="nav-item">
            <a class="nav-link <?= $active_tab === 'all' ? 'active' : '' ?>" 
               id="all-tab" 
               href="search.php?q=<?= urlencode($search_query) ?>&tab=all" 
               role="tab">
               <i class="fa fa-th-large mr-2"></i>All Results
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?= $active_tab === 'programs' ? 'active' : '' ?>" 
               id="programs-tab" 
               href="search.php?q=<?= urlencode($search_query) ?>&tab=programs" 
               role="tab">
               <i class="fa fa-graduation-cap mr-2"></i>Programs (<?= count($programs) ?>)
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?= $active_tab === 'universities' ? 'active' : '' ?>" 
               id="universities-tab" 
               href="search.php?q=<?= urlencode($search_query) ?>&tab=universities" 
               role="tab">
               <i class="fa fa-university mr-2"></i>Universities (<?= count($universities) ?>)
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?= $active_tab === 'blog' ? 'active' : '' ?>" 
               id="blog-tab" 
               href="search.php?q=<?= urlencode($search_query) ?>&tab=blog" 
               role="tab">
               <i class="fa fa-newspaper mr-2"></i>Blog Posts (<?= count($blog_posts) ?>)
            </a>
        </li>
        <?php if (isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'admin'): ?>
        <li class="nav-item">
            <a class="nav-link <?= $active_tab === 'students' ? 'active' : '' ?>" 
               id="students-tab" 
               href="search.php?q=<?= urlencode($search_query) ?>&tab=students" 
               role="tab">
               <i class="fa fa-users mr-2"></i>Students (<?= count($students) ?>)
            </a>
        </li>
        <?php endif; ?>
    </ul>
    
    <!-- Search Results -->
    <div class="tab-content" id="searchTabContent">
        <div class="tab-pane fade show active" role="tabpanel">
            <?php if (empty($programs) && empty($universities) && empty($blog_posts) && 
                     !(isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'admin' && !empty($students))): ?>
            <!-- No results found -->
            <div class="no-results">
                <i class="fa fa-search-minus"></i>
                <h3>No results found</h3>
                <p>We couldn't find any results matching your search for "<strong><?= htmlspecialchars($search_query) ?></strong>".</p>
                <p>Try searching with different keywords or browse our <a href="index.php">homepage</a>.</p>
            </div>
            
            <?php else: ?>
            <!-- Results by category -->
            <?php if (($active_tab === 'all' || $active_tab === 'programs') && !empty($programs)): ?>
            <h3 class="mt-4 mb-3"><i class="fa fa-graduation-cap text-primary mr-2"></i>Programs</h3>
            <div class="mb-5">
                <?php foreach ($programs as $program): ?>
                <div class="search-result">
                    <div class="row">
                        <div class="col-12 col-md-4 mb-3 mb-md-0">
                            <a href="program-profile.php?id=<?= $program['id'] ?>">
                                <img src="<?= htmlspecialchars($program['university_logo'] ?: 'img/university-placeholder.png') ?>" 
                                     alt="<?= htmlspecialchars($program['university_name']) ?>" 
                                     class="search-result-img">
                            </a>
                        </div>
                        <div class="col-12 col-md-8">
                            <h4 class="search-result-title">
                                <a href="program-profile.php?id=<?= $program['id'] ?>" class="text-dark">
                                    <?= highlightText(htmlspecialchars($program['name']), $search_query) ?>
                                </a>
                            </h4>
                            <div class="search-result-meta">
                                <span><i class="fa fa-university mr-1"></i> <?= htmlspecialchars($program['university_name']) ?></span>
                                <span class="mx-2">|</span>
                                <span><i class="fa fa-map-marker-alt mr-1"></i> <?= htmlspecialchars($program['country_name']) ?></span>
                                <span class="mx-2">|</span>
                                <span><i class="fa fa-clock mr-1"></i> <?= $program['duration_months'] ?> months</span>
                            </div>
                            <p class="search-result-excerpt">
                                <?= highlightText(getExcerpt($program['program_description'], $search_query), $search_query) ?>
                            </p>
                            <a href="program-profile.php?id=<?= $program['id'] ?>" class="btn btn-sm btn-primary">View Program</a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <?php if (($active_tab === 'all' || $active_tab === 'universities') && !empty($universities)): ?>
            <h3 class="mt-4 mb-3"><i class="fa fa-university text-primary mr-2"></i>Universities</h3>
            <div class="mb-5">
                <?php foreach ($universities as $university): ?>
                <div class="search-result">
                    <div class="row">
                        <div class="col-12 col-md-4 mb-3 mb-md-0">
                            <a href="university-profile.php?id=<?= $university['id'] ?>">
                                <img src="<?= htmlspecialchars($university['logo'] ?: 'img/university-placeholder.png') ?>" 
                                     alt="<?= htmlspecialchars($university['name']) ?>" 
                                     class="search-result-img">
                            </a>
                        </div>
                        <div class="col-12 col-md-8">
                            <h4 class="search-result-title">
                                <a href="university-profile.php?id=<?= $university['id'] ?>" class="text-dark">
                                    <?= highlightText(htmlspecialchars($university['name']), $search_query) ?>
                                </a>
                            </h4>
                            <div class="search-result-meta">
                                <span><i class="fa fa-map-marker-alt mr-1"></i> <?= htmlspecialchars($university['country_name']) ?></span>
                                <span class="mx-2">|</span>
                                <span><i class="fa fa-graduation-cap mr-1"></i> <?= $university['program_count'] ?> Programs</span>
                            </div>
                            <p class="search-result-excerpt">
                                <?= highlightText(getExcerpt($university['description'], $search_query), $search_query) ?>
                            </p>
                            <a href="university-profile.php?id=<?= $university['id'] ?>" class="btn btn-sm btn-primary">View University</a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <?php if (($active_tab === 'all' || $active_tab === 'blog') && !empty($blog_posts)): ?>
            <h3 class="mt-4 mb-3"><i class="fa fa-newspaper text-primary mr-2"></i>Blog Posts</h3>
            <div class="mb-5">
                <?php foreach ($blog_posts as $post): ?>
                <div class="search-result">
                    <div class="row">
                        <div class="col-12 col-md-4 mb-3 mb-md-0">
                            <a href="blog-post.php?slug=<?= urlencode($post['slug']) ?>">
                                <img src="<?= htmlspecialchars($post['featured_image'] ?: 'img/blog-default.jpg') ?>" 
                                     alt="<?= htmlspecialchars($post['title']) ?>" 
                                     class="search-result-img">
                            </a>
                        </div>
                        <div class="col-12 col-md-8">
                            <h4 class="search-result-title">
                                <a href="blog-post.php?slug=<?= urlencode($post['slug']) ?>" class="text-dark">
                                    <?= highlightText(htmlspecialchars($post['title']), $search_query) ?>
                                </a>
                            </h4>
                            <div class="search-result-meta">
                                <span><i class="fa fa-folder-open mr-1"></i> <?= htmlspecialchars($post['category_name']) ?></span>
                                <span class="mx-2">|</span>
                                <span><i class="far fa-calendar-alt mr-1"></i> <?= date('M j, Y', strtotime($post['created_at'])) ?></span>
                            </div>
                            <p class="search-result-excerpt">
                                <?= highlightText(getExcerpt($post['excerpt'], $search_query), $search_query) ?>
                            </p>
                            <a href="blog-post.php?slug=<?= urlencode($post['slug']) ?>" class="btn btn-sm btn-primary">Read More</a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <?php if (isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'admin' && 
                     ($active_tab === 'all' || $active_tab === 'students') && !empty($students)): ?>
            <h3 class="mt-4 mb-3"><i class="fa fa-users text-primary mr-2"></i>Students</h3>
            <div class="mb-5">
                <?php foreach ($students as $student): ?>
                <div class="search-result">
                    <div class="row">
                        <div class="col-12 col-md-4 mb-3 mb-md-0">
                            <div class="d-flex align-items-center">
                                <img src="img/profile-placeholder.jpg" 
                                     alt="<?= htmlspecialchars($student['full_name']) ?>" 
                                     class="search-result-img">
                                <div class="ml-3">
                                    <h5 class="mb-0"><?= htmlspecialchars($student['full_name']) ?></h5>
                                    <small><?= htmlspecialchars($student['email']) ?></small>
                                </div>
                            </div>
                        </div>
                        <div class="col-12 col-md-8">
                            <div class="search-result-meta">
                                <span><i class="fa fa-phone-alt mr-1"></i> <?= htmlspecialchars($student['phone']) ?></span>
                                <span class="mx-2">|</span>
                                <span><i class="far fa-calendar-alt mr-1"></i> Joined <?= date('M j, Y', strtotime($student['created_at'])) ?></span>
                                <?php if ($student['last_login']): ?>
                                <span class="mx-2">|</span>
                                <span><i class="far fa-clock mr-1"></i> Last active <?= timeAgo($student['last_login']) ?></span>
                                <?php endif; ?>
                            </div>
                            <p class="search-result-excerpt">
                                <?php if ($student['preferred_destinations']): ?>
                                <strong>Preferred Destinations:</strong> <?= htmlspecialchars($student['preferred_destinations']) ?><br>
                                <?php endif; ?>
                                <?php if ($student['preferred_programs']): ?>
                                <strong>Preferred Programs:</strong> <?= htmlspecialchars($student['preferred_programs']) ?>
                                <?php endif; ?>
                            </p>
                            <a href="admin-student-profile.php?id=<?= $student['id'] ?>" class="btn btn-sm btn-primary">View Profile</a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script src="lib/easing/easing.min.js"></script>
<script src="lib/waypoints/waypoints.min.js"></script>
<script src="lib/counterup/counterup.min.js"></script>
<script src="lib/owlcarousel/owl.carousel.min.js"></script>
<script src="js/main.js"></script>

<script>
    // Function to highlight search terms in text
    function highlightText(text, query) {
        if (!query) return text;
        
        // Create a regular expression to find the query (case insensitive)
        const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
        
        // Replace the query with highlighted version
        return text.replace(regex, '<span class="search-result-highlight">$1</span>');
    }
</script>

<?php
// Helper functions
function highlightText($text, $query) {
    if (empty($query)) return $text;
    
    // Escape special regex characters in the query
    $escaped_query = preg_quote($query, '/');
    
    // Create a case-insensitive regex pattern
    $pattern = '/' . $escaped_query . '/i';
    
    // Replace matches with highlighted version
    return preg_replace($pattern, '<span class="search-result-highlight">$0</span>', $text);
}

function getExcerpt($text, $query, $length = 150) {
    if (empty($text)) return '';
    
    // Strip HTML tags
    $text = strip_tags($text);
    
    // If text is shorter than length, return as is
    if (strlen($text) <= $length) {
        return $text . '...';
    }
    
    // Find the position of the query if it exists
    $pos = stripos($text, $query);
    
    if ($pos !== false) {
        // If query is found, create excerpt centered around it
        $start = max(0, $pos - ($length / 2));
        $excerpt = '...' . substr($text, $start, $length) . '...';
    } else {
        // If query not found, take the beginning of the text
        $excerpt = substr($text, 0, $length) . '...';
    }
    
    return $excerpt;
}

function timeAgo($datetime) {
    $time = strtotime($datetime);
    $time_diff = time() - $time;
    
    if ($time_diff < 60) {
        return $time_diff . ' seconds ago';
    } elseif ($time_diff < 3600) {
        return floor($time_diff / 60) . ' minutes ago';
    } elseif ($time_diff < 86400) {
        return floor($time_diff / 3600) . ' hours ago';
    } elseif ($time_diff < 2592000) {
        return floor($time_diff / 86400) . ' days ago';
    } elseif ($time_diff < 31536000) {
        return floor($time_diff / 2592000) . ' months ago';
    } else {
        return floor($time_diff / 31536000) . ' years ago';
    }
}
?>
</body>
</html>