<?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'] : '';
$work_location_type = isset($_GET['work_location_type']) ? $_GET['work_location_type'] : '';
$company_filter = isset($_GET['company']) ? (int)$_GET['company'] : '';
$benefits_filter = isset($_GET['benefits']) ? (array)$_GET['benefits'] : [];

// Sidebar filter parameters
$date_posted = isset($_GET['date_posted']) ? (int)$_GET['date_posted'] : '';
$remote_work_filter = isset($_GET['remote_work']) ? (array)$_GET['remote_work'] : [];
$sidebar_categories = isset($_GET['sidebar_categories']) ? (array)$_GET['sidebar_categories'] : [];
$emp_types_filter = isset($_GET['emp_types']) ? (array)$_GET['emp_types'] : [];

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

// Build search query
$where_conditions = ["j.status = 'active'", "c.status = 'approved'"];
$params = [];

// Add job type filtering based on candidate type and login status
$user_candidate_type = null;
$user_company_id = null;

if (isLoggedIn('candidate')) {
    // Get candidate's type, company_id, and employment status
    $stmt = $db->prepare("SELECT candidate_type, company_id, employment_status, approval_status FROM candidates WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $candidate_info = $stmt->fetch();
    
    if ($candidate_info) {
        $user_candidate_type = $candidate_info['candidate_type'];
        $user_company_id = $candidate_info['company_id'];
        $employment_status = $candidate_info['employment_status'];
        $approval_status = $candidate_info['approval_status'];
        
        if ($user_candidate_type === 'internal') {
            // Internal candidates can only see jobs if they are active employees and approved
            if ($employment_status === 'active' && $approval_status === 'approved') {
                // Active internal candidates can see jobs that are 'internal' or 'both' from their company
                $where_conditions[] = "(j.job_type IN ('internal', 'both') AND j.company_id = ?)";
                $params[] = $user_company_id;
            } else {
                // Inactive/terminated/unapproved internal candidates cannot see any internal jobs
                $where_conditions[] = "j.job_type = 'external'"; // Only external jobs (if any)
            }
        } else {
            // External candidates can only see jobs that are 'external' or 'both'
            $where_conditions[] = "j.job_type IN ('external', 'both')";
        }
    }
} else {
    // Non-logged in users can only see external and both jobs
    $where_conditions[] = "j.job_type 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%";
}

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

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

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

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

// Sidebar filter conditions
if ($date_posted) {
    $where_conditions[] = "j.created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)";
    $params[] = $date_posted;
}

if (!empty($remote_work_filter)) {
    $remote_placeholders = str_repeat('?,', count($remote_work_filter) - 1) . '?';
    $where_conditions[] = "j.work_location_type IN ($remote_placeholders)";
    $params = array_merge($params, $remote_work_filter);
}

if (!empty($sidebar_categories)) {
    $cat_placeholders = str_repeat('?,', count($sidebar_categories) - 1) . '?';
    $where_conditions[] = "j.category_id IN ($cat_placeholders)";
    $params = array_merge($params, array_map('intval', $sidebar_categories));
}

if (!empty($emp_types_filter)) {
    $emp_placeholders = str_repeat('?,', count($emp_types_filter) - 1) . '?';
    $where_conditions[] = "j.employment_type IN ($emp_placeholders)";
    $params = array_merge($params, $emp_types_filter);
}

if (!empty($benefits_filter)) {
    $benefit_placeholders = str_repeat('?,', count($benefits_filter) - 1) . '?';
    $where_conditions[] = "j.id IN (
        SELECT DISTINCT jbs.job_id 
        FROM job_benefit_selections jbs 
        WHERE jbs.benefit_id IN ($benefit_placeholders)
        GROUP BY jbs.job_id 
        HAVING COUNT(DISTINCT jbs.benefit_id) = " . count($benefits_filter) . "
    )";
    $params = array_merge($params, array_map('intval', $benefits_filter));
}

