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

check_role('profesor');

$user = get_logged_in_user();

$job_id = $_GET['id'] ?? 0;
if (!$job_id) {
    header('Location: dashboard.php');
    exit;
}

// Get job details
$stmt = $pdo->prepare("SELECT j.*, c.company_name, c.logo, c.description as company_description, c.website, c.phone, c.address, 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 = $stmt->fetch();

if (!$job) {
    header('Location: dashboard.php');
    exit;
}

// Get applications count
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM applications WHERE job_id = ?");
$stmt->execute([$job_id]);
$app_count = $stmt->fetch()['count'];

$page_title = 'Detalles de la Oferta - ' . htmlspecialchars($job['title']);

$content = '
<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">' . htmlspecialchars($job['title']) . '</h3>
                <div class="card-tools">
                    <a href="' . route_url('teacher_jobs') . '" class="btn btn-secondary btn-sm">Volver a Ofertas</a>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-12">
                        <h4>Información de la Oferta</h4>
                        <table class="table table-bordered">
                            <tr>
                                <th width="200">Cargo</th>
                                <td>' . htmlspecialchars($job['title']) . '</td>
                            </tr>
                            <tr>
                                <th>Programa de Estudio</th>
                                <td>' . htmlspecialchars($job['career_name'] ?: 'General') . '</td>
                            </tr>
                            <tr>
                                <th>Tipo de Trabajo</th>
                                <td>' . match($job['job_type']) {
                                    'full-time' => 'Tiempo Completo',
                                    'part-time' => 'Medio Tiempo',
                                    'contract' => 'Contratado',
                                    'internship' => 'Pasantia',
                                    default => ucfirst($job['job_type'])
                                } . '</td>
                            </tr>
                            <tr>
                                <th>Sueldo</th>
                                <td>' . ($job['salary'] ? 'S/. ' . number_format($job['salary'], 2) : 'No especificado') . '</td>
                            </tr>
                            <tr>
                                <th>Lugar</th>
                                <td>' . htmlspecialchars($job['location'] ?: 'No especificado') . '</td>
                            </tr>
                            <tr>
                                <th>Fecha de Publicación</th>
                                <td>' . date('d/m/Y H:i', strtotime($job['posted_date'])) . '</td>
                            </tr>
                            <tr>
                                <th>Fecha de Expiración</th>
                                <td>' . ($job['expiration_date'] ? date('d/m/Y', strtotime($job['expiration_date'])) : 'No expira') . '</td>
                            </tr>
                            <tr>
                                <th>Estado</th>
                                <td><span class="badge bg-' . ($job['status'] == 'active' ? 'success' : 'secondary') . '">' . match($job['status']) {
                                    'active' => 'Activo',
                                    'inactive' => 'Inactivo',
                                    'filled' => 'Completado',
                                    default => ucfirst($job['status'])
                                } . '</span></td>
                            </tr>
                            <tr>
                                <th>Postulaciones</th>
                                <td>' . $app_count . ' postulantes</td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div class="row mt-4">
                    <div class="col-md-12">
                        <h4>Descripción</h4>
                        <div class="bg-light p-3 rounded">
                            ' . nl2br(htmlspecialchars($job['description'])) . '
                        </div>
                    </div>
                </div>

                ' . ($job['requirements'] ? '<div class="row mt-4">
                    <div class="col-md-12">
                        <h4>Requerimientos</h4>
                        <div class="bg-light p-3 rounded">
                            ' . nl2br(htmlspecialchars($job['requirements'])) . '
                        </div>
                    </div>
                </div>' : '') . '
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Información de la Empresa</h4>
            </div>
            <div class="card-body text-center">
                ' . ($job['logo'] ? '<img src="' . url($job['logo']) . '" class="img-fluid mb-3" style="max-height: 100px;" alt="Company Logo"><br>' : '') . '
                <h5>' . htmlspecialchars($job['company_name']) . '</h5>
                ' . ($job['company_description'] ? '<p class="text-muted">' . htmlspecialchars(substr($job['company_description'], 0, 150)) . '...</p>' : '') . '
                <hr>
                <div class="text-start">
                    ' . ($job['website'] ? '<p><strong>Website:</strong> <a href="' . htmlspecialchars($job['website']) . '" target="_blank">' . htmlspecialchars($job['website']) . '</a></p>' : '') . '
                    ' . ($job['phone'] ? '<p><strong>Teléfono:</strong> ' . htmlspecialchars($job['phone']) . '</p>' : '') . '
                    ' . ($job['address'] ? '<p><strong>Dirección:</strong> ' . htmlspecialchars($job['address']) . '</p>' : '') . '
                </div>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-header">
                <h4 class="card-title">Acciones Rápidas</h4>
            </div>
            <div class="card-body">
                <p><strong>Postulaciones:</strong> ' . $app_count . '</p>
                <p><strong>Estado:</strong> ' . ucfirst($job['status']) . '</p>
                <div class="mt-3">
                    <span class="text-muted">Vista de Profesor - Use esta información para guiar a los estudiantes</span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Postulantes para esta Oferta</h4>
                <div class="card-tools">
                    <span class="badge badge-info">' . $app_count . ' Postulaciones Totales</span>
                </div>
            </div>
            <div class="card-body">';

if ($app_count > 0) {
    $content .= '<table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Nombre del Postulante</th>
                            <th>Programa/Especialidad</th>
                            <th>Fecha de Postulación</th>
                            <th>Estado</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>';

    $stmt = $pdo->prepare("
        SELECT a.*, u.id as user_id, u.first_name, u.last_name, car.name as major, 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 car ON (st.career_id = car.id OR g.career_id = car.id)
        WHERE a.job_id = ? ORDER BY a.applied_date DESC
    ");
    $stmt->execute([$job_id]);

    while ($row = $stmt->fetch()) {
        $status_badge = match($row['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($row['status']) . '</span>'
        };

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

        $content .= '<tr>
            <td>' . htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) . '<small>' . $applicant_type_label . '</small></td>
            <td>' . htmlspecialchars($row['major'] ?: 'No especificado') . '</td>
            <td>' . date('d/m/Y H:i', strtotime($row['applied_date'])) . '</td>
            <td>' . $status_badge . '</td>
            <td><a href="' . route_url('teacher_resume', ['id' => $row['user_id']]) . '" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye"></i> Ver CV</a></td>
        </tr>';
    }

    $content .= '</tbody>
                </table>';
} else {
    $content .= '<div class="alert alert-info">
                    <i class="icon fas fa-info"></i> Aún no se han recibido postulaciones para esta oferta.
                </div>';
}

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

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