<?php
/**
 * Job Portal - Job Listings Page
 * GHAMECC Choir Management Platform
 * 
 * This page displays all available job listings with filtering options.
 */

// Include database connection and functions
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Initialize variables
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$categoryId = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$location = isset($_GET['location']) ? trim($_GET['location']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : 'open';
$sort = isset($_GET['sort']) ? trim($_GET['sort']) : 'newest';

// Build the WHERE clause
$whereConditions = ["j.status = 'open'", "j.approval_status = 'approved'"];
$params = [];

// Add search condition
if (!empty($search)) {
    $whereConditions[] = "(j.title LIKE ? OR j.description LIKE ? OR j.requirements LIKE ? OR j.location LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
}

// Add category filter
if ($categoryId > 0) {
    $whereConditions[] = "j.category_id = ?";
    $params[] = $categoryId;
}

// Add location filter
if (!empty($location)) {
    $locationTerm = "%$location%";
    $whereConditions[] = "j.location LIKE ?";
    $params[] = $locationTerm;
}

// Add status filter
if (!empty($status)) {
    $whereConditions[] = "j.status = ?";
    $params[] = $status;
}

$whereClause = "WHERE " . implode(" AND ", $whereConditions);

// Build the query
$query = "SELECT j.*, c.name as category_name, 
          (SELECT COUNT(*) FROM job_applications WHERE job_id = j.id) as application_count 
          FROM jobs j 
          LEFT JOIN job_categories c ON j.category_id = c.id 
          $whereClause";
$countQuery = "SELECT COUNT(*) FROM jobs j $whereClause";

// Add sorting
switch ($sort) {
    case 'title_asc':
        $query .= " ORDER BY j.title ASC";
        break;
    case 'title_desc':
        $query .= " ORDER BY j.title DESC";
        break;
    case 'deadline_asc':
        $query .= " ORDER BY j.deadline ASC";
        break;
    case 'deadline_desc':
        $query .= " ORDER BY j.deadline DESC";
        break;
    case 'oldest':
        $query .= " ORDER BY j.created_at ASC";
        break;
    case 'newest':
    default:
        $query .= " ORDER BY j.created_at DESC";
        break;
}

// Add pagination
$query .= " LIMIT ? OFFSET ?";
$paginationParams = [$perPage, $offset];

// Get total count for pagination
$totalJobs = fetchValue($countQuery, $params);
$totalPages = ceil($totalJobs / $perPage);

// Get jobs
$jobs = fetchRows($query, array_merge($params, $paginationParams));

// Get all categories for filter dropdown
$categories = fetchRows("SELECT * FROM job_categories ORDER BY name ASC");

// Get distinct locations for filter dropdown
$locations = fetchRows("SELECT DISTINCT location FROM jobs WHERE location != '' ORDER BY location ASC");

// Page title
$pageTitle = "Job Listings | GHAMECC Job Portal";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom CSS -->
    <style>
        .job-card {
            transition: transform 0.3s;
            border-left: 4px solid #0d6efd;
        }
        .job-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .filter-section {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .badge-job-type {
            font-size: 0.8rem;
            padding: 0.35em 0.65em;
        }
        .pagination-container {
            margin-top: 30px;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/job-portal-navbar.php'; ?>
    
    <div class="container py-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="mb-0">Job Listings</h1>
            <?php if (isLoggedIn()): ?>
                <a href="post-job.php" class="btn btn-primary">
                    <i class="fas fa-plus-circle me-2"></i> Post a Job
                </a>
            <?php endif; ?>
        </div>
        
        <!-- Filter Section -->
        <div class="filter-section">
            <form action="job-listings.php" method="get" class="row g-3">
                <div class="col-md-4">
                    <label for="search" class="form-label">Search</label>
                    <input type="text" class="form-control" id="search" name="search" placeholder="Job title, description..." value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-3">
                    <label for="category" class="form-label">Category</label>
                    <select class="form-select" id="category" name="category">
                        <option value="0">All Categories</option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?php echo $category['id']; ?>" <?php echo $categoryId == $category['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="location" class="form-label">Location</label>
                    <select class="form-select" id="location" name="location">
                        <option value="">All Locations</option>
                        <?php foreach ($locations as $loc): ?>
                            <option value="<?php echo htmlspecialchars($loc['location']); ?>" <?php echo $location == $loc['location'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($loc['location']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="status" class="form-label">Status</label>
                    <select class="form-select" id="status" name="status">
                        <option value="open" <?php echo $status == 'open' ? 'selected' : ''; ?>>Open</option>
                        <option value="closed" <?php echo $status == 'closed' ? 'selected' : ''; ?>>Closed</option>
                        <option value="filled" <?php echo $status == 'filled' ? 'selected' : ''; ?>>Filled</option>
                        <option value="" <?php echo $status == '' ? 'selected' : ''; ?>>All</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="sort" class="form-label">Sort By</label>
                    <select class="form-select" id="sort" name="sort">
                        <option value="newest" <?php echo $sort == 'newest' ? 'selected' : ''; ?>>Newest First</option>
                        <option value="oldest" <?php echo $sort == 'oldest' ? 'selected' : ''; ?>>Oldest First</option>
                        <option value="title_asc" <?php echo $sort == 'title_asc' ? 'selected' : ''; ?>>Title (A-Z)</option>
                        <option value="title_desc" <?php echo $sort == 'title_desc' ? 'selected' : ''; ?>>Title (Z-A)</option>
                        <option value="deadline_asc" <?php echo $sort == 'deadline_asc' ? 'selected' : ''; ?>>Deadline (Soonest)</option>
                        <option value="deadline_desc" <?php echo $sort == 'deadline_desc' ? 'selected' : ''; ?>>Deadline (Latest)</option>
                    </select>
                </div>
                <div class="col-md-9 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="fas fa-filter me-2"></i> Apply Filters
                    </button>
                    <a href="job-listings.php" class="btn btn-outline-secondary">
                        <i class="fas fa-redo me-2"></i> Reset
                    </a>
                </div>
            </form>
        </div>
        
        <!-- Results Summary -->
        <div class="mb-4">
            <p class="text-muted">
                Showing <?php echo count($jobs); ?> of <?php echo $totalJobs; ?> jobs
                <?php if (!empty($search)): ?>
                    matching "<?php echo htmlspecialchars($search); ?>"
                <?php endif; ?>
                <?php if ($categoryId > 0): 
                    $catName = fetchValue("SELECT name FROM job_categories WHERE id = ?", [$categoryId]);
                    echo ' in category "' . htmlspecialchars($catName) . '"';
                endif; ?>
                <?php if (!empty($location)): ?>
                    in "<?php echo htmlspecialchars($location); ?>"
                <?php endif; ?>
            </p>
        </div>
        
        <!-- Job Listings -->
        <?php if (empty($jobs)): ?>
            <div class="alert alert-info">
                <i class="fas fa-info-circle me-2"></i> No jobs found matching your criteria. Try adjusting your filters.
            </div>
        <?php else: ?>
            <div class="row">
                <?php foreach ($jobs as $job): ?>
                    <div class="col-12 mb-4">
                        <div class="card job-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <h5 class="card-title mb-1">
                                            <a href="job-details.php?id=<?php echo $job['id']; ?>" class="text-decoration-none">
                                                <?php echo htmlspecialchars($job['title']); ?>
                                            </a>
                                        </h5>
                                        <p class="text-muted mb-2">
                                            <span class="me-3">
                                                <i class="fas fa-building me-1"></i> <?php echo htmlspecialchars($job['company_name']); ?>
                                            </span>
                                            <span class="me-3">
                                                <i class="fas fa-map-marker-alt me-1"></i> <?php echo htmlspecialchars($job['location']); ?>
                                            </span>
                                            <?php if (!empty($job['salary_range'])): ?>
                                                <span class="me-3">
                                                    <i class="fas fa-money-bill-wave me-1"></i> <?php echo htmlspecialchars($job['salary_range']); ?>
                                                </span>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <div>
                                        <span class="badge bg-<?php 
                                        switch($job['status']) {
                                            case 'open': echo 'success'; break;
                                            case 'closed': echo 'danger'; break;
                                            case 'filled': echo 'warning'; break;
                                            default: echo 'secondary';
                                        }
                                        ?>">
                                            <?php echo ucfirst($job['status']); ?>
                                        </span>
                                        <?php if (!empty($job['category_name'])): ?>
                                            <span class="badge bg-primary ms-1"><?php echo htmlspecialchars($job['category_name']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <p class="card-text mt-3"><?php echo substr(cleanText($job['description'], false), 0, 200) . '...'; ?></p>
                                
                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <div>
                                        <small class="text-muted">
                                            <i class="far fa-calendar-alt me-1"></i> Posted: <?php echo date('M d, Y', strtotime($job['created_at'])); ?>
                                        </small>
                                        <?php if (!empty($job['deadline'])): ?>
                                            <small class="text-muted ms-3">
                                                <i class="fas fa-hourglass-end me-1"></i> Deadline: <?php echo date('M d, Y', strtotime($job['deadline'])); ?>
                                                <?php 
                                                $daysLeft = ceil((strtotime($job['deadline']) - time()) / (60 * 60 * 24));
                                                if ($daysLeft > 0 && $job['status'] == 'open'): 
                                                ?>
                                                    <span class="text-<?php echo $daysLeft <= 3 ? 'danger' : 'success'; ?>">
                                                        (<?php echo $daysLeft; ?> days left)
                                                    </span>
                                                <?php endif; ?>
                                            </small>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <small class="text-muted me-3">
                                            <i class="fas fa-users me-1"></i> <?php echo $job['application_count']; ?> applicants
                                        </small>
                                        <a href="job-details.php?id=<?php echo $job['id']; ?>" class="btn btn-outline-primary btn-sm">
                                            View Details
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
                <div class="pagination-container d-flex justify-content-center">
                    <nav aria-label="Page navigation">
                        <ul class="pagination">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId > 0 ? '&category=' . $categoryId : ''; ?><?php echo !empty($location) ? '&location=' . urlencode($location) : ''; ?><?php echo !empty($status) ? '&status=' . urlencode($status) : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="First">
                                        <span aria-hidden="true">&laquo;&laquo;</span>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId > 0 ? '&category=' . $categoryId : ''; ?><?php echo !empty($location) ? '&location=' . urlencode($location) : ''; ?><?php echo !empty($status) ? '&status=' . urlencode($status) : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $startPage = max(1, $page - 2);
                            $endPage = min($totalPages, $page + 2);
                            
                            for ($i = $startPage; $i <= $endPage; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId > 0 ? '&category=' . $categoryId : ''; ?><?php echo !empty($location) ? '&location=' . urlencode($location) : ''; ?><?php echo !empty($status) ? '&status=' . urlencode($status) : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId > 0 ? '&category=' . $categoryId : ''; ?><?php echo !empty($location) ? '&location=' . urlencode($location) : ''; ?><?php echo !empty($status) ? '&status=' . urlencode($status) : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $totalPages; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo $categoryId > 0 ? '&category=' . $categoryId : ''; ?><?php echo !empty($location) ? '&location=' . urlencode($location) : ''; ?><?php echo !empty($status) ? '&status=' . urlencode($status) : ''; ?><?php echo !empty($sort) ? '&sort=' . urlencode($sort) : ''; ?>" aria-label="Last">
                                        <span aria-hidden="true">&raquo;&raquo;</span>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    
    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>GHAMECC Job Portal</h5>
                    <p class="text-muted">Connecting talent with opportunities within the GHAMECC community.</p>
                </div>
                <div class="col-md-4 mb-4 mb-md-0">
                    <h5>Quick Links</h5>
                    <ul class="list-unstyled">
                        <li><a href="index.php" class="text-decoration-none text-muted">Home</a></li>
                        <li><a href="talent-showcase.php" class="text-decoration-none text-muted">Talent Showcase</a></li>
                        <li><a href="categories.php" class="text-decoration-none text-muted">Categories</a></li>
                        <?php if (isLoggedIn()): ?>
                            <li><a href="create-profile.php" class="text-decoration-none text-muted">Create Profile</a></li>
                        <?php else: ?>
                            <li><a href="../login.php" class="text-decoration-none text-muted">Login</a></li>
                        <?php endif; ?>
                    </ul>
                </div>
                <div class="col-md-4">
                    <h5>Contact</h5>
                    <address class="text-muted">
                        <i class="fas fa-map-marker-alt me-2"></i> GHAMECC Headquarters<br>
                        <i class="fas fa-phone me-2"></i> (123) 456-7890<br>
                        <i class="fas fa-envelope me-2"></i> jobs@ghamecc.org
                    </address>
                </div>
            </div>
            <hr class="my-4 bg-secondary">
            <div class="text-center text-muted">
                <small>&copy; <?php echo date('Y'); ?> GHAMECC Job Portal. All rights reserved.</small>
            </div>
        </div>
    </footer>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