$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,
           GROUP_CONCAT(CONCAT(jb.icon, '|', jb.name) SEPARATOR '###') as benefits
    FROM jobs j 
    JOIN companies c ON j.company_id = c.id 
    LEFT JOIN job_categories cat ON j.category_id = cat.id 
    LEFT JOIN job_benefit_selections jbs ON j.id = jbs.job_id
    LEFT JOIN job_benefits jb ON jbs.benefit_id = jb.id AND jb.is_active = 1
    $where_clause
    GROUP BY j.id, c.name, c.logo, cat.name
    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();

// Get available benefits for filtering  
$stmt = $db->prepare("SELECT * FROM job_benefits WHERE is_active = 1 ORDER BY display_order, name LIMIT 10");
$stmt->execute();
$filter_benefits = $stmt->fetchAll();

// Get company name if filtering by company
$company_name = '';
if ($company_filter) {
    $stmt = $db->prepare("SELECT name FROM companies WHERE id = ? AND status = 'approved'");
    $stmt->execute([$company_filter]);
    $company_info = $stmt->fetch();
    if ($company_info) {
        $company_name = $company_info['name'];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Browse Jobs - <?php echo SITE_NAME; ?></title>
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="assets/images/favicon.ico">
    <link rel="apple-touch-icon" sizes="180x180" href="assets/images/favicon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="assets/images/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="assets/images/favicon-16x16.png">
    <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-card-modern {
            transition: transform 0.2s ease-in-out;
        }
        
        .job-card-modern:hover {
            transform: translateY(-2px);
        }
        
        .job-item {
            border-radius: 8px !important;
            border: 1px solid #e3e6f0 !important;
            transition: all 0.3s ease;
        }
        
        .job-item:hover {
            border-color: #4285f4 !important;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
        }
        
        .job-title {
            font-size: 1.25rem;
            line-height: 1.4;
            margin-bottom: 0.5rem;
        }
        
        .job-title a {
            color: #4285f4 !important;
            text-decoration: none;
        }
        
        .job-title a:hover {
            color: #1a73e8 !important;
            text-decoration: underline;
        }
        
        .company-logo-small {
            width: 20px;
            height: 20px;
            object-fit: contain;
            border-radius: 2px;
        }
        
        .company-logo-small-placeholder {
            width: 20px;
            height: 20px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 2px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            color: #6c757d;
        }
        
        .job-description-preview {
            font-size: 0.9rem;
            line-height: 1.5;
        }
        
        .salary-info {
            font-size: 0.9rem;
        }
        
        .experience-info {
            font-size: 0.85rem;
        }
        
        .save-job-btn {
            border-radius: 50%;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }
        
        .save-job-btn:hover {
            background-color: #dc3545;
            border-color: #dc3545;
            color: white;
        }
        
        .save-job-btn:hover i {
            transform: scale(1.1);
        }
        
        .save-job-btn.saved {
            background-color: #dc3545;
            border-color: #dc3545;
            color: white;
        }
        
        .save-job-btn.saved i::before {
            content: "\f004"; /* solid heart */
        }
        
        /* Share Job Button */
        .share-job-btn {
            border-radius: 50%;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }
        
        .share-job-btn:hover {
            background-color: #28a745;
            border-color: #28a745;
            color: white;
        }
        
        .share-job-btn:hover i {
            transform: scale(1.1);
        }
        
        .share-dropdown {
            min-width: 160px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border: none;
            border-radius: 8px;
            padding: 8px 0;
        }
        
        .share-dropdown .dropdown-item {
            padding: 8px 16px;
            font-size: 0.9rem;
            transition: all 0.2s ease;
        }
        
        .share-dropdown .dropdown-item:hover {
            background-color: #f8f9fa;
            transform: translateX(2px);
        }
        
        .share-dropdown .dropdown-item i {
            width: 18px;
        }
        
        /* Sidebar Styling */
        .filters-sidebar {
            position: sticky;
            top: 20px;
        }
        
        .filters-sidebar .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            padding: 0.75rem 1rem;
        }
        
        .filters-sidebar .card-header h6 {
            font-weight: 600;
            color: #495057;
        }
        
        .filters-sidebar .form-check-label {
            font-size: 0.9rem;
            color: #495057;
        }
        
        .filters-sidebar .form-check small {
            font-size: 0.75rem;
            color: #6c757d;
        }
        
        @media (max-width: 991.98px) {
            .filters-sidebar {
                position: static;
                margin-bottom: 2rem;
            }
        }
        
        .job-location {
            font-size: 0.95rem;
            color: #6c757d !important;
            margin-bottom: 1rem;
        }
        
        .job-meta .badge {
            font-size: 0.8rem;
            padding: 0.5rem 0.75rem;
            border-radius: 20px;
            font-weight: 500;
            background-color: #f8f9fa !important;
            color: #495057 !important;
            border: 1px solid #dee2e6 !important;
        }
        
        .job-arrow {
            font-size: 1.1rem;
            color: #adb5bd;
            transition: color 0.2s ease;
        }
        
        .job-item:hover .job-arrow i {
            color: #dc3545;
        }
        
        .jobs-container {
            max-width: 100%;
        }
        
        @media (min-width: 768px) {
            .jobs-container {
                max-width: 900px;
                margin: 0 auto;
            }
        }
        
        .company-logo {
            width: 50px;
            height: 50px;
            object-fit: contain;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            background: white;
            padding: 4px;
        }
        
        .company-logo-placeholder {
            width: 50px;
            height: 50px;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
        }
    </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">
                <h1 class="h2 mb-2">
                    <?php if ($company_name): ?>
                        Jobs at <?php echo htmlspecialchars($company_name); ?>
                    <?php else: ?>
                        Browse Jobs
                    <?php endif; ?>
                </h1>
                <p class="text-muted">
                    Found <?php echo $total_jobs; ?> job opportunities
                    <?php if ($company_name): ?>
                        at <?php echo htmlspecialchars($company_name); ?>
                    <?php endif; ?>
                </p>
            </div>
            <div class="col-md-4 text-md-end">
                <?php if (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>

        <!-- Search and Filters -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label for="keyword" class="form-label">Keywords</label>
                            <input type="text" class="form-control" id="keyword" name="keyword" 
                                   value="<?php echo htmlspecialchars($keyword); ?>" placeholder="Job title, skills...">
                        </div>
                        <div class="col-md-3">
                            <label for="category" class="form-label">Category</label>
                            <select class="form-select" id="category" name="category">
                                <option value="">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo $category == $cat['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="location" class="form-label">Location</label>
                            <input type="text" class="form-control" id="location" name="location" 
                                   value="<?php echo htmlspecialchars($location); ?>" placeholder="City, State">
                        </div>
                        <div class="col-md-2">
                            <label for="employment_type" class="form-label">Type</label>
                            <select class="form-select" id="employment_type" name="employment_type">
                                <option value="">All Types</option>
                                <option value="full-time" <?php echo $employment_type === 'full-time' ? 'selected' : ''; ?>>Full-time</option>
                                <option value="part-time" <?php echo $employment_type === 'part-time' ? 'selected' : ''; ?>>Part-time</option>
                                <option value="contract" <?php echo $employment_type === 'contract' ? 'selected' : ''; ?>>Contract</option>
                                <option value="internship" <?php echo $employment_type === 'internship' ? 'selected' : ''; ?>>Internship</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-search me-1"></i>Search
                            </button>
                        </div>
                    </div>
                    
                    <div class="row g-3 mt-2">
                        <div class="col-md-3">
                            <label for="experience_level" class="form-label">Experience</label>
                            <select class="form-select" id="experience_level" name="experience_level">
                                <option value="">All Levels</option>
                                <option value="entry" <?php echo $experience_level === 'entry' ? 'selected' : ''; ?>>Entry Level</option>
                                <option value="mid" <?php echo $experience_level === 'mid' ? 'selected' : ''; ?>>Mid Level</option>
                                <option value="senior" <?php echo $experience_level === 'senior' ? 'selected' : ''; ?>>Senior Level</option>
                                <option value="executive" <?php echo $experience_level === 'executive' ? 'selected' : ''; ?>>Executive</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="work_location_type" class="form-label">Work Location</label>
                            <select class="form-select" id="work_location_type" name="work_location_type">
                                <option value="">All Locations</option>
                                <option value="office" <?php echo $work_location_type === 'office' ? 'selected' : ''; ?>>Office-based</option>
                                <option value="remote" <?php echo $work_location_type === 'remote' ? 'selected' : ''; ?>>Work from Home</option>
                                <option value="hybrid" <?php echo $work_location_type === 'hybrid' ? 'selected' : ''; ?>>Hybrid</option>
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="button" class="btn btn-outline-info btn-sm me-2" data-bs-toggle="collapse" data-bs-target="#benefitsFilter">
                                <i class="fas fa-gift me-1"></i>Benefits Filter
                            </button>
                            <a href="jobs.php" class="btn btn-outline-secondary">Clear Filters</a>
                        </div>
                    </div>
                    
                    <!-- Collapsible Benefits Filter -->
                    <div class="collapse mt-3" id="benefitsFilter">
                        <div class="card card-body bg-light">
                            <h6 class="mb-3">Filter by Benefits:</h6>
                            <div class="row">
                                <?php foreach ($filter_benefits as $benefit): ?>
                                    <div class="col-md-4 col-lg-3 mb-2">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" 
                                                   name="benefits[]" 
                                                   value="<?php echo $benefit['id']; ?>" 
                                                   id="filter_benefit_<?php echo $benefit['id']; ?>"
                                                   <?php echo in_array($benefit['id'], $benefits_filter) ? 'checked' : ''; ?>>
                                            <label class="form-check-label small" for="filter_benefit_<?php echo $benefit['id']; ?>">
                                                <i class="<?php echo $benefit['icon']; ?> me-1 text-primary"></i>
                                                <?php echo htmlspecialchars($benefit['name']); ?>
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-3">
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <i class="fas fa-filter me-1"></i>Apply Benefits Filter
                                </button>
                                <small class="text-muted ms-3">
                                    <span id="selectedFiltersCount"><?php echo count($benefits_filter); ?></span> benefits selected
                                </small>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Main Content with Sidebar -->
        <div class="row">
            <!-- Sidebar Filters -->
            <div class="col-lg-3">
                <div class="filters-sidebar">
                    <!-- Date Posted Filter -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">
                                <i class="fas fa-calendar-alt me-2"></i>Date posted
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="date_posted" value="" id="date_all" 
                                       <?php echo !isset($_GET['date_posted']) || $_GET['date_posted'] === '' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="date_all">All dates</label>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="date_posted" value="1" id="date_1d"
                                       <?php echo isset($_GET['date_posted']) && $_GET['date_posted'] === '1' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="date_1d">Past 24 hours</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="date_posted" value="3" id="date_3d"
                                       <?php echo isset($_GET['date_posted']) && $_GET['date_posted'] === '3' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="date_3d">Past 3 days</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.created_at >= DATE_SUB(NOW(), INTERVAL 3 DAY)");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="radio" name="date_posted" value="7" id="date_7d"
                                       <?php echo isset($_GET['date_posted']) && $_GET['date_posted'] === '7' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="date_7d">Past week</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="date_posted" value="14" id="date_14d"
                                       <?php echo isset($_GET['date_posted']) && $_GET['date_posted'] === '14' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="date_14d">Past 2 weeks</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.created_at >= DATE_SUB(NOW(), INTERVAL 14 DAY)");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                        </div>
                    </div>

                    <!-- Work from Home Options -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">
                                <i class="fas fa-home me-2"></i>Work from home options
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="remote_work[]" value="remote" id="remote"
                                       <?php echo in_array('remote', (array)($_GET['remote_work'] ?? [])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="remote">Fully remote</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.work_location_type = 'remote'");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="remote_work[]" value="hybrid" id="hybrid"
                                       <?php echo in_array('hybrid', (array)($_GET['remote_work'] ?? [])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="hybrid">Hybrid remote</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.work_location_type = 'hybrid'");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                        </div>
                    </div>

                    <!-- Functions -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">
                                <i class="fas fa-briefcase me-2"></i>Functions
                            </h6>
                        </div>
                        <div class="card-body">
                            <?php
                            $stmt = $db->prepare("SELECT cat.*, COUNT(j.id) as job_count FROM job_categories cat LEFT JOIN jobs j ON cat.id = j.category_id AND j.status = 'active' LEFT JOIN companies c ON j.company_id = c.id AND c.status = 'approved' GROUP BY cat.id ORDER BY cat.name");
                            $stmt->execute();
                            $sidebar_categories = $stmt->fetchAll();
                            
                            foreach ($sidebar_categories as $cat):
                            ?>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="sidebar_categories[]" value="<?php echo $cat['id']; ?>" 
                                       id="cat_<?php echo $cat['id']; ?>"
                                       <?php echo in_array($cat['id'], (array)($_GET['sidebar_categories'] ?? [])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="cat_<?php echo $cat['id']; ?>">
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </label>
                                <small class="text-muted d-block"><?php echo $cat['job_count']; ?></small>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Employment Type -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">
                                <i class="fas fa-clock me-2"></i>Employment type
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="emp_types[]" value="full-time" id="emp_full"
                                       <?php echo in_array('full-time', (array)($_GET['emp_types'] ?? [])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="emp_full">Full-time</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.employment_type = 'full-time'");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="emp_types[]" value="part-time" id="emp_part"
                                       <?php echo in_array('part-time', (array)($_GET['emp_types'] ?? [])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="emp_part">Part-time</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.employment_type = 'part-time'");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="emp_types[]" value="contract" id="emp_contract"
                                       <?php echo in_array('contract', (array)($_GET['emp_types'] ?? [])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="emp_contract">Contract</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.employment_type = 'contract'");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="emp_types[]" value="internship" id="emp_intern"
                                       <?php echo in_array('internship', (array)($_GET['emp_types'] ?? [])) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="emp_intern">Internship</label>
                                <small class="text-muted d-block">
                                    <?php
                                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs j LEFT JOIN companies c ON j.company_id = c.id WHERE j.status = 'active' AND c.status = 'approved' AND j.employment_type = 'internship'");
                                    $stmt->execute();
                                    $count = $stmt->fetch()['count'];
                                    echo $count;
                                    ?>
                                </small>
                            </div>
                        </div>
                    </div>

                    <!-- Apply Filter Button -->
                    <button type="button" class="btn btn-primary w-100 mb-3" onclick="applySidebarFilters()">
                        <i class="fas fa-filter me-1"></i>Apply Filters
                    </button>
                    <button type="button" class="btn btn-outline-secondary w-100" onclick="clearSidebarFilters()">
                        <i class="fas fa-times me-1"></i>Clear All
                    </button>
                </div>
            </div>

            <!-- Jobs List -->
            <div class="col-lg-9">
                <div class="jobs-container">
                    <?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): ?>
                    <div class="job-card-modern mb-3">
                        <div class="card border-0 shadow-sm job-item">
                            <div class="card-body p-4">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <!-- Job Title -->
                                        <h3 class="job-title mb-2">
                                            <a href="job-details.php?id=<?php echo $job['id']; ?>" class="text-decoration-none">
                                                <?php echo htmlspecialchars($job['title']); ?>
                                            </a>
                                        </h3>
                                        
                                        <!-- Company and Location -->
                                        <div class="d-flex align-items-center text-muted mb-3">
                                            <div class="company-info d-flex align-items-center me-4">
                                                <?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-small me-2">
                                                <?php else: ?>
                                                    <div class="company-logo-small-placeholder me-2">
                                                        <i class="fas fa-building"></i>
                                                    </div>
                                                <?php endif; ?>
                                                <span><?php echo htmlspecialchars($job['company_name']); ?></span>
                                            </div>
                                            <div class="location-info d-flex align-items-center">
                                                <i class="fas fa-map-marker-alt me-1"></i>
                                                <span><?php echo htmlspecialchars($job['location']); ?></span>
                                            </div>
                                        </div>
                                        
                                        <!-- Job Description Preview -->
                                        <p class="job-description-preview text-muted mb-3">
                                            <?php 
                                                $description = strip_tags($job['description']);
                                                echo htmlspecialchars(strlen($description) > 150 ? substr($description, 0, 150) . '...' : $description);
                                            ?>
                                        </p>
                                        
                                        <!-- Salary and Experience -->
                                        <div class="d-flex flex-wrap align-items-center gap-3 mb-3">
                                            <?php if ($job['salary_min'] || $job['salary_max']): ?>
                                                <div class="salary-info">
                                                    <i class="fas fa-money-bill-wave text-success me-1"></i>
                                                    <span class="fw-semibold text-success">
                                                        <?php if ($job['salary_min'] && $job['salary_max']): ?>
                                                            R<?php echo number_format($job['salary_min']); ?> - R<?php echo number_format($job['salary_max']); ?> TCTC
                                                        <?php elseif ($job['salary_min']): ?>
                                                            From R<?php echo number_format($job['salary_min']); ?> TCTC
                                                        <?php else: ?>
                                                            Up to R<?php echo number_format($job['salary_max']); ?> TCTC
                                                        <?php endif; ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                            <div class="experience-info text-muted">
                                                <?php echo ucfirst($job['experience_level']); ?> years experience in <?php echo htmlspecialchars($job['category_name'] ?: 'General'); ?>
                                            </div>
                                        </div>
                                        
                                        <!-- Job Type and Work Location Badges -->
                                        <div class="d-flex flex-wrap gap-2 mb-3">
                                            <?php
                                            switch ($job['job_type']) {
                                                case 'internal':
                                                    $job_type_badge = 'bg-warning text-dark';
                                                    $job_type_icon = 'fas fa-user-tie';
                                                    $job_type_text = 'Internal Only';
                                                    break;
                                                case 'external':
                                                    $job_type_badge = 'bg-info text-white';
                                                    $job_type_icon = 'fas fa-globe';
                                                    $job_type_text = 'External Only';
                                                    break;
                                                default:
                                                    $job_type_badge = 'bg-primary text-white';
                                                    $job_type_icon = 'fas fa-users';
                                                    $job_type_text = 'All Candidates';
                                            }
                                            
                                            switch ($job['work_location_type']) {
                                                case 'remote':
                                                    $work_location_badge = 'bg-success text-white';
                                                    $work_location_icon = 'fas fa-home';
                                                    $work_location_text = 'Remote';
                                                    break;
                                                case 'hybrid':
                                                    $work_location_badge = 'bg-warning text-dark';
                                                    $work_location_icon = 'fas fa-arrows-alt-h';
                                                    $work_location_text = 'Hybrid';
                                                    break;
                                                default:
                                                    $work_location_badge = 'bg-secondary text-white';
                                                    $work_location_icon = 'fas fa-building';
                                                    $work_location_text = 'Office';
                                            }
                                            ?>
                                            <span class="badge <?php echo $job_type_badge; ?>">
                                                <i class="<?php echo $job_type_icon; ?> me-1"></i>
                                                <?php echo $job_type_text; ?>
                                            </span>
                                            <span class="badge <?php echo $work_location_badge; ?>">
                                                <i class="<?php echo $work_location_icon; ?> me-1"></i>
                                                <?php echo $work_location_text; ?>
                                            </span>
                                            <span class="badge bg-light text-dark border">
                                                <i class="fas fa-clock me-1"></i>
                                                <?php echo ucfirst(str_replace('-', ' ', $job['employment_type'])); ?>
                                            </span>
                                        </div>
                                        
                                        <!-- Posted Time -->
                                        <div class="text-muted small">
                                            <?php 
                                                $posted_time = new DateTime($job['created_at']);
                                                $now = new DateTime();
                                                $interval = $now->diff($posted_time);
                                                
                                                if ($interval->d > 0) {
                                                    echo $interval->d . ' day' . ($interval->d > 1 ? 's' : '') . ' ago';
                                                } elseif ($interval->h > 0) {
                                                    echo $interval->h . ' hour' . ($interval->h > 1 ? 's' : '') . ' ago';
                                                } else {
                                                    echo 'Just posted';
                                                }
                                            ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Save Job & Share Buttons -->
                                    <div class="job-actions d-flex gap-2">
                                        <button class="btn btn-outline-secondary btn-sm save-job-btn" data-job-id="<?php echo $job['id']; ?>" title="Save Job">
                                            <i class="far fa-heart"></i>
                                        </button>
                                        
                                        <!-- Share Button with Dropdown -->
                                        <div class="dropdown">
                                            <button class="btn btn-outline-secondary btn-sm share-job-btn" data-bs-toggle="dropdown" aria-expanded="false" title="Share Job">
                                                <i class="fas fa-share-alt"></i>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end share-dropdown">
                                                <li>
                                                    <a class="dropdown-item share-option" 
                                                       href="#" 
                                                       data-platform="whatsapp" 
                                                       data-url="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/recruitment/job-details.php?id=' . $job['id']; ?>"
                                                       data-title="<?php echo htmlspecialchars($job['title']); ?>"
                                                       data-company="<?php echo htmlspecialchars($job['company_name']); ?>">
                                                        <i class="fab fa-whatsapp text-success me-2"></i>WhatsApp
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item share-option" 
                                                       href="#" 
                                                       data-platform="facebook" 
                                                       data-url="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/recruitment/job-details.php?id=' . $job['id']; ?>"
                                                       data-title="<?php echo htmlspecialchars($job['title']); ?>"
                                                       data-company="<?php echo htmlspecialchars($job['company_name']); ?>">
                                                        <i class="fab fa-facebook-f text-primary me-2"></i>Facebook
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item share-option" 
                                                       href="#" 
                                                       data-platform="twitter" 
                                                       data-url="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/recruitment/job-details.php?id=' . $job['id']; ?>"
                                                       data-title="<?php echo htmlspecialchars($job['title']); ?>"
                                                       data-company="<?php echo htmlspecialchars($job['company_name']); ?>">
                                                        <i class="fab fa-twitter text-info me-2"></i>X (Twitter)
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item share-option" 
                                                       href="#" 
                                                       data-platform="email" 
                                                       data-url="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . '/recruitment/job-details.php?id=' . $job['id']; ?>"
                                                       data-title="<?php echo htmlspecialchars($job['title']); ?>"
                                                       data-company="<?php echo htmlspecialchars($job['company_name']); ?>">
                                                        <i class="fas fa-envelope text-secondary me-2"></i>Email
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <nav aria-label="Job search pagination">
                <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>

    <!-- 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>
        // Save job functionality
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.save-job-btn').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const jobId = this.dataset.jobId;
                    const icon = this.querySelector('i');
                    
                    // Toggle saved state
                    if (this.classList.contains('saved')) {
                        this.classList.remove('saved');
                        icon.className = 'far fa-heart';
                        this.title = 'Save Job';
                    } else {
                        this.classList.add('saved');
                        icon.className = 'fas fa-heart';
                        this.title = 'Job Saved';
                    }
                    
                    // Here you could add AJAX call to save/unsave job
                    // fetch('/api/save-job.php', { method: 'POST', ... })
                });
            });
            
            // Share job functionality
            document.querySelectorAll('.share-option').forEach(shareLink => {
                shareLink.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    const platform = this.getAttribute('data-platform');
                    const url = this.getAttribute('data-url');
                    const title = this.getAttribute('data-title');
                    const company = this.getAttribute('data-company');
                    
                    const shareText = `Check out this ${title} position at ${company}!`;
                    
                    let shareUrl = '';
                    
                    switch(platform) {
                        case 'whatsapp':
                            shareUrl = `https://wa.me/?text=${encodeURIComponent(shareText + ' ' + url)}`;
                            break;
                        case 'facebook':
                            shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}&quote=${encodeURIComponent(shareText)}`;
                            break;
                        case 'twitter':
                            shareUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(url)}`;
                            break;
                        case 'email':
                            shareUrl = `mailto:?subject=${encodeURIComponent('Job Opportunity: ' + title)}&body=${encodeURIComponent(shareText + '\n\n' + url)}`;
                            break;
                    }
                    
                    if (shareUrl) {
                        if (platform === 'email') {
                            window.location.href = shareUrl;
                        } else {
                            window.open(shareUrl, '_blank', 'width=600,height=400,scrollbars=yes,resizable=yes');
                        }
                    }
                });
            });
        });
        
        // Sidebar filter functions
        function applySidebarFilters() {
            const form = document.createElement('form');
            form.method = 'GET';
            form.style.display = 'none';
            
            // Get current top filters
            const currentParams = new URLSearchParams(window.location.search);
            ['keyword', 'category', 'location', 'employment_type', 'experience_level', 'work_location_type', 'company'].forEach(param => {
                const value = currentParams.get(param);
                if (value) {
                    const input = document.createElement('input');
                    input.name = param;
                    input.value = value;
                    form.appendChild(input);
                }
            });
            
            // Add sidebar filters
            // Date posted
            const datePosted = document.querySelector('input[name="date_posted"]:checked');
            if (datePosted && datePosted.value) {
                const input = document.createElement('input');
                input.name = 'date_posted';
                input.value = datePosted.value;
                form.appendChild(input);
            }
            
            // Remote work options
            document.querySelectorAll('input[name="remote_work[]"]:checked').forEach(checkbox => {
                const input = document.createElement('input');
                input.name = 'remote_work[]';
                input.value = checkbox.value;
                form.appendChild(input);
            });
            
            // Categories
            document.querySelectorAll('input[name="sidebar_categories[]"]:checked').forEach(checkbox => {
                const input = document.createElement('input');
                input.name = 'sidebar_categories[]';
                input.value = checkbox.value;
                form.appendChild(input);
            });
            
            // Employment types
            document.querySelectorAll('input[name="emp_types[]"]:checked').forEach(checkbox => {
                const input = document.createElement('input');
                input.name = 'emp_types[]';
                input.value = checkbox.value;
                form.appendChild(input);
            });
            
            document.body.appendChild(form);
            form.submit();
        }
        
        function clearSidebarFilters() {
            // Keep only the main search parameters, remove sidebar filters
            const currentParams = new URLSearchParams(window.location.search);
            const keepParams = ['keyword', 'category', 'location', 'employment_type', 'experience_level', 'work_location_type', 'company'];
            
            const newParams = new URLSearchParams();
            keepParams.forEach(param => {
                const value = currentParams.get(param);
                if (value) {
                    newParams.set(param, value);
                }
            });
            
            window.location.href = '?' + newParams.toString();
        }
    </script>
</body>
</html>