<?php
/**
 * Gestión de vacantes - Backoffice administrativo
 * Turpial Airlines, C.A.
 */

$page_title = 'Gestión de Vacantes';

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

// Verificar autenticación
requireLogin();

$jobVacancy = new JobVacancy();
$division = new Division();
$category = new Category();

$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$message = '';
$error = '';

// Procesar acciones
if ($_POST) {
    switch ($action) {
        case 'create':
        case 'edit':
            $data = [
                'category_id' => (int)$_POST['category_id'],
                'title' => cleanString($_POST['title']),
                'description' => cleanString($_POST['description']),
                'requirements' => cleanString($_POST['requirements']),
                'responsibilities' => cleanString($_POST['responsibilities']),
                'salary_range' => cleanString($_POST['salary_range']),
                'employment_type' => $_POST['employment_type'],
                'location' => cleanString($_POST['location']),
                'experience_required' => cleanString($_POST['experience_required']),
                'education_required' => cleanString($_POST['education_required']),
                'deadline' => $_POST['deadline'],
                'max_applicants' => (int)($_POST['max_applicants'] ?? 0),
                'is_featured' => isset($_POST['is_featured'])
            ];
            
            try {
                if ($action == 'create') {
                    $jobVacancy->create($data);
                    $message = 'Vacante creada exitosamente';
                    $action = 'list';
                } else {
                    $jobVacancy->update($id, $data);
                    $message = 'Vacante actualizada exitosamente';
                }
            } catch (Exception $e) {
                $error = 'Error al procesar la vacante: ' . $e->getMessage();
            }
            break;
    }
}

// Manejar acciones GET
if (isset($_GET['toggle']) && $id) {
    $jobVacancy->toggleStatus($id);
    $message = 'Estado de la vacante actualizado';
    header('Location: vacancies.php');
    exit;
}

if (isset($_GET['delete']) && $id) {
    $jobVacancy->delete($id);
    $message = 'Vacante eliminada';
    header('Location: vacancies.php');
    exit;
}

// Obtener datos según la acción
switch ($action) {
    case 'list':
        $filters = [];
        if (isset($_GET['division'])) $filters['division_id'] = (int)$_GET['division'];
        if (isset($_GET['category'])) $filters['category_id'] = (int)$_GET['category'];
        if (isset($_GET['status'])) $filters['is_active'] = (int)$_GET['status'];
        
        $vacancies = $jobVacancy->getAll($filters);
        $divisions = $division->getAll();
        break;
        
    case 'create':
    case 'edit':
        $divisions = $division->getAll(true);
        $categories = [];
        
        if ($action == 'edit' && $id) {
            $vacancy = $jobVacancy->getById($id);
            if (!$vacancy) {
                header('Location: vacancies.php?error=not_found');
                exit;
            }
            $categories = $category->getByDivision($vacancy['division_id']);
        }
        break;
        
    case 'view':
        if (!$id) {
            header('Location: vacancies.php');
            exit;
        }
        $vacancy = $jobVacancy->getById($id);
        if (!$vacancy) {
            header('Location: vacancies.php?error=not_found');
            exit;
        }
        break;
}

