<?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'] : '';

// 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 = [];

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;
}

$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
    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>Browse Jobs - <?php echo 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-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: #dc3545 !important;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1) !important;
        }
        
        .job-title {
            font-size: 1.25rem;
            line-height: 1.4;
            color: #dc3545 !important;
        }
        
        .job-title:hover {
            color: #c82333 !important;
        }
        
        .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">Browse Jobs</h1>
                <p class="text-muted">Found <?php echo $total_jobs; ?> job opportunities</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 d-flex align-items-end">
                            <a href="jobs.php" class="btn btn-outline-secondary">Clear Filters</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Jobs List -->
        <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">
                        <a href="job-details.php?id=<?php echo $job['id']; ?>" class="text-decoration-none">
                            <div class="card border-0 shadow-sm job-item h-100">
                                <div class="card-body p-4">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="d-flex align-items-start">
                                            <!-- Company Logo -->
                                            <div class="me-3">
                                                <?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 Details -->
                                            <div class="flex-grow-1">
                                                <h5 class="job-title text-danger mb-1 fw-bold">
                                                    <?php echo htmlspecialchars($job['title']); ?>
                                                </h5>
                                                <p class="text-primary mb-2 fw-medium">
                                                    <?php echo htmlspecialchars($job['company_name']); ?>
                                                </p>
                                                <p class="job-location text-muted mb-3 fs-6">
                                                    <i class="fas fa-map-marker-alt me-1"></i>
                                                    <?php echo htmlspecialchars($job['location']); ?>
                                                </p>
                                                <div class="job-meta d-flex flex-wrap gap-3">
                                                    <span class="job-category badge bg-light text-dark border">
                                                        <i class="fas fa-briefcase me-1"></i>
                                                        <?php echo htmlspecialchars($job['category_name'] ?: 'General'); ?>
                                                    </span>
                                                    <span class="job-type badge bg-light text-dark border">
                                                        <i class="fas fa-clock me-1"></i>
                                                        <?php echo ucfirst(str_replace('-', ' ', $job['employment_type'])); ?>
                                                    </span>
                                                    <span class="job-level badge bg-light text-dark border">
                                                        <i class="fas fa-layer-group me-1"></i>
                                                        <?php echo ucfirst($job['experience_level']); ?>+ years
                                                    </span>
                                                    <?php if ($job['salary_min'] || $job['salary_max']): ?>
                                                        <span class="job-salary badge bg-success text-white">
                                                            <i class="fas fa-coins me-1"></i>
                                                            <?php if ($job['salary_min'] && $job['salary_max']): ?>
                                                                R<?php echo number_format($job['salary_min']); ?> - R<?php echo number_format($job['salary_max']); ?>
                                                            <?php elseif ($job['salary_min']): ?>
                                                                From R<?php echo number_format($job['salary_min']); ?>
                                                            <?php else: ?>
                                                                Up to R<?php echo number_format($job['salary_max']); ?>
                                                            <?php endif; ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="job-arrow">
                                            <i class="fas fa-chevron-right text-muted"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </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>
</body>
</html>