<?php
/**
 * Página de listado de vacantes - Frontend público
 * Turpial Airlines, C.A.
 */

require_once '../includes/functions.php';
require_once '../includes/JobVacancy.php';
require_once '../includes/Division.php';

$page_title = 'Vacantes de Empleo';

// Obtener filtros
$division_id = isset($_GET['division']) ? (int)$_GET['division'] : null;
$category_id = isset($_GET['category']) ? (int)$_GET['category'] : null;
$search = isset($_GET['search']) ? cleanString($_GET['search']) : '';

// Preparar filtros
$filters = ['is_active' => 1];
if ($division_id) $filters['division_id'] = $division_id;
if ($category_id) $filters['category_id'] = $category_id;
if ($search) $filters['search'] = $search;

// Obtener vacantes
$jobVacancy = new JobVacancy();
$jobs = $jobVacancy->getAll($filters);

// Obtener divisiones y categorías para filtros
$division = new Division();
$divisions = $division->getAll(true);

// Si hay una división seleccionada, obtener sus categorías
$categories = [];
if ($division_id) {
    require_once '../includes/Division.php';
    $categoryObj = new Category();
    $categories = $categoryObj->getByDivision($division_id);
}

include 'includes/header.php';
?>

<!-- Page Header -->
<section class="py-5 bg-dark text-white">
    <div class="container">
        <div class="row">
            <div class="col-lg-8">
                <h1 class="display-5 fw-bold mb-3">
                    <i class="fas fa-briefcase me-3"></i>Oportunidades de Empleo
                </h1>
                <p class="lead">Descubre la vacante perfecta para tu perfil profesional en Turpial Airlines</p>
            </div>
            <div class="col-lg-4 text-lg-end">
                <div class="bg-turpial text-black p-3 rounded">
                    <h4 class="mb-0"><?php echo count($jobs); ?></h4>
                    <small>Vacantes Encontradas</small>
                </div>
            </div>
        </div>
    </div>
</section>

<div class="container py-5">
    <div class="row">
        <!-- Filtros -->
        <div class="col-lg-3 mb-4">
            <div class="filters">
                <h4><i class="fas fa-filter me-2"></i>Filtros</h4>
                
                <form method="GET" action="jobs.php">
                    <!-- Búsqueda por texto -->
                    <div class="mb-3">
                        <label for="search" class="form-label">Buscar</label>
                        <input type="text" class="form-control" id="search" name="search" 
                               value="<?php echo escape($search); ?>" 
                               placeholder="Título, descripción...">
                    </div>
                    
                    <!-- División -->
                    <div class="mb-3">
                        <label for="division" class="form-label">División</label>
                        <select class="form-select" id="division" name="division" onchange="loadCategories(this.value)">
                            <option value="">Todas las Divisiones</option>
                            <?php foreach ($divisions as $div): ?>
                                <option value="<?php echo $div['id']; ?>" 
                                        <?php echo ($division_id == $div['id']) ? 'selected' : ''; ?>>
                                    <?php echo escape($div['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Categoría -->
                    <div class="mb-3">
                        <label for="category" class="form-label">Categoría</label>
                        <select class="form-select" id="category" name="category">
                            <option value="">Todas las Categorías</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>" 
                                        <?php echo ($category_id == $cat['id']) ? 'selected' : ''; ?>>
                                    <?php echo escape($cat['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-turpial">
                            <i class="fas fa-search me-2"></i>Buscar
                        </button>
                        <a href="jobs.php" class="btn btn-outline-secondary">
                            <i class="fas fa-times me-2"></i>Limpiar
                        </a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Lista de Vacantes -->
        <div class="col-lg-9">
            <?php if (empty($jobs)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-search fa-4x text-muted mb-4"></i>
                    <h3>No se encontraron vacantes</h3>
                    <p class="text-muted">Intenta modificar los filtros de búsqueda o explora todas nuestras oportunidades.</p>
                    <a href="jobs.php" class="btn btn-turpial">Ver Todas las Vacantes</a>
                </div>
            <?php else: ?>
                <?php foreach ($jobs as $job): ?>
                    <div class="card vacancy-card">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-lg-8">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <h5 class="vacancy-title mb-0"><?php echo escape($job['title']); ?></h5>
                                        <?php if ($job['is_featured']): ?>
                                            <span class="badge bg-warning ms-2">
                                                <i class="fas fa-star"></i> Destacada
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="vacancy-meta mb-3">
                                        <span class="badge bg-secondary me-2">
                                            <i class="fas fa-building me-1"></i><?php echo escape($job['division_name']); ?>
                                        </span>
                                        <span class="badge bg-info me-2">
                                            <i class="fas fa-tag me-1"></i><?php echo escape($job['category_name']); ?>
                                        </span>
                                        <span class="badge bg-success me-2">
                                            <i class="fas fa-map-marker-alt me-1"></i><?php echo escape($job['location']); ?>
                                        </span>
                                        <span class="badge bg-dark">
                                            <i class="fas fa-clock me-1"></i><?php echo escape($job['employment_type']); ?>
                                        </span>
                                    </div>
                                    
                                    <p class="text-muted mb-3"><?php echo truncateText(strip_tags($job['description']), 200); ?></p>
                                    
                                    <div class="row text-muted small">
                                        <div class="col-md-6">
                                            <i class="fas fa-calendar me-1"></i>Publicada: <?php echo formatDate($job['created_at']); ?>
                                        </div>
                                        <div class="col-md-6">
                                            <i class="fas fa-users me-1"></i><?php echo $job['application_count']; ?> candidatos
                                        </div>
                                        <?php if ($job['deadline']): ?>
                                            <div class="col-md-6 mt-1">
                                                <i class="fas fa-hourglass-end me-1"></i>Cierra: <?php echo formatDate($job['deadline']); ?>
                                            </div>
                                        <?php endif; ?>
                                        <?php if ($job['salary_range']): ?>
                                            <div class="col-md-6 mt-1">
                                                <i class="fas fa-dollar-sign me-1"></i><?php echo escape($job['salary_range']); ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="col-lg-4 text-lg-end">
                                    <div class="d-grid gap-2">
                                        <a href="job-detail.php?id=<?php echo $job['id']; ?>" class="btn btn-outline-primary">
                                            <i class="fas fa-eye me-2"></i>Ver Detalles
                                        </a>
                                        <a href="apply.php?job=<?php echo $job['id']; ?>" class="btn btn-turpial">
                                            <i class="fas fa-paper-plane me-2"></i>Aplicar Ahora
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Script para cargar categorías dinámicamente -->
<script>
function loadCategories(divisionId) {
    const categorySelect = document.getElementById('category');
    
    // Limpiar opciones actuales
    categorySelect.innerHTML = '<option value="">Todas las Categorías</option>';
    
    if (divisionId) {
        // Hacer petición AJAX para obtener categorías
        fetch(`ajax/get-categories.php?division_id=${divisionId}`)
            .then(response => response.json())
            .then(data => {
                data.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.id;
                    option.textContent = category.name;
                    categorySelect.appendChild(option);
                });
            })
            .catch(error => console.error('Error:', error));
    }
}
</script>

<?php include 'includes/footer.php'; ?>