<?php
/**
 * Formulario de aplicación a vacante - Frontend público
 * Turpial Airlines, C.A.
 */

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

// Verificar que se proporcione ID de vacante
if (!isset($_GET['job']) || !is_numeric($_GET['job'])) {
    header('Location: jobs.php');
    exit;
}

$job_id = (int)$_GET['job'];

// Obtener detalles de la vacante
$jobVacancy = new JobVacancy();
$job = $jobVacancy->getById($job_id);

if (!$job || !$job['is_active']) {
    header('Location: jobs.php?error=not_found');
    exit;
}

// Verificar si la vacante ha expirado
if ($job['deadline'] && strtotime($job['deadline']) < time()) {
    header('Location: job-detail.php?id=' . $job_id . '&error=expired');
    exit;
}

$page_title = 'Aplicar a ' . $job['title'];
$errors = [];
$success = false;

// Procesar formulario
if ($_POST) {
    $csrf_token = $_POST['csrf_token'] ?? '';
    
    if (!verifyCSRFToken($csrf_token)) {
        $errors[] = 'Token de seguridad inválido';
    } else {
        // Validar datos
        $full_name = cleanString($_POST['full_name'] ?? '');
        $email = cleanString($_POST['email'] ?? '');
        $phone = cleanString($_POST['phone'] ?? '');
        $address = cleanString($_POST['address'] ?? '');
        $city = cleanString($_POST['city'] ?? '');
        $country = cleanString($_POST['country'] ?? 'Venezuela');
        $education_level = cleanString($_POST['education_level'] ?? '');
        $years_experience = (int)($_POST['years_experience'] ?? 0);
        $current_position = cleanString($_POST['current_position'] ?? '');
        $cover_letter = cleanString($_POST['cover_letter'] ?? '');
        
        // Validaciones
        if (empty($full_name)) $errors[] = 'El nombre completo es requerido';
        if (empty($email) || !validateEmail($email)) $errors[] = 'Email válido es requerido';
        if (empty($phone)) $errors[] = 'El teléfono es requerido';
        if (empty($address)) $errors[] = 'La dirección es requerida';
        if (empty($city)) $errors[] = 'La ciudad es requerida';
        if (empty($education_level)) $errors[] = 'El nivel educativo es requerido';
        if (empty($cover_letter)) $errors[] = 'La carta de presentación es requerida';
        
        // Verificar duplicados
        $application = new Application();
        if ($application->checkDuplicateApplication($email, $job_id)) {
            $errors[] = 'Ya has aplicado a esta vacante anteriormente';
        }
        
        // Manejar archivo CV
        $cv_data = null;
        if (isset($_FILES['cv']) && $_FILES['cv']['error'] === UPLOAD_ERR_OK) {
            $cv_upload = uploadFile($_FILES['cv'], ALLOWED_FILE_TYPES, MAX_FILE_SIZE);
            if (!$cv_upload['success']) {
                $errors[] = 'Error en CV: ' . $cv_upload['message'];
            } else {
                $cv_data = $cv_upload;
            }
        }
        
        // Si no hay errores, guardar aplicación
        if (empty($errors)) {
            $application_data = [
                'job_vacancy_id' => $job_id,
                'full_name' => $full_name,
                'email' => $email,
                'phone' => $phone,
                'address' => $address,
                'city' => $city,
                'country' => $country,
                'education_level' => $education_level,
                'years_experience' => $years_experience,
                'current_position' => $current_position,
                'cover_letter' => $cover_letter,
                'cv_filename' => $cv_data ? $cv_data['original_name'] : null,
                'cv_path' => $cv_data ? $cv_data['path'] : null
            ];
            
            try {
                $application_id = $application->create($application_data);
                
                if ($application_id) {
                    // Redireccionar a página de éxito
                    header('Location: success.php?type=application&job=' . $job_id);
                    exit;
                } else {
                    $errors[] = 'Error al procesar la aplicación. Intenta nuevamente.';
                }
            } catch (Exception $e) {
                $errors[] = 'Error interno. Intenta nuevamente más tarde.';
            }
        }
    }
}

include 'includes/header.php';
?>

<!-- Breadcrumb -->
<nav aria-label="breadcrumb" class="bg-light py-3">
    <div class="container">
        <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item"><a href="index.php">Inicio</a></li>
            <li class="breadcrumb-item"><a href="jobs.php">Vacantes</a></li>
            <li class="breadcrumb-item"><a href="job-detail.php?id=<?php echo $job['id']; ?>"><?php echo escape($job['title']); ?></a></li>
            <li class="breadcrumb-item active">Aplicar</li>
        </ol>
    </div>
