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

$page_title = 'Gestión de Aplicaciones';

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

// Verificar autenticación
requireLogin();

$application = new Application();
$jobVacancy = new JobVacancy();
$division = new Division();

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

// Procesar acciones POST
if ($_POST) {
    switch ($action) {
        case 'update_status':
            $status = $_POST['status'];
            $notes = cleanString($_POST['notes'] ?? '');
            
            try {
                $application->updateStatus($id, $status, $notes);
                $message = 'Estado de aplicación actualizado';
            } catch (Exception $e) {
                $error = 'Error al actualizar: ' . $e->getMessage();
            }
            break;
    }
}

// Manejar acciones GET
if (isset($_GET['delete']) && $id) {
    $application->delete($id);
    $message = 'Aplicación eliminada';
    header('Location: applications.php');
    exit;
}

// Obtener datos según la acción
switch ($action) {
    case 'list':
        $filters = [];
        if (isset($_GET['job'])) $filters['job_vacancy_id'] = (int)$_GET['job'];
        if (isset($_GET['status'])) $filters['status'] = $_GET['status'];
        if (isset($_GET['division'])) $filters['division_id'] = (int)$_GET['division'];
        if (isset($_GET['date_from'])) $filters['date_from'] = $_GET['date_from'];
        if (isset($_GET['date_to'])) $filters['date_to'] = $_GET['date_to'];
        
        $applications = $application->getAll($filters);
        $divisions = $division->getAll();
        $jobs = $jobVacancy->getActiveVacancies();
        break;
        
    case 'view':
        if (!$id) {
            header('Location: applications.php');
            exit;
        }
        $app = $application->getById($id);
        if (!$app) {
            header('Location: applications.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 aplicaciones -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-file-alt me-2"></i>Aplicaciones Recibidas</h4>
        <div>
            <span class="badge bg-info fs-6"><?php echo count($applications); ?> aplicaciones</span>
        </div>
    </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">Vacante</label>
                    <select name="job" class="form-select">
                        <option value="">Todas las vacantes</option>
                        <?php foreach ($jobs as $job): ?>
                            <option value="<?php echo $job['id']; ?>" 
                                    <?php echo ($_GET['job'] ?? '') == $job['id'] ? 'selected' : ''; ?>>
                                <?php echo escape($job['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Estado</label>
                    <select name="status" class="form-select">
                        <option value="">Todos</option>
                        <option value="Pendiente" <?php echo ($_GET['status'] ?? '') === 'Pendiente' ? 'selected' : ''; ?>>Pendiente</option>
                        <option value="En Revisión" <?php echo ($_GET['status'] ?? '') === 'En Revisión' ? 'selected' : ''; ?>>En Revisión</option>
                        <option value="Entrevista" <?php echo ($_GET['status'] ?? '') === 'Entrevista' ? 'selected' : ''; ?>>Entrevista</option>
                        <option value="Seleccionado" <?php echo ($_GET['status'] ?? '') === 'Seleccionado' ? 'selected' : ''; ?>>Seleccionado</option>
                        <option value="Rechazado" <?php echo ($_GET['status'] ?? '') === 'Rechazado' ? 'selected' : ''; ?>>Rechazado</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Desde</label>
                    <input type="date" name="date_from" class="form-control" 
                           value="<?php echo $_GET['date_from'] ?? ''; ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Hasta</label>
                    <input type="date" name="date_to" class="form-control" 
                           value="<?php echo $_GET['date_to'] ?? ''; ?>">
                </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="applications.php" class="btn btn-outline-secondary">
                        <i class="fas fa-times"></i> Limpiar
                    </a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Tabla de aplicaciones -->
    <div class="card">
        <div class="card-body">
            <?php if (empty($applications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-inbox fa-4x text-muted mb-3"></i>
                    <h5>No hay aplicaciones</h5>
                    <p class="text-muted">No se encontraron aplicaciones con los filtros seleccionados.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Candidato</th>
                                <th>Vacante</th>
                                <th>Fecha Aplicación</th>
                                <th>Estado</th>
                                <th>Experiencia</th>
                                <th>CV</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($applications as $app): ?>
                                <tr>
                                    <td>
                                        <div>
                                            <strong><?php echo escape($app['full_name']); ?></strong><br>
                                            <small class="text-muted">
                                                <i class="fas fa-envelope me-1"></i><?php echo escape($app['email']); ?><br>
                                                <i class="fas fa-phone me-1"></i><?php echo escape($app['phone']); ?><br>
                                                <i class="fas fa-map-marker-alt me-1"></i><?php echo escape($app['city']); ?>
                                            </small>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            <?php echo escape($app['job_title']); ?><br>
                                            <small class="text-muted"><?php echo escape($app['category_name']); ?></small>
                                        </div>
                                    </td>
                                    <td><?php echo formatDateTime($app['application_date']); ?></td>
                                    <td>
                                        <span class="badge status-<?php echo strtolower(str_replace(' ', '', $app['status'])); ?>">
                                            <?php echo escape($app['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div>
                                            <?php echo $app['years_experience']; ?> años<br>
                                            <small class="text-muted"><?php echo escape($app['current_position']); ?></small>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($app['cv_filename']): ?>
                                            <a href="../uploads/<?php echo basename($app['cv_path']); ?>" 
                                               target="_blank" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-file-pdf"></i>
                                            </a>
                                        <?php else: ?>
                                            <span class="text-muted">N/A</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <a href="applications.php?action=view&id=<?php echo $app['id']; ?>" 
                                               class="btn btn-sm btn-outline-primary" title="Ver">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <div class="dropdown">
                                                <button class="btn btn-sm btn-outline-success dropdown-toggle" 
                                                        type="button" data-bs-toggle="dropdown" title="Cambiar Estado">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="#" onclick="updateStatus(<?php echo $app['id']; ?>, 'En Revisión')">En Revisión</a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="updateStatus(<?php echo $app['id']; ?>, 'Entrevista')">Entrevista</a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="updateStatus(<?php echo $app['id']; ?>, 'Seleccionado')">Seleccionado</a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="updateStatus(<?php echo $app['id']; ?>, 'Rechazado')">Rechazado</a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

<?php elseif ($action == 'view'): ?>
    <!-- Vista detallada de aplicación -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-user me-2"></i>Detalle de Aplicación</h4>
        <a href="applications.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left me-2"></i>Volver
        </a>
    </div>
    
    <div class="row">
        <div class="col-lg-8">
            <!-- Datos del candidato -->
            <div class="card mb-4">
                <div class="card-header bg-turpial-gradient">
                    <h5 class="mb-0"><i class="fas fa-user me-2"></i>Datos del Candidato</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>Nombre:</strong> <?php echo escape($app['full_name']); ?></p>
                            <p><strong>Email:</strong> <?php echo escape($app['email']); ?></p>
                            <p><strong>Teléfono:</strong> <?php echo escape($app['phone']); ?></p>
                            <p><strong>Dirección:</strong> <?php echo escape($app['address']); ?></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>Ciudad:</strong> <?php echo escape($app['city']); ?></p>
                            <p><strong>País:</strong> <?php echo escape($app['country']); ?></p>
                            <p><strong>Nivel Educativo:</strong> <?php echo escape($app['education_level']); ?></p>
                            <p><strong>Años de Experiencia:</strong> <?php echo $app['years_experience']; ?></p>
                        </div>
                    </div>
                    
                    <?php if ($app['current_position']): ?>
                        <p><strong>Cargo Actual:</strong> <?php echo escape($app['current_position']); ?></p>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Vacante aplicada -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-briefcase me-2"></i>Vacante Aplicada</h6>
                </div>
                <div class="card-body">
                    <h5><?php echo escape($app['job_title']); ?></h5>
                    <p class="text-muted"><?php echo escape($app['division_name']); ?> - <?php echo escape($app['category_name']); ?></p>
                    <p><?php echo nl2br(escape($app['job_description'])); ?></p>
                </div>
            </div>
            
            <!-- Carta de presentación -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-comment me-2"></i>Carta de Presentación</h6>
                </div>
                <div class="card-body">
                    <p><?php echo nl2br(escape($app['cover_letter'])); ?></p>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- Estado y acciones -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-cog me-2"></i>Estado y Acciones</h6>
                </div>
                <div class="card-body">
                    <form method="POST" action="applications.php?action=update_status&id=<?php echo $app['id']; ?>">
                        <div class="mb-3">
                            <label class="form-label">Estado Actual</label>
                            <select name="status" class="form-select">
                                <option value="Pendiente" <?php echo $app['status'] == 'Pendiente' ? 'selected' : ''; ?>>Pendiente</option>
                                <option value="En Revisión" <?php echo $app['status'] == 'En Revisión' ? 'selected' : ''; ?>>En Revisión</option>
                                <option value="Entrevista" <?php echo $app['status'] == 'Entrevista' ? 'selected' : ''; ?>>Entrevista</option>
                                <option value="Seleccionado" <?php echo $app['status'] == 'Seleccionado' ? 'selected' : ''; ?>>Seleccionado</option>
                                <option value="Rechazado" <?php echo $app['status'] == 'Rechazado' ? 'selected' : ''; ?>>Rechazado</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Notas</label>
                            <textarea name="notes" class="form-control" rows="3" 
                                      placeholder="Observaciones del proceso..."><?php echo escape($app['notes']); ?></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-turpial w-100">
                            <i class="fas fa-save me-2"></i>Actualizar Estado
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Información de aplicación -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>Información</h6>
                </div>
                <div class="card-body">
                    <p><strong>Fecha Aplicación:</strong><br><?php echo formatDateTime($app['application_date']); ?></p>
                    
                    <?php if ($app['reviewed_by_name']): ?>
                        <p><strong>Revisado por:</strong><br><?php echo escape($app['reviewed_by_name']); ?></p>
                        <p><strong>Fecha Revisión:</strong><br><?php echo formatDateTime($app['reviewed_at']); ?></p>
                    <?php endif; ?>
                    
                    <?php if ($app['cv_filename']): ?>
                        <p><strong>Currículum:</strong><br>
                        <a href="../uploads/<?php echo basename($app['cv_path']); ?>" 
                           target="_blank" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-file-pdf me-1"></i><?php echo escape($app['cv_filename']); ?>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Acciones adicionales -->
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-tools me-2"></i>Acciones</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="mailto:<?php echo escape($app['email']); ?>" class="btn btn-outline-primary">
                            <i class="fas fa-envelope me-2"></i>Enviar Email
                        </a>
                        <a href="tel:<?php echo escape($app['phone']); ?>" class="btn btn-outline-success">
                            <i class="fas fa-phone me-2"></i>Llamar
                        </a>
                        <a href="applications.php?delete=1&id=<?php echo $app['id']; ?>" 
                           class="btn btn-outline-danger" 
                           onclick="return confirm('¿Estás seguro de eliminar esta aplicación?')">
                            <i class="fas fa-trash me-2"></i>Eliminar
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php endif; ?>

<?php
if ($action == 'list') {
    $additional_js = '
    <script>
    function updateStatus(applicationId, status) {
        if (confirm("¿Cambiar estado a: " + status + "?")) {
            const form = document.createElement("form");
            form.method = "POST";
            form.action = "applications.php?action=update_status&id=" + applicationId;
            
            const statusInput = document.createElement("input");
            statusInput.type = "hidden";
            statusInput.name = "status";
            statusInput.value = status;
            
            form.appendChild(statusInput);
            document.body.appendChild(form);
            form.submit();
        }
    }
    </script>
    ';
}
?>

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