<?php
require_once 'config/config.php';

$database = new Database();
$db = $database->getConnection();

// Get search parameters
$keyword = isset($_GET['keyword']) ? sanitize($_GET['keyword']) : '';
$category = isset($_GET['category']) ? (int)$_GET['category'] : '';
$location = isset($_GET['location']) ? sanitize($_GET['location']) : '';
$employment_type = isset($_GET['employment_type']) ? $_GET['employment_type'] : '';
$experience_level = isset($_GET['experience_level']) ? $_GET['experience_level'] : '';
$salary_range = isset($_GET['salary_range']) ? $_GET['salary_range'] : '';
$industry = isset($_GET['industry']) ? $_GET['industry'] : '';
$benefit = isset($_GET['benefit']) ? $_GET['benefit'] : '';
$date_posted = isset($_GET['date_posted']) ? $_GET['date_posted'] : '';
$remote_work = isset($_GET['remote_work']) ? $_GET['remote_work'] : '';
$company_filter = isset($_GET['company']) ? (int)$_GET['company'] : 0;

// Get company information if filtering by company
$filtered_company = null;
if ($company_filter) {
    $stmt = $db->prepare("SELECT id, name, logo FROM companies WHERE id = ? AND status = 'approved'");
    $stmt->execute([$company_filter]);
    $filtered_company = $stmt->fetch();
    
    // If company doesn't exist or is not approved, redirect to all jobs
    if (!$filtered_company) {
        redirect('jobs.php');
    }
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$items_per_page = 12;
$offset = ($page - 1) * $items_per_page;

// Build search query with visibility filtering - exclude closed jobs and expired deadlines
$where_conditions = ["j.status = 'active'", "j.status != 'closed'", "c.status = 'approved'"];
$where_conditions[] = "(j.deadline IS NULL OR j.deadline >= CURDATE())"; // Only show jobs with no deadline or future deadlines
$params = [];

// Add job visibility filtering based on user type
if (isLoggedIn('company')) {
    // Company users (HR) can see all jobs from their company
    $where_conditions[] = "j.company_id = ?";
    $params[] = $_SESSION['company_id'];
} elseif (isLoggedIn('candidate')) {
    // Get candidate type
    $stmt = $db->prepare("SELECT candidate_type, company_id FROM candidates WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $candidate_data = $stmt->fetch();
    
    if ($candidate_data && $candidate_data['candidate_type'] === 'internal') {
        // Internal candidates can see:
        // 1. Internal and 'both' jobs from their company
        // 2. External and 'both' jobs from OTHER companies (not their own)
        // They CANNOT see external-only jobs from their own company
        $where_conditions[] = "(
            (j.job_visibility IN ('internal', 'both') AND j.company_id = ?) OR 
            (j.job_visibility IN ('external', 'both') AND j.company_id != ?)
        )";
        $params[] = $candidate_data['company_id'];
        $params[] = $candidate_data['company_id'];
    } else {
        // External candidates can only see external and 'both' jobs
        $where_conditions[] = "j.job_visibility IN ('external', 'both')";
    }
} else {
    // Non-logged in users can only see external and 'both' jobs
    $where_conditions[] = "j.job_visibility IN ('external', 'both')";
}

if ($keyword) {
    $where_conditions[] = "(j.title LIKE ? OR j.description LIKE ? OR j.requirements LIKE ?)";
    $params[] = "%$keyword%";
    $params[] = "%$keyword%";
    $params[] = "%$keyword%";
}

if ($category) {
    $where_conditions[] = "j.category_id = ?";
    $params[] = $category;
}

if ($location) {
    $where_conditions[] = "j.location LIKE ?";
    $params[] = "%$location%";
}

// Company filter - show only jobs from specific company if requested
if ($company_filter && $filtered_company) {
    $where_conditions[] = "j.company_id = ?";
    $params[] = $company_filter;
}

if ($employment_type) {
    $where_conditions[] = "j.employment_type = ?";
    $params[] = $employment_type;
}

if ($experience_level) {
    $where_conditions[] = "j.experience_level = ?";
    $params[] = $experience_level;
}

// Salary range filter
if ($salary_range) {
    switch ($salary_range) {
        case '0-30000':
            $where_conditions[] = "((j.salary_min BETWEEN 0 AND 30000) OR (j.salary_max BETWEEN 0 AND 30000))";
            break;
        case '30000-50000':
            $where_conditions[] = "((j.salary_min BETWEEN 30000 AND 50000) OR (j.salary_max BETWEEN 30000 AND 50000))";
            break;
        case '50000-80000':
            $where_conditions[] = "((j.salary_min BETWEEN 50000 AND 80000) OR (j.salary_max BETWEEN 50000 AND 80000))";
            break;
        case '80000+':
            $where_conditions[] = "(j.salary_min >= 80000 OR j.salary_max >= 80000)";
            break;
    }
}

// Date posted filter
if ($date_posted) {
    switch ($date_posted) {
        case 'today':
            $where_conditions[] = "j.created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)";
            break;
        case 'week':
            $where_conditions[] = "j.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
            break;
    }
}

// Remote work filter
if ($remote_work) {
    switch ($remote_work) {
        case 'partial':
            $where_conditions[] = "(j.description LIKE '%remote%' OR j.description LIKE '%hybrid%')";
            break;
        case 'full':
            $where_conditions[] = "j.description LIKE '%fully remote%'";
            break;
    }
}


// Industry filter - Using company name/description and job title patterns since industry column doesn't exist
if ($industry) {
    switch ($industry) {
        case 'technology':
            $where_conditions[] = "(c.name LIKE ? OR c.description LIKE ? OR j.title LIKE ? OR j.title LIKE ? OR j.title LIKE ?)";
            $params[] = '%tech%';
            $params[] = '%IT%';
            $params[] = '%developer%';
            $params[] = '%programmer%';
            $params[] = '%IT%';
            break;
        case 'finance':
            $where_conditions[] = "(c.name LIKE ? OR c.description LIKE ? OR j.title LIKE ? OR j.title LIKE ?)";
            $params[] = '%finance%';
            $params[] = '%bank%';
            $params[] = '%financial%';
            $params[] = '%accounting%';
            break;
        case 'healthcare':
            $where_conditions[] = "(c.name LIKE ? OR c.description LIKE ? OR j.title LIKE ? OR j.title LIKE ?)";
            $params[] = '%health%';
            $params[] = '%medical%';
            $params[] = '%nurse%';
            $params[] = '%doctor%';
            break;
        case 'education':
            $where_conditions[] = "(c.name LIKE ? OR c.description LIKE ? OR j.title LIKE ? OR j.title LIKE ?)";
            $params[] = '%education%';
            $params[] = '%training%';
            $params[] = '%teacher%';
            $params[] = '%instructor%';
            break;
        case 'retail':
            $where_conditions[] = "(c.name LIKE ? OR c.description LIKE ? OR j.title LIKE ? OR j.title LIKE ?)";
            $params[] = '%retail%';
            $params[] = '%sales%';
            $params[] = '%sales%';
            $params[] = '%retail%';
            break;
    }
}

// Benefits filter - Only search in description since benefits column doesn't exist
if ($benefit) {
    switch ($benefit) {
        case 'medical_aid':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%medical aid%';
            $params[] = '%Medical Aid%';
            break;
        case 'dental_cover':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%dental cover%';
            $params[] = '%Dental Cover%';
            break;
        case 'provident_fund':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%provident fund%';
            $params[] = '%Provident Fund%';
            break;
        case 'group_life_cover':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%group life cover%';
            $params[] = '%Group Life Cover%';
            break;
        case 'flexible_hours':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%flexible working hours%';
            $params[] = '%Flexible Working Hours%';
            break;
        case 'annual_bonus':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%annual bonus%';
            $params[] = '%13th cheque%';
            $params[] = '%Annual Bonus%';
            break;
        case 'training_development':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%training & development%';
            $params[] = '%Training & Development%';
            break;
        case 'transport_allowance':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%transport allowance%';
            $params[] = '%travel allowance%';
            $params[] = '%Transport / Travel Allowance%';
            break;
        case 'cellphone_allowance':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%cellphone allowance%';
            $params[] = '%Cellphone Allowance%';
            break;
        case 'study_assistance':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%study assistance%';
            $params[] = '%Study Assistance%';
            break;
        case 'wellness_program':
            $where_conditions[] = "(j.description LIKE ? OR j.description LIKE ?)";
            $params[] = '%wellness program%';
            $params[] = '%Wellness Program%';
            break;
    }
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

// Count total jobs
$count_query = "
    SELECT COUNT(*) as total 
    FROM jobs j 
    JOIN companies c ON j.company_id = c.id 
    $where_clause
";
$stmt = $db->prepare($count_query);
$stmt->execute($params);
$total_jobs = $stmt->fetch()['total'];
$total_pages = ceil($total_jobs / $items_per_page);

// Get jobs with pagination
$query = "
    SELECT j.*, c.name as company_name, c.logo as company_logo,
           cat.name as category_name,
           DATEDIFF(j.deadline, NOW()) as days_until_deadline,
           DATEDIFF(NOW(), j.created_at) as days_ago
    FROM jobs j 
    JOIN companies c ON j.company_id = c.id 
    LEFT JOIN job_categories cat ON j.category_id = cat.id 
    $where_clause
    ORDER BY j.created_at DESC 
    LIMIT $items_per_page OFFSET $offset
";

$stmt = $db->prepare($query);
$stmt->execute($params);
$jobs = $stmt->fetchAll();

// Get job categories for filter
$stmt = $db->prepare("SELECT * FROM job_categories ORDER BY name");
$stmt->execute();
$categories = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $filtered_company ? 'Jobs at ' . htmlspecialchars($filtered_company['name']) . ' - ' . SITE_NAME : 'Browse Jobs - ' . SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        /* Job Browser Layout - Similar to image but with portal colors */
        .jobs-layout {
            display: grid;
            grid-template-columns: 300px 1fr;
            gap: 2rem;
            margin-top: 2rem;
        }
        
        @media (max-width: 768px) {
            .jobs-layout {
                grid-template-columns: 1fr;
                gap: 1rem;
            }
        }
        
        /* Filter Sidebar */
        .filter-sidebar {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            height: fit-content;
            border: 1px solid #e9ecef;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        }
        
        .filter-section {
            margin-bottom: 2rem;
        }
        
        .filter-section h6 {
            font-weight: 600;
            margin-bottom: 1rem;
            color: #2d3748;
            font-size: 0.95rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .filter-option {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.5rem 0;
            font-size: 0.9rem;
            color: #4a5568;
            cursor: pointer;
            border-radius: 6px;
            transition: all 0.2s;
        }
        
        .filter-option:hover {
            background: #f7fafc;
            color: #FFA500;
        }
        
        .filter-count {
            background: #e2e8f0;
            color: #718096;
            padding: 0.2rem 0.5rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        /* Results Header */
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e9ecef;
        }
        
        .results-count {
            color: #4a5568;
            font-size: 0.95rem;
        }
        
        .results-count strong {
            color: #FFA500;
            font-weight: 600;
        }
        
        .sort-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.5rem 1rem;
            font-size: 0.9rem;
            background: white;
        }
        
        /* Job Cards - Modern List Style */
        .job-card {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
            position: relative;
            text-decoration: none;
            color: inherit;
            display: block;
        }
        
        .job-card:hover {
            border-color: #FFA500;
            box-shadow: 0 4px 12px rgba(255, 165, 0, 0.1);
            transform: translateY(-2px);
            text-decoration: none;
            color: inherit;
        }
        
        .job-header {
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .company-logo {
            width: 60px;
            height: 60px;
            object-fit: contain;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            background: white;
            padding: 6px;
            flex-shrink: 0;
        }
        
        .company-logo-placeholder {
            width: 60px;
            height: 60px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            flex-shrink: 0;
        }
        
        .job-info {
            flex-grow: 1;
            min-width: 0;
        }
        
        .job-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #2d3748;
            margin: 0 0 0.25rem 0;
            line-height: 1.4;
        }
        
        .job-card:hover .job-title {
            color: #FFA500;
        }
        
        .company-name {
            color: #718096;
            font-size: 0.95rem;
            margin: 0 0 0.5rem 0;
        }
        
        .job-location {
            color: #a0aec0;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .job-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 0.75rem;
            margin-bottom: 1rem;
        }
        
        .job-badge {
            background: #f7fafc;
            color: #4a5568;
            border: 1px solid #e2e8f0;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.8rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .job-badge.remote {
            background: #fed7d7;
            color: #c53030;
            border-color: #feb2b2;
        }
        
        .job-badge.market-related {
            background: #c6f6d5;
            color: #22543d;
            border-color: #9ae6b4;
        }
        
        .job-badge.internal {
            background: #fed7d7;
            color: #c53030;
            border-color: #feb2b2;
        }
        
        .job-badge.external {
            background: #c6f6d5;
            color: #22543d;
            border-color: #9ae6b4;
        }
        
        .job-badge.both {
            background: #faf089;
            color: #744210;
            border-color: #ecc94b;
        }
        
        .job-posted {
            color: #a0aec0;
            font-size: 0.85rem;
            position: absolute;
            top: 1.5rem;
            right: 1.5rem;
        }
        
        .job-description {
            color: #4a5568;
            font-size: 0.9rem;
            line-height: 1.5;
            margin-bottom: 1rem;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        
        /* Search Bar Enhancement */
        .search-bar {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 1rem;
            margin-bottom: 2rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        }
        
        .search-input {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem 1rem;
            font-size: 0.95rem;
            width: 100%;
        }
        
        .search-input:focus {
            border-color: #FFA500;
            box-shadow: 0 0 0 3px rgba(255, 165, 0, 0.1);
            outline: none;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="jobs.php">Browse Jobs</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="companies.php">Companies</a>
                    </li>
                </ul>
                
                <ul class="navbar-nav">
                    <?php if (isLoggedIn()): ?>
                        <?php if ($_SESSION['user_type'] === 'admin'): ?>
                            <li class="nav-item">
                                <a class="nav-link" href="admin/dashboard.php">Admin Dashboard</a>
                            </li>
                        <?php elseif ($_SESSION['user_type'] === 'company'): ?>
                            <li class="nav-item">
                                <a class="nav-link" href="company/dashboard.php">Company Dashboard</a>
                            </li>
                        <?php elseif ($_SESSION['user_type'] === 'candidate'): ?>
                            <li class="nav-item">
                                <a class="nav-link" href="candidate/dashboard.php">My Profile</a>
                            </li>
                        <?php endif; ?>
                        <li class="nav-item">
                            <a class="nav-link" href="auth/logout.php">Logout</a>
                        </li>
                    <?php else: ?>
                        <li class="nav-item">
                            <a class="nav-link" href="auth/login.php">Login</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="auth/register.php">Register</a>
                        </li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container py-4">
        <!-- Page Header -->
        <div class="row mb-4">
            <div class="col-md-8">
                <?php if ($filtered_company): ?>
                    <h1 class="h2 mb-2">
                        <i class="fas fa-building me-2 text-primary"></i>Jobs at <?php echo htmlspecialchars($filtered_company['name']); ?>
                    </h1>
                    <p class="text-muted">All available positions from this company</p>
                <?php elseif (isLoggedIn('company')): ?>
                    <h1 class="h2 mb-2">
                        <i class="fas fa-users-cog me-2 text-primary"></i>HR Job Browser
                    </h1>
                    <p class="text-muted">
                        Viewing all company jobs 
                        <span class="badge bg-primary"><?php echo htmlspecialchars($_SESSION['company_name']); ?></span>
                    </p>
                <?php else: ?>
                    <h1 class="h2 mb-2">Browse Jobs</h1>
                    <p class="text-muted">Discover your next career opportunity</p>
                <?php endif; ?>
            </div>
            <div class="col-md-4 text-md-end">
                <?php if (isLoggedIn('company')): ?>
                    <a href="company/jobs.php" class="btn btn-primary me-2">
                        <i class="fas fa-cog me-1"></i>Manage Jobs
                    </a>
                    <a href="company/post-job.php" class="btn btn-outline-primary">
                        <i class="fas fa-plus me-1"></i>Post New Job
                    </a>
                <?php elseif (isLoggedIn('candidate')): ?>
                    <a href="candidate/cv-builder.php" class="btn btn-outline-primary">
                        <i class="fas fa-file-alt me-1"></i>Build Your CV
                    </a>
                <?php endif; ?>
            </div>
        </div>

        <!-- Main Search Bar -->
        <div class="search-bar">
            <form method="GET" class="d-flex gap-3 align-items-end">
                <div class="flex-grow-1">
                    <input type="text" class="search-input" name="keyword" 
                           value="<?php echo htmlspecialchars($keyword); ?>" 
                           placeholder="Search job titles, companies, or keywords...">
                </div>
                <div>
                    <input type="text" class="search-input" name="location" 
                           value="<?php echo htmlspecialchars($location); ?>" 
                           placeholder="Location" style="width: 200px;">
                </div>
                <div>
                    <button type="submit" class="btn btn-primary px-4">
                        <i class="fas fa-search me-2"></i>Search
                    </button>
                </div>
            </form>
        </div>

        <!-- Jobs Layout - Sidebar + Results -->
        <div class="jobs-layout">
            <!-- Filter Sidebar -->
            <div class="filter-sidebar">
                <form method="GET" id="filterForm">
                    <!-- Preserve search terms and active filters -->
                    <input type="hidden" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>">
                    <input type="hidden" name="location" value="<?php echo htmlspecialchars($location); ?>">
                    <?php if ($company_filter): ?><input type="hidden" name="company" value="<?php echo $company_filter; ?>"><?php endif; ?>
                    <?php if ($employment_type): ?><input type="hidden" name="employment_type" value="<?php echo htmlspecialchars($employment_type); ?>"><?php endif; ?>
                    <?php if ($experience_level): ?><input type="hidden" name="experience_level" value="<?php echo htmlspecialchars($experience_level); ?>"><?php endif; ?>
                    <?php if ($salary_range): ?><input type="hidden" name="salary_range" value="<?php echo htmlspecialchars($salary_range); ?>"><?php endif; ?>
                    <?php if ($industry): ?><input type="hidden" name="industry" value="<?php echo htmlspecialchars($industry); ?>"><?php endif; ?>
                    <?php if ($benefit): ?><input type="hidden" name="benefit" value="<?php echo htmlspecialchars($benefit); ?>"><?php endif; ?>
                    <?php if ($date_posted): ?><input type="hidden" name="date_posted" value="<?php echo htmlspecialchars($date_posted); ?>"><?php endif; ?>
                    <?php if ($remote_work): ?><input type="hidden" name="remote_work" value="<?php echo htmlspecialchars($remote_work); ?>"><?php endif; ?>
                    
                    <!-- Date Posted Filter -->
                    <div class="filter-section">
                        <h6>Date Posted</h6>
                        <?php 
                        // New jobs (today)
                        $stmt = $db->query("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY) AND j.status = 'active' AND c.status = 'approved'");
                        $new_jobs_count = $stmt->fetch()['count'];
                        if ($new_jobs_count > 0): ?>
                        <div class="filter-option" onclick="filterByDatePosted('today')">
                            <span>New jobs</span>
                            <span class="filter-count"><?php echo $new_jobs_count; ?></span>
                        </div>
                        <?php endif; ?>
                        
                        <?php 
                        // Jobs from last week
                        $stmt = $db->query("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) AND j.status = 'active' AND c.status = 'approved'");
                        $week_jobs_count = $stmt->fetch()['count'];
                        if ($week_jobs_count > 0): ?>
                        <div class="filter-option" onclick="filterByDatePosted('week')">
                            <span>Last week</span>
                            <span class="filter-count"><?php echo $week_jobs_count; ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Work From Home -->
                    <?php 
                    // Check if there are any remote jobs at all
                    $stmt = $db->query("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%remote%' OR j.description LIKE '%hybrid%' OR j.description LIKE '%fully remote%') AND j.status = 'active' AND c.status = 'approved'");
                    $total_remote_count = $stmt->fetch()['count'];
                    if ($total_remote_count > 0): ?>
                    <div class="filter-section">
                        <h6>Work from home options</h6>
                        <?php 
                        // Partially remote
                        $stmt = $db->query("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%remote%' OR j.description LIKE '%hybrid%') AND j.status = 'active' AND c.status = 'approved'");
                        $partial_remote_count = $stmt->fetch()['count'];
                        if ($partial_remote_count > 0): ?>
                        <div class="filter-option" onclick="filterByRemoteWork('partial')">
                            <span>Partially remote</span>
                            <span class="filter-count"><?php echo $partial_remote_count; ?></span>
                        </div>
                        <?php endif; ?>
                        
                        <?php 
                        // Fully remote
                        $stmt = $db->query("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.description LIKE '%fully remote%' AND j.status = 'active' AND c.status = 'approved'");
                        $full_remote_count = $stmt->fetch()['count'];
                        if ($full_remote_count > 0): ?>
                        <div class="filter-option" onclick="filterByRemoteWork('full')">
                            <span>Fully remote</span>
                            <span class="filter-count"><?php echo $full_remote_count; ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Application Method - Removed as it uses fake data without database backing -->
                    
                    <!-- Functions/Categories -->
                    <?php 
                    // Check if there are any categories with jobs
                    $stmt = $db->query("SELECT COUNT(DISTINCT j.category_id) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.category_id IS NOT NULL AND j.status = 'active' AND c.status = 'approved'");
                    $categories_with_jobs = $stmt->fetch()['count'];
                    if ($categories_with_jobs > 0): ?>
                    <div class="filter-section">
                        <h6>Functions</h6>
                        <?php foreach ($categories as $cat): 
                            $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.category_id = ? AND j.status = 'active' AND c.status = 'approved'");
                            $stmt->execute([$cat['id']]);
                            $cat_count = $stmt->fetch()['count'];
                            if ($cat_count > 0): ?>
                        <div class="filter-option" onclick="filterByCategory(<?php echo $cat['id']; ?>)">
                            <span><?php echo htmlspecialchars($cat['name']); ?></span>
                            <span class="filter-count"><?php echo $cat_count; ?></span>
                        </div>
                        <?php endif; endforeach; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Employment Type -->
                    <?php 
                    // Check if there are any employment types with jobs
                    $employment_types = ['full-time', 'part-time', 'contract', 'internship'];
                    $employment_type_labels = ['Full-time', 'Part-time', 'Contract', 'Internship'];
                    $has_employment_types = false;
                    $employment_counts = [];
                    
                    foreach ($employment_types as $type) {
                        $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.employment_type = ? AND j.status = 'active' AND c.status = 'approved'");
                        $stmt->execute([$type]);
                        $count = $stmt->fetch()['count'];
                        $employment_counts[$type] = $count;
                        if ($count > 0) $has_employment_types = true;
                    }
                    
                    if ($has_employment_types): ?>
                    <div class="filter-section">
                        <h6>Employment Type</h6>
                        <?php foreach ($employment_types as $i => $type): 
                            if ($employment_counts[$type] > 0): ?>
                        <div class="filter-option" onclick="filterByType('<?php echo $type; ?>')">
                            <span><?php echo $employment_type_labels[$i]; ?></span>
                            <span class="filter-count"><?php echo $employment_counts[$type]; ?></span>
                        </div>
                        <?php endif; endforeach; ?>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Experience Level -->
                    <div class="filter-section">
                        <h6>Experience Level</h6>
                        <div class="filter-option" onclick="filterByExperience('entry')">
                            <span>Entry Level (0-2 years)</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.experience_level = 'entry' AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByExperience('mid')">
                            <span>Mid Level (3-5 years)</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.experience_level = 'mid' AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByExperience('senior')">
                            <span>Senior Level (5+ years)</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.experience_level = 'senior' AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByExperience('executive')">
                            <span>Executive Level</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.experience_level = 'executive' AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Salary Range -->
                    <div class="filter-section">
                        <h6>Salary Range</h6>
                        <div class="filter-option" onclick="filterBySalary('0-30000')">
                            <span>R0 - R30,000</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE ((j.salary_min BETWEEN 0 AND 30000) OR (j.salary_max BETWEEN 0 AND 30000)) AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterBySalary('30000-50000')">
                            <span>R30,000 - R50,000</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE ((j.salary_min BETWEEN 30000 AND 50000) OR (j.salary_max BETWEEN 30000 AND 50000)) AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterBySalary('50000-80000')">
                            <span>R50,000 - R80,000</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE ((j.salary_min BETWEEN 50000 AND 80000) OR (j.salary_max BETWEEN 50000 AND 80000)) AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterBySalary('80000+')">
                            <span>R80,000+</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.salary_min >= 80000 OR j.salary_max >= 80000) AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                echo $stmt->fetch()['count'];
                                ?>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Location/City -->
                    <div class="filter-section">
                        <h6>Popular Locations</h6>
                        <?php
                        // Get top cities with job counts
                        $location_stmt = $db->query("
                            SELECT 
                                TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(j.location, ',', 1), ',', -1)) as city,
                                COUNT(*) as count 
                            FROM jobs j 
                            JOIN companies c ON j.company_id = c.id 
                            WHERE j.status = 'active' AND c.status = 'approved' 
                            GROUP BY city 
                            HAVING city != '' AND city IS NOT NULL
                            ORDER BY count DESC 
                            LIMIT 6
                        ");
                        $locations = $location_stmt->fetchAll();
                        foreach ($locations as $loc): ?>
                            <div class="filter-option" onclick="filterByLocation('<?php echo addslashes($loc['city']); ?>')">
                                <span><?php echo htmlspecialchars($loc['city']); ?></span>
                                <span class="filter-count"><?php echo $loc['count']; ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Industry/Sector -->
                    <div class="filter-section">
                        <h6>Industry Sector</h6>
                        <div class="filter-option" onclick="filterByIndustry('technology')">
                            <span>Technology & IT</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (c.name LIKE '%tech%' OR c.name LIKE '%IT%' OR c.description LIKE '%tech%' OR c.description LIKE '%IT%' OR j.title LIKE '%developer%' OR j.title LIKE '%programmer%' OR j.title LIKE '%IT%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByIndustry('finance')">
                            <span>Finance & Banking</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (c.name LIKE '%finance%' OR c.name LIKE '%bank%' OR c.description LIKE '%finance%' OR c.description LIKE '%bank%' OR j.title LIKE '%financial%' OR j.title LIKE '%accounting%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByIndustry('healthcare')">
                            <span>Healthcare & Medical</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (c.name LIKE '%health%' OR c.name LIKE '%medical%' OR c.description LIKE '%health%' OR c.description LIKE '%medical%' OR j.title LIKE '%nurse%' OR j.title LIKE '%doctor%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByIndustry('education')">
                            <span>Education & Training</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (c.name LIKE '%education%' OR c.name LIKE '%training%' OR c.description LIKE '%education%' OR c.description LIKE '%training%' OR j.title LIKE '%teacher%' OR j.title LIKE '%instructor%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByIndustry('retail')">
                            <span>Retail & Sales</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (c.name LIKE '%retail%' OR c.name LIKE '%sales%' OR c.description LIKE '%retail%' OR c.description LIKE '%sales%' OR j.title LIKE '%sales%' OR j.title LIKE '%retail%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; echo $count;
                                ?>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Job Benefits -->
                    <div class="filter-section">
                        <h6>Job Benefits</h6>
                        <div class="filter-option" onclick="filterByBenefit('medical_aid')">
                            <span><i class="fas fa-heartbeat text-danger me-1"></i>Medical Aid</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%medical aid%' OR j.description LIKE '%Medical Aid%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; 
                                if ($count > 0) echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByBenefit('provident_fund')">
                            <span><i class="fas fa-piggy-bank text-success me-1"></i>Provident Fund</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%provident fund%' OR j.description LIKE '%Provident Fund%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; 
                                if ($count > 0) echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByBenefit('flexible_hours')">
                            <span><i class="fas fa-clock text-warning me-1"></i>Flexible Hours</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%flexible working hours%' OR j.description LIKE '%Flexible Working Hours%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; 
                                if ($count > 0) echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByBenefit('annual_bonus')">
                            <span><i class="fas fa-gift text-success me-1"></i>Annual Bonus</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%annual bonus%' OR j.description LIKE '%13th cheque%' OR j.description LIKE '%Annual Bonus%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; 
                                if ($count > 0) echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByBenefit('training_development')">
                            <span><i class="fas fa-graduation-cap text-info me-1"></i>Training & Development</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%training & development%' OR j.description LIKE '%Training & Development%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; 
                                if ($count > 0) echo $count;
                                ?>
                            </span>
                        </div>
                        <div class="filter-option" onclick="filterByBenefit('transport_allowance')">
                            <span><i class="fas fa-car text-primary me-1"></i>Transport Allowance</span>
                            <span class="filter-count">
                                <?php 
                                $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j JOIN companies c ON j.company_id = c.id WHERE (j.description LIKE '%transport allowance%' OR j.description LIKE '%travel allowance%' OR j.description LIKE '%Transport / Travel Allowance%') AND j.status = 'active' AND c.status = 'approved'");
                                $stmt->execute();
                                $count = $stmt->fetch()['count']; 
                                if ($count > 0) echo $count;
                                ?>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Clear Filters -->
                    <div class="filter-section">
                        <button type="button" class="btn btn-outline-secondary w-100" onclick="clearAllFilters()">
                            <i class="fas fa-times me-2"></i>Clear All Filters
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Results Area -->
            <div class="results-area">
                <!-- Results Header -->
                <div class="results-header">
                    <div class="results-count">
                        <strong><?php echo $total_jobs; ?></strong> job<?php echo $total_jobs != 1 ? 's' : ''; ?> found
                        <?php if ($keyword): ?>
                            for <strong><?php echo htmlspecialchars($keyword); ?></strong>
                        <?php endif; ?>
                        <?php if ($location): ?>
                            in <strong><?php echo htmlspecialchars($location); ?></strong>
                        <?php endif; ?>
                        <?php if ($filtered_company): ?>
                            at <strong><?php echo htmlspecialchars($filtered_company['name']); ?></strong>
                        <?php elseif (isLoggedIn('company')): ?>
                            <span class="badge bg-primary ms-2"><?php echo htmlspecialchars($_SESSION['company_name']); ?></span>
                        <?php endif; ?>
                    </div>
                    <div>
                        <select class="sort-select" onchange="sortResults(this.value)">
                            <option value="relevance">Relevance</option>
                            <option value="date">Date posted</option>
                            <option value="salary">Salary</option>
                            <option value="company">Company</option>
                        </select>
                    </div>
                </div>
                
                <!-- Active Filters -->
                <?php 
                $activeFilters = [];
                if ($keyword) $activeFilters['keyword'] = $keyword;
                if ($location) $activeFilters['location'] = $location;
                if ($filtered_company) $activeFilters['company'] = $filtered_company['name'];
                if ($category) {
                    $stmt = $db->prepare("SELECT name FROM job_categories WHERE id = ?");
                    $stmt->execute([$category]);
                    $catName = $stmt->fetch();
                    if ($catName) $activeFilters['category'] = $catName['name'];
                }
                if ($employment_type) $activeFilters['employment_type'] = ucfirst(str_replace('-', ' ', $employment_type));
                if ($experience_level) $activeFilters['experience_level'] = ucfirst($experience_level) . ' Level';
                if ($salary_range) $activeFilters['salary_range'] = 'Salary: R' . str_replace('-', ' - R', $salary_range);
                if ($date_posted) {
                    $dateLabels = ['today' => 'Posted Today', 'week' => 'Posted This Week'];
                    $activeFilters['date_posted'] = $dateLabels[$date_posted] ?? 'Date Posted';
                }
                if ($remote_work) {
                    $remoteLabels = ['partial' => 'Partially Remote', 'full' => 'Fully Remote'];
                    $activeFilters['remote_work'] = $remoteLabels[$remote_work] ?? 'Remote Work';
                }
                if ($industry) $activeFilters['industry'] = ucfirst($industry) . ' Industry';
                if ($benefit) $activeFilters['benefit'] = ucfirst(str_replace('_', ' ', $benefit));
                ?>
                
                <?php if (!empty($activeFilters)): ?>
                <div class="active-filters mb-3">
                    <div class="d-flex flex-wrap align-items-center gap-2">
                        <span class="text-muted small">Active filters:</span>
                        <?php foreach ($activeFilters as $param => $label): ?>
                        <span class="badge bg-primary d-flex align-items-center gap-1">
                            <?php echo htmlspecialchars($label); ?>
                            <button type="button" class="btn-close btn-close-white" 
                                    onclick="removeFilter('<?php echo $param; ?>')" 
                                    style="font-size: 0.6rem;"
                                    aria-label="Remove filter"></button>
                        </span>
                        <?php endforeach; ?>
                        <button class="btn btn-sm btn-outline-secondary" onclick="clearAllFilters()">
                            Clear All
                        </button>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Job Cards -->
                <?php if (empty($jobs)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-search fa-4x text-muted mb-3"></i>
                        <h3>No jobs found</h3>
                        <p class="text-muted">Try adjusting your search criteria or browse all jobs.</p>
                        <a href="jobs.php" class="btn btn-primary">View All Jobs</a>
                    </div>
                <?php else: ?>
                    <?php foreach ($jobs as $job): ?>
                        <a href="job-details.php?id=<?php echo $job['id']; ?>" class="job-card">
                            <div class="job-posted">
                                <?php 
                                if ($job['days_ago'] == 0) {
                                    echo "Today";
                                } elseif ($job['days_ago'] == 1) {
                                    echo "1 day ago";
                                } else {
                                    echo $job['days_ago'] . " days ago";
                                }
                                ?>
                            </div>
                            
                            <div class="job-header">
                                <!-- Company Logo -->
                                <div>
                                    <?php if ($job['company_logo']): ?>
                                        <img src="<?php echo UPLOAD_URL . 'logos/' . $job['company_logo']; ?>" 
                                             alt="<?php echo htmlspecialchars($job['company_name']); ?>" 
                                             class="company-logo">
                                    <?php else: ?>
                                        <div class="company-logo-placeholder">
                                            <i class="fas fa-building"></i>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Job Info -->
                                <div class="job-info">
                                    <h3 class="job-title"><?php echo htmlspecialchars($job['title']); ?></h3>
                                    <div class="company-name"><?php echo htmlspecialchars($job['company_name']); ?></div>
                                    <div class="job-location">
                                        <i class="fas fa-map-marker-alt"></i>
                                        <?php echo htmlspecialchars($job['location']); ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Job Description Preview -->
                            <div class="job-description">
                                <?php 
                                $description = strip_tags($job['description']);
                                echo htmlspecialchars(substr($description, 0, 150) . '...');
                                ?>
                            </div>
                            
                            <!-- Job Meta -->
                            <div class="job-meta">
                                <span class="job-badge">
                                    <i class="fas fa-briefcase"></i>
                                    <?php echo htmlspecialchars($job['category_name'] ?: 'General'); ?>
                                </span>
                                <span class="job-badge">
                                    <i class="fas fa-clock"></i>
                                    <?php echo ucfirst(str_replace('-', ' ', $job['employment_type'])); ?>
                                </span>
                                <span class="job-badge">
                                    <i class="fas fa-layer-group"></i>
                                    <?php echo ucfirst($job['experience_level']); ?> Level
                                </span>
                                
                                <?php if (strpos(strtolower($job['description']), 'remote') !== false): ?>
                                    <span class="job-badge remote">
                                        <i class="fas fa-home"></i>
                                        Partially remote
                                    </span>
                                <?php endif; ?>
                                
                                <?php if ($job['salary_min'] || $job['salary_max']): ?>
                                    <span class="job-badge market-related">
                                        <i class="fas fa-coins"></i>
                                        Market Related
                                    </span>
                                <?php endif; ?>
                                
                                <!-- Job Visibility Badge -->
                                <?php 
                                $visibility = $job['job_visibility'] ?? 'external'; // Default to external if not set
                                $visibility_class = strtolower($visibility);
                                $visibility_icon = '';
                                $visibility_text = '';
                                
                                switch($visibility) {
                                    case 'internal':
                                        $visibility_icon = 'fas fa-building';
                                        $visibility_text = 'Internal Only';
                                        break;
                                    case 'external':
                                        $visibility_icon = 'fas fa-globe';
                                        $visibility_text = 'External Only';
                                        break;
                                    case 'both':
                                        $visibility_icon = 'fas fa-users';
                                        $visibility_text = 'Internal & External';
                                        break;
                                    default:
                                        $visibility_icon = 'fas fa-globe';
                                        $visibility_text = 'External Only';
                                }
                                ?>
                                <span class="job-badge <?php echo $visibility_class; ?>">
                                    <i class="<?php echo $visibility_icon; ?>"></i>
                                    <?php echo $visibility_text; ?>
                                </span>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
                
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <nav aria-label="Job search pagination" class="mt-4">
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">Previous</a>
                                </li>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">Next</a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-lg-6">
                    <h5><?php echo SITE_NAME; ?></h5>
                    <p class="text-muted">Connecting talented individuals with amazing opportunities.</p>
                </div>
                <div class="col-lg-6">
                    <div class="text-lg-end">
                        <p>&copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. All rights reserved.</p>
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function applyFilter(paramName, value) {
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set(paramName, value);
            currentUrl.searchParams.delete('page'); // Reset to first page when filtering
            window.location.href = currentUrl.toString();
        }
        
        function filterByCategory(categoryId) {
            applyFilter('category', categoryId);
        }
        
        function filterByType(employmentType) {
            applyFilter('employment_type', employmentType);
        }
        
        function filterByDatePosted(dateRange) {
            applyFilter('date_posted', dateRange);
        }
        
        function filterByRemoteWork(remoteType) {
            applyFilter('remote_work', remoteType);
        }
        
        function filterByExperience(experienceLevel) {
            applyFilter('experience_level', experienceLevel);
        }
        
        function filterBySalary(salaryRange) {
            applyFilter('salary_range', salaryRange);
        }
        
        function filterByLocation(city) {
            applyFilter('location', city);
        }
        
        function filterByIndustry(industry) {
            applyFilter('industry', industry);
        }
        
        function filterByBenefit(benefit) {
            applyFilter('benefit', benefit);
        }
        
        function clearAllFilters() {
            // Redirect to clean URL with no filters
            window.location.href = window.location.pathname;
        }
        
        function removeFilter(paramName) {
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.delete(paramName);
            window.location.href = currentUrl.toString();
        }
        
        function sortResults(sortBy) {
            const urlParams = new URLSearchParams(window.location.search);
            urlParams.set('sort', sortBy);
            window.location.search = urlParams;
        }
        
        // Show active filters
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            
            // Highlight active filters
            const filterOptions = document.querySelectorAll('.filter-option');
            filterOptions.forEach(option => {
                const filterType = option.onclick ? option.onclick.toString().match(/filter\w+\('([^']+)'\)/)?.[1] : null;
                if (filterType && urlParams.get(getParamName(option.onclick.toString())) === filterType) {
                    option.style.backgroundColor = '#fff3cd';
                    option.style.color = '#856404';
                    option.style.fontWeight = 'bold';
                }
            });
        });
        
        function getParamName(onclickStr) {
            if (onclickStr.includes('filterByCategory')) return 'category';
            if (onclickStr.includes('filterByType')) return 'employment_type';
            if (onclickStr.includes('filterByExperience')) return 'experience_level';
            if (onclickStr.includes('filterBySalary')) return 'salary_range';
            if (onclickStr.includes('filterByLocation')) return 'location';
            if (onclickStr.includes('filterByIndustry')) return 'industry';
            if (onclickStr.includes('filterByBenefit')) return 'benefit';
            return '';
        }
    </script>
</body>
</html>