<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
require_once '../includes/auth.php';

check_role('profesor');

$user = get_logged_in_user();

// Get teacher
$stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
$stmt->execute([$user['id']]);
$teacher = $stmt->fetch();

if (!$teacher) {
    die('Teacher profile not found.');
}

$job_id = isset($_GET['job_id']) ? (int)$_GET['job_id'] : 0;
$job_info = null;

if ($job_id) {
    // Get job information
    $stmt = $pdo->prepare("SELECT j.*, c.company_name, car.name as career_name FROM jobs j JOIN companies c ON j.company_id = c.id LEFT JOIN careers car ON j.career_id = car.id WHERE j.id = ?");
    $stmt->execute([$job_id]);
    $job_info = $stmt->fetch();
}

$page_title = $job_info ? 'Postulantes para: ' . htmlspecialchars($job_info['title']) : 'Mis Alumnos';

$content = '';

if ($job_info) {
    // Show students related to this specific job
    $content .= '<div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Cargo: ' . htmlspecialchars($job_info['title']) . '</h3>
                    <div class="card-tools">
                        <span class="badge bg-success">' . htmlspecialchars($job_info['company_name']) . '</span>
                        <a href="jobs.php" class="btn btn-secondary btn-sm">Volver a las ofertas</a>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>Programa de Estudio:</strong> ' . htmlspecialchars($job_info['career_name'] ?: 'General') . '</p>
                            <p><strong>Lugar:</strong> ' . htmlspecialchars($job_info['location'] ?: 'Not specified') . '</p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>Sueldo:</strong> ' . ($job_info['salary'] ? 'S/. ' . number_format($job_info['salary'], 2) : 'Not specified') . '</p>
                            <p><strong>Tipo de Trabajo:</strong> ' . match($job_info['job_type']) {
                                'full-time' => 'Tiempo Completo',
                                'part-time' => 'Medio Tiempo',
                                'contract' => 'Contratado',
                                'internship' => 'Pasantia',
                                default => ucfirst($job_info['job_type'])
                            } . '</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Postulantes a esta Oferta</h3>
                </div>
                <div class="card-body">';

    // Get applicants who applied to this job
    $stmt = $pdo->prepare("SELECT a.*, u.id as user_id, u.first_name, u.last_name, u.email, c.name as career_name, a.applicant_type FROM applications a LEFT JOIN students st ON a.applicant_id = st.id AND a.applicant_type = 'student' LEFT JOIN graduates g ON a.applicant_id = g.id AND a.applicant_type = 'graduate' JOIN users u ON (st.user_id = u.id OR g.user_id = u.id) LEFT JOIN careers c ON (st.career_id = c.id OR g.career_id = c.id) WHERE a.job_id = ? ORDER BY a.applied_date DESC");
    $stmt->execute([$job_id]);
    $applied_students = $stmt->fetchAll();

    if (empty($applied_students)) {
        $content .= '<p class="text-muted">Nadie ha postulado a esta oferta todavía.</p>';
    } else {
        $content .= '<div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Nombre Completo</th>
                                    <th>Email</th>
                                    <th>Programa de Estudio</th>
                                    <th>Fecha de Postulación</th>
                                    <th>Estado</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>';
        foreach ($applied_students as $applicant) {
            $status_badge = match($applicant['status']) {
                'pending' => '<span class="badge bg-warning">Pendiente</span>',
                'reviewed' => '<span class="badge bg-info">Revisado</span>',
                'accepted' => '<span class="badge bg-success">Aceptado</span>',
                'rejected' => '<span class="badge bg-danger">Rechazado</span>',
                default => '<span class="badge bg-secondary">' . ucfirst($applicant['status']) . '</span>'
            };

            $applicant_type_label = match($applicant['applicant_type']) {
                'graduate' => ' (Egresado)',
                'student' => ' (Alumno)',
                default => ''
            };

            $content .= '<tr>
                            <td>' . htmlspecialchars($applicant['first_name'] . ' ' . $applicant['last_name']) . ' <small>' . $applicant_type_label . '</small></td>
                            <td>' . htmlspecialchars($applicant['email']) . '</td>
                            <td>' . htmlspecialchars($applicant['career_name'] ?: 'Not specified') . '</td>
                            <td>' . date('M d, Y H:i', strtotime($applicant['applied_date'])) . '</td>
                            <td>' . $status_badge . '</td>
                            <td>
                                <a href="resume.php?id=' . $applicant['user_id'] . '" class="btn btn-info btn-sm"><i class="fas fa-eye"></i> Ver</a>
                            </td>
                        </tr>';
        }
        $content .= '</tbody>
                        </table>
                    </div>';
    }

    $content .= '</div>
            </div>
        </div>
    </div>';

} else {
    // Show all students (general view)
    $content .= '<div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Todos los Alumnos</h3>
                    <div class="card-tools">
                        <a href="dashboard.php" class="btn btn-secondary btn-sm">Volver al Dashboard</a>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Nombre</th>
                                    <th>Email</th>
                                    <th>Programa/Especialidad</th>
                                    <th>Postulaciones</th>
                                    <th>Se unió</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>';

    $stmt = $pdo->query("SELECT st.*, u.id as user_id, u.first_name, u.last_name, u.email, u.created_at, c.name as career_name, COUNT(a.id) as app_count FROM students st JOIN users u ON st.user_id = u.id LEFT JOIN careers c ON st.career_id = c.id LEFT JOIN applications a ON st.id = a.applicant_id AND a.applicant_type = 'student' GROUP BY st.id ORDER BY u.first_name, u.last_name");
    while ($student = $stmt->fetch()) {
        $content .= '<tr>
                        <td>' . htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) . '</td>
                        <td>' . htmlspecialchars($student['email']) . '</td>
                        <td>' . htmlspecialchars($student['career_name'] ?: $student['major'] ?: 'Not specified') . '</td>
                        <td>' . $student['app_count'] . '</td>
                        <td>' . date('M d, Y', strtotime($student['created_at'])) . '</td>
                        <td>
                            <a href="resume.php?id=' . $student['user_id'] . '" class="btn btn-info btn-sm"><i class="fas fa-eye"></i> Ver</a>
                        </td>
                    </tr>';
    }

    $content .= '</tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>';
}

include '../includes/layout.php';
?>