include 'includes/header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle me-2"></i><?php echo escape($message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fas fa-exclamation-triangle me-2"></i><?php echo escape($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($action == 'list'): ?>
    <!-- Lista de vacantes -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-briefcase me-2"></i>Vacantes de Empleo</h4>
        <a href="vacancies.php?action=create" class="btn btn-turpial">
            <i class="fas fa-plus me-2"></i>Nueva Vacante
        </a>
    </div>
    
    <!-- Filtros -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">División</label>
                    <select name="division" class="form-select">
                        <option value="">Todas</option>
                        <?php foreach ($divisions as $div): ?>
                            <option value="<?php echo $div['id']; ?>" 
                                    <?php echo ($_GET['division'] ?? '') == $div['id'] ? 'selected' : ''; ?>>
                                <?php echo escape($div['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Estado</label>
                    <select name="status" class="form-select">
                        <option value="">Todos</option>
                        <option value="1" <?php echo ($_GET['status'] ?? '') === '1' ? 'selected' : ''; ?>>Activas</option>
                        <option value="0" <?php echo ($_GET['status'] ?? '') === '0' ? 'selected' : ''; ?>>Inactivas</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="fas fa-search"></i> Filtrar
                    </button>
                    <a href="vacancies.php" class="btn btn-outline-secondary">
                        <i class="fas fa-times"></i> Limpiar
                    </a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Tabla de vacantes -->
    <div class="card">
        <div class="card-body">
            <?php if (empty($vacancies)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-briefcase fa-4x text-muted mb-3"></i>
                    <h5>No hay vacantes disponibles</h5>
                    <p class="text-muted">Comienza creando tu primera vacante de empleo.</p>
                    <a href="vacancies.php?action=create" class="btn btn-turpial">
                        <i class="fas fa-plus me-2"></i>Crear Vacante
                    </a>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Título</th>
                                <th>División/Categoría</th>
                                <th>Ubicación</th>
                                <th>Aplicaciones</th>
                                <th>Estado</th>
                                <th>Fecha</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($vacancies as $vacancy): ?>
                                <tr>
                                    <td>
                                        <div>
                                            <strong><?php echo escape($vacancy['title']); ?></strong>
                                            <?php if ($vacancy['is_featured']): ?>
                                                <span class="badge bg-warning ms-1">Destacada</span>
                                            <?php endif; ?>
                                            <br>
                                            <small class="text-muted"><?php echo escape($vacancy['employment_type']); ?></small>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            <?php echo escape($vacancy['division_name']); ?><br>
                                            <small class="text-muted"><?php echo escape($vacancy['category_name']); ?></small>
                                        </div>
                                    </td>
                                    <td><?php echo escape($vacancy['location']); ?></td>
                                    <td>
                                        <span class="badge bg-info"><?php echo $vacancy['application_count']; ?></span>
                                    </td>
                                    <td>
                                        <?php if ($vacancy['is_active']): ?>
                                            <span class="badge bg-success">Activa</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">Inactiva</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo formatDate($vacancy['created_at']); ?></td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <a href="vacancies.php?action=view&id=<?php echo $vacancy['id']; ?>" 
                                               class="btn btn-sm btn-outline-primary" title="Ver">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="vacancies.php?action=edit&id=<?php echo $vacancy['id']; ?>" 
                                               class="btn btn-sm btn-outline-warning" title="Editar">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="vacancies.php?toggle=1&id=<?php echo $vacancy['id']; ?>" 
                                               class="btn btn-sm btn-outline-info" title="Cambiar Estado">
                                                <i class="fas fa-toggle-on"></i>
                                            </a>
                                            <a href="applications.php?job=<?php echo $vacancy['id']; ?>" 
                                               class="btn btn-sm btn-outline-success" title="Ver Aplicaciones">
                                                <i class="fas fa-users"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

<?php elseif ($action == 'create' || $action == 'edit'): ?>
    <!-- Formulario de creación/edición -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4>
            <i class="fas fa-<?php echo $action == 'create' ? 'plus' : 'edit'; ?> me-2"></i>
            <?php echo $action == 'create' ? 'Crear' : 'Editar'; ?> Vacante
        </h4>
        <a href="vacancies.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-2"></i>Volver
        </a>
    </div>
    
    <div class="card">
        <div class="card-body">
            <form method="POST">
                <div class="row">
                    <div class="col-md-8">
                        <div class="mb-3">
                            <label for="title" class="form-label">Título de la Vacante *</label>
                            <input type="text" class="form-control" id="title" name="title" 
                                   value="<?php echo escape($vacancy['title'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="division_id" class="form-label">División *</label>
                                <select class="form-select" id="division_id" name="division_id" 
                                        onchange="loadCategories(this.value)" required>
                                    <option value="">Seleccionar...</option>
                                    <?php foreach ($divisions as $div): ?>
                                        <option value="<?php echo $div['id']; ?>" 
                                                <?php echo ($vacancy['division_id'] ?? '') == $div['id'] ? 'selected' : ''; ?>>
                                            <?php echo escape($div['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="category_id" class="form-label">Categoría *</label>
                                <select class="form-select" id="category_id" name="category_id" required>
                                    <option value="">Seleccionar...</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>" 
                                                <?php echo ($vacancy['category_id'] ?? '') == $cat['id'] ? 'selected' : ''; ?>>
                                            <?php echo escape($cat['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">Descripción *</label>
                            <textarea class="form-control" id="description" name="description" rows="4" required><?php echo escape($vacancy['description'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="requirements" class="form-label">Requisitos</label>
                            <textarea class="form-control" id="requirements" name="requirements" rows="4"><?php echo escape($vacancy['requirements'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="responsibilities" class="form-label">Responsabilidades</label>
                            <textarea class="form-control" id="responsibilities" name="responsibilities" rows="4"><?php echo escape($vacancy['responsibilities'] ?? ''); ?></textarea>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="employment_type" class="form-label">Tipo de Empleo</label>
                            <select class="form-select" id="employment_type" name="employment_type">
                                <option value="Tiempo Completo" <?php echo ($vacancy['employment_type'] ?? '') == 'Tiempo Completo' ? 'selected' : ''; ?>>Tiempo Completo</option>
                                <option value="Medio Tiempo" <?php echo ($vacancy['employment_type'] ?? '') == 'Medio Tiempo' ? 'selected' : ''; ?>>Medio Tiempo</option>
                                <option value="Contrato" <?php echo ($vacancy['employment_type'] ?? '') == 'Contrato' ? 'selected' : ''; ?>>Contrato</option>
                                <option value="Pasantía" <?php echo ($vacancy['employment_type'] ?? '') == 'Pasantía' ? 'selected' : ''; ?>>Pasantía</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="location" class="form-label">Ubicación</label>
                            <input type="text" class="form-control" id="location" name="location" 
                                   value="<?php echo escape($vacancy['location'] ?? ''); ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label for="salary_range" class="form-label">Rango Salarial</label>
                            <input type="text" class="form-control" id="salary_range" name="salary_range" 
                                   value="<?php echo escape($vacancy['salary_range'] ?? ''); ?>" 
                                   placeholder="Ej: $800 - $1,500">
                        </div>
                        
                        <div class="mb-3">
                            <label for="experience_required" class="form-label">Experiencia Requerida</label>
                            <input type="text" class="form-control" id="experience_required" name="experience_required" 
                                   value="<?php echo escape($vacancy['experience_required'] ?? ''); ?>" 
                                   placeholder="Ej: 2-3 años">
                        </div>
                        
                        <div class="mb-3">
                            <label for="education_required" class="form-label">Educación Requerida</label>
                            <input type="text" class="form-control" id="education_required" name="education_required" 
                                   value="<?php echo escape($vacancy['education_required'] ?? ''); ?>" 
                                   placeholder="Ej: Universitario">
                        </div>
                        
                        <div class="mb-3">
                            <label for="deadline" class="form-label">Fecha Límite</label>
                            <input type="date" class="form-control" id="deadline" name="deadline" 
                                   value="<?php echo $vacancy['deadline'] ?? ''; ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label for="max_applicants" class="form-label">Máx. Candidatos (0 = ilimitado)</label>
                            <input type="number" class="form-control" id="max_applicants" name="max_applicants" 
                                   value="<?php echo $vacancy['max_applicants'] ?? 0; ?>" min="0">
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="is_featured" name="is_featured" 
                                       <?php echo ($vacancy['is_featured'] ?? false) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="is_featured">
                                    Vacante Destacada
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between">
                    <a href="vacancies.php" class="btn btn-outline-secondary">
                        <i class="fas fa-times me-2"></i>Cancelar
                    </a>
                    <button type="submit" class="btn btn-turpial">
                        <i class="fas fa-save me-2"></i>
                        <?php echo $action == 'create' ? 'Crear' : 'Actualizar'; ?> Vacante
                    </button>
                </div>
            </form>
        </div>
    </div>

<?php elseif ($action == 'view'): ?>
    <!-- Vista de vacante -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-eye me-2"></i>Detalles de Vacante</h4>
        <div>
            <a href="vacancies.php?action=edit&id=<?php echo $vacancy['id']; ?>" class="btn btn-warning me-2">
                <i class="fas fa-edit me-2"></i>Editar
            </a>
            <a href="vacancies.php" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-2"></i>Volver
            </a>
        </div>
    </div>
    
    <div class="row">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header bg-turpial-gradient">
                    <h5 class="mb-0"><?php echo escape($vacancy['title']); ?></h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>División:</strong> <?php echo escape($vacancy['division_name']); ?><br>
                            <strong>Categoría:</strong> <?php echo escape($vacancy['category_name']); ?><br>
                            <strong>Ubicación:</strong> <?php echo escape($vacancy['location']); ?>
                        </div>
                        <div class="col-md-6">
                            <strong>Tipo:</strong> <?php echo escape($vacancy['employment_type']); ?><br>
                            <strong>Creada por:</strong> <?php echo escape($vacancy['created_by_name']); ?><br>
                            <strong>Fecha:</strong> <?php echo formatDate($vacancy['created_at']); ?>
                        </div>
                    </div>
                    
                    <h6>Descripción</h6>
                    <p><?php echo nl2br(escape($vacancy['description'])); ?></p>
                    
                    <?php if ($vacancy['requirements']): ?>
                        <h6>Requisitos</h6>
                        <p><?php echo nl2br(escape($vacancy['requirements'])); ?></p>
                    <?php endif; ?>
                    
                    <?php if ($vacancy['responsibilities']): ?>
                        <h6>Responsabilidades</h6>
                        <p><?php echo nl2br(escape($vacancy['responsibilities'])); ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">Información Adicional</h6>
                </div>
                <div class="card-body">
                    <?php if ($vacancy['salary_range']): ?>
                        <p><strong>Salario:</strong> <?php echo escape($vacancy['salary_range']); ?></p>
                    <?php endif; ?>
                    
                    <?php if ($vacancy['experience_required']): ?>
                        <p><strong>Experiencia:</strong> <?php echo escape($vacancy['experience_required']); ?></p>
                    <?php endif; ?>
                    
                    <?php if ($vacancy['education_required']): ?>
                        <p><strong>Educación:</strong> <?php echo escape($vacancy['education_required']); ?></p>
                    <?php endif; ?>
                    
                    <?php if ($vacancy['deadline']): ?>
                        <p><strong>Fecha Límite:</strong> <?php echo formatDate($vacancy['deadline']); ?></p>
                    <?php endif; ?>
                    
                    <p><strong>Estado:</strong> 
                        <?php if ($vacancy['is_active']): ?>
                            <span class="badge bg-success">Activa</span>
                        <?php else: ?>
                            <span class="badge bg-secondary">Inactiva</span>
                        <?php endif; ?>
                    </p>
                    
                    <?php if ($vacancy['is_featured']): ?>
                        <p><span class="badge bg-warning">Vacante Destacada</span></p>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card mt-3">
                <div class="card-header">
                    <h6 class="mb-0">Acciones</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="applications.php?job=<?php echo $vacancy['id']; ?>" class="btn btn-primary">
                            <i class="fas fa-users me-2"></i>Ver Aplicaciones
                        </a>
                        <a href="../job-detail.php?id=<?php echo $vacancy['id']; ?>" class="btn btn-outline-info" target="_blank">
                            <i class="fas fa-external-link-alt me-2"></i>Ver en Sitio Web
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php endif; ?>

<?php
if ($action == 'create' || $action == 'edit') {
    $additional_js = '
    <script>
    function loadCategories(divisionId) {
        const categorySelect = document.getElementById("category_id");
        
        // Limpiar opciones actuales
        categorySelect.innerHTML = "<option value=\"\">Seleccionar...</option>";
        
        if (divisionId) {
            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'; ?>