</nav>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <!-- Información de la vacante -->
            <div class="card mb-4">
                <div class="card-header bg-turpial-gradient">
                    <h4 class="mb-0">
                        <i class="fas fa-paper-plane me-2"></i>Aplicar a: <?php echo escape($job['title']); ?>
                    </h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p class="mb-1"><strong>División:</strong> <?php echo escape($job['division_name']); ?></p>
                            <p class="mb-1"><strong>Categoría:</strong> <?php echo escape($job['category_name']); ?></p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-1"><strong>Ubicación:</strong> <?php echo escape($job['location']); ?></p>
                            <p class="mb-1"><strong>Tipo:</strong> <?php echo escape($job['employment_type']); ?></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Mostrar errores -->
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <h6><i class="fas fa-exclamation-triangle me-2"></i>Se encontraron errores:</h6>
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo escape($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
            
            <!-- Formulario de aplicación -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-user-edit me-2"></i>Datos del Candidato</h5>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data" novalidate>
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        
                        <!-- Información Personal -->
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="full_name" class="form-label">Nombre Completo *</label>
                                <input type="text" class="form-control" id="full_name" name="full_name" 
                                       value="<?php echo escape($_POST['full_name'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="email" class="form-label">Email *</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo escape($_POST['email'] ?? ''); ?>" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="phone" class="form-label">Teléfono *</label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       value="<?php echo escape($_POST['phone'] ?? ''); ?>" 
                                       placeholder="+58-XXX-XXX-XXXX" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="city" class="form-label">Ciudad *</label>
                                <input type="text" class="form-control" id="city" name="city" 
                                       value="<?php echo escape($_POST['city'] ?? ''); ?>" required>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="address" class="form-label">Dirección *</label>
                            <textarea class="form-control" id="address" name="address" rows="2" required><?php echo escape($_POST['address'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="country" class="form-label">País</label>
                                <select class="form-select" id="country" name="country">
                                    <option value="Venezuela" <?php echo ($_POST['country'] ?? 'Venezuela') == 'Venezuela' ? 'selected' : ''; ?>>Venezuela</option>
                                    <option value="Colombia" <?php echo ($_POST['country'] ?? '') == 'Colombia' ? 'selected' : ''; ?>>Colombia</option>
                                    <option value="Perú" <?php echo ($_POST['country'] ?? '') == 'Perú' ? 'selected' : ''; ?>>Perú</option>
                                    <option value="Ecuador" <?php echo ($_POST['country'] ?? '') == 'Ecuador' ? 'selected' : ''; ?>>Ecuador</option>
                                    <option value="Otro" <?php echo ($_POST['country'] ?? '') == 'Otro' ? 'selected' : ''; ?>>Otro</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="education_level" class="form-label">Nivel Educativo *</label>
                                <select class="form-select" id="education_level" name="education_level" required>
                                    <option value="">Seleccionar...</option>
                                    <option value="Bachiller" <?php echo ($_POST['education_level'] ?? '') == 'Bachiller' ? 'selected' : ''; ?>>Bachiller</option>
                                    <option value="Técnico" <?php echo ($_POST['education_level'] ?? '') == 'Técnico' ? 'selected' : ''; ?>>Técnico</option>
                                    <option value="TSU" <?php echo ($_POST['education_level'] ?? '') == 'TSU' ? 'selected' : ''; ?>>TSU</option>
                                    <option value="Universitario" <?php echo ($_POST['education_level'] ?? '') == 'Universitario' ? 'selected' : ''; ?>>Universitario</option>
                                    <option value="Especialista" <?php echo ($_POST['education_level'] ?? '') == 'Especialista' ? 'selected' : ''; ?>>Especialista</option>
                                    <option value="Maestría" <?php echo ($_POST['education_level'] ?? '') == 'Maestría' ? 'selected' : ''; ?>>Maestría</option>
                                    <option value="Doctorado" <?php echo ($_POST['education_level'] ?? '') == 'Doctorado' ? 'selected' : ''; ?>>Doctorado</option>
                                </select>
                            </div>
                        </div>
                        
                        <!-- Experiencia Profesional -->
                        <hr>
                        <h6 class="mb-3"><i class="fas fa-briefcase me-2"></i>Experiencia Profesional</h6>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="years_experience" class="form-label">Años de Experiencia</label>
                                <select class="form-select" id="years_experience" name="years_experience">
                                    <option value="0" <?php echo ($_POST['years_experience'] ?? 0) == 0 ? 'selected' : ''; ?>>Sin experiencia</option>
                                    <option value="1" <?php echo ($_POST['years_experience'] ?? 0) == 1 ? 'selected' : ''; ?>>1 año</option>
                                    <option value="2" <?php echo ($_POST['years_experience'] ?? 0) == 2 ? 'selected' : ''; ?>>2 años</option>
                                    <option value="3" <?php echo ($_POST['years_experience'] ?? 0) == 3 ? 'selected' : ''; ?>>3 años</option>
                                    <option value="4" <?php echo ($_POST['years_experience'] ?? 0) == 4 ? 'selected' : ''; ?>>4 años</option>
                                    <option value="5" <?php echo ($_POST['years_experience'] ?? 0) == 5 ? 'selected' : ''; ?>>5 años</option>
                                    <option value="10" <?php echo ($_POST['years_experience'] ?? 0) >= 10 ? 'selected' : ''; ?>>Más de 5 años</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="current_position" class="form-label">Cargo Actual</label>
                                <input type="text" class="form-control" id="current_position" name="current_position" 
                                       value="<?php echo escape($_POST['current_position'] ?? ''); ?>" 
                                       placeholder="Ej: Desarrollador, Piloto, etc.">
                            </div>
                        </div>
                        
                        <!-- Carta de Presentación -->
                        <div class="mb-3">
                            <label for="cover_letter" class="form-label">Carta de Presentación *</label>
                            <textarea class="form-control" id="cover_letter" name="cover_letter" rows="6" 
                                      placeholder="Expresa tu motivación para aplicar a esta vacante, tus fortalezas y por qué eres el candidato ideal..." 
                                      required><?php echo escape($_POST['cover_letter'] ?? ''); ?></textarea>
                            <div class="form-text">Mínimo 100 caracteres. Sé específico sobre tu interés en la posición.</div>
                        </div>
                        
                        <!-- Currículum -->
                        <div class="mb-4">
                            <label for="cv" class="form-label">Currículum Vitae (Opcional)</label>
                            <input type="file" class="form-control" id="cv" name="cv" 
                                   accept=".pdf,.doc,.docx">
                            <div class="form-text">
                                Formatos aceptados: PDF, DOC, DOCX. Tamaño máximo: 5MB.
                            </div>
                        </div>
                        
                        <!-- Términos y Condiciones -->
                        <div class="mb-4">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="terms" required>
                                <label class="form-check-label" for="terms">
                                    Acepto que mis datos sean procesados por Turpial Airlines para fines de reclutamiento y selección. *
                                </label>
                            </div>
                        </div>
                        
                        <!-- Botones -->
                        <div class="d-grid gap-2 d-md-flex justify-content-md-between">
                            <a href="job-detail.php?id=<?php echo $job['id']; ?>" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Volver a la Vacante
                            </a>
                            <button type="submit" class="btn btn-turpial btn-lg">
                                <i class="fas fa-paper-plane me-2"></i>Enviar Aplicación
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Sidebar con información adicional -->
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>Información Importante</h6>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled">
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            Proceso de selección transparente
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            Respuesta en máximo 15 días
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            Datos protegidos y confidenciales
                        </li>
                        <li class="mb-2">
                            <i class="fas fa-check text-success me-2"></i>
                            Ambiente de trabajo profesional
                        </li>
                    </ul>
                    
                    <hr>
                    
                    <h6>Contacto RRHH</h6>
                    <p class="small text-muted mb-1">
                        <i class="fas fa-envelope me-1"></i> <?php echo getSetting('company_email'); ?>
                    </p>
                    <p class="small text-muted">
                        <i class="fas fa-phone me-1"></i> <?php echo getSetting('company_phone'); ?>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Script para validación del formulario -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form');
    const coverLetter = document.getElementById('cover_letter');
    
    // Validación de carta de presentación
    coverLetter.addEventListener('input', function() {
        const length = this.value.length;
        const minLength = 100;
        
        if (length < minLength) {
            this.setCustomValidity(`Mínimo ${minLength} caracteres. Actual: ${length}`);
        } else {
            this.setCustomValidity('');
        }
    });
    
    // Validación antes de enviar
    form.addEventListener('submit', function(e) {
        const terms = document.getElementById('terms');
        
        if (!terms.checked) {
            e.preventDefault();
            alert('Debes aceptar los términos y condiciones');
            return false;
        }
        
        if (coverLetter.value.length < 100) {
            e.preventDefault();
            alert('La carta de presentación debe tener al menos 100 caracteres');
            coverLetter.focus();
            return false;
        }
    });
});
</script>

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