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

check_role('egresado');

$user = get_logged_in_user();

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

if (!$graduate) {
    die('Graduate profile not found.');
}

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

if (!$job_id) {
    header('Location: /graduate/jobs');
    exit;
}

// Get job details
$stmt = $pdo->prepare("SELECT j.*, c.company_name, c.logo as company_logo, c.website as company_website, u.first_name, u.last_name, u.email as contact_email, car.name as career_name FROM jobs j JOIN companies c ON j.company_id = c.id JOIN users u ON c.user_id = u.id LEFT JOIN careers car ON j.career_id = car.id WHERE j.id = ? AND j.status = 'active'");
$stmt->execute([$job_id]);
$job = $stmt->fetch();

if (!$job) {
    header('Location: /graduate/jobs');
    exit;
}

// Increment view count
$stmt = $pdo->prepare("UPDATE jobs SET view_count = view_count + 1 WHERE id = ?");
$stmt->execute([$job_id]);

// Check if already applied
    $app_stmt = $pdo->prepare("SELECT id, status FROM applications WHERE job_id = ? AND applicant_id = ? AND applicant_type = 'graduate'");
    $app_stmt->execute([$job_id, $graduate['id']]);
$application = $app_stmt->fetch();

$page_title = 'Detalles del Trabajo - ' . htmlspecialchars($job['title']);

$content = '
<div class="row mb-3">
    <div class="col-12">
        <a href="' . route_url('graduate_jobs') . '" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left mr-2"></i>Volver a Ofertas de Trabajo
        </a>
    </div>
</div>
<div class="row">
    <div class="col-md-4">
        <div class="card card-primary card-outline">
            <div class="card-body box-profile">
                <div class="text-center">
                    ' . ($job['company_logo'] ? '<img class="profile-user-img img-fluid img-circle" src="' . url($job['company_logo']) . '" alt="Company Logo" style="max-height: 100px;">' : '<div class="profile-user-img img-fluid img-circle bg-light d-flex align-items-center justify-content-center" style="width: 100px; height: 100px;"><i class="fas fa-building fa-2x text-muted"></i></div>') . '
                </div>
                <h3 class="profile-username text-center">' . htmlspecialchars($job['title']) . '</h3>
                <p class="text-muted text-center">' . htmlspecialchars($job['company_name']) . '</p>
                <ul class="list-group list-group-unbordered mb-3">
                    <li class="list-group-item">
                        <b>Estado</b> <a class="float-right"><span class="badge badge-success">Activo</span></a>
                    </li>
                    <li class="list-group-item">
                        <b>Publicado</b> <a class="float-right">' . date('d/m/Y', strtotime($job['posted_date'])) . '</a>
                    </li>
                    <li class="list-group-item">
                        <b>Estado de postulación</b> <a class="float-right">' . ($application ? '<span class="badge ' . match($application['status']) {
                            'pending' => 'bg-warning',
                            'reviewed' => 'bg-info',
                            'accepted' => 'bg-success',
                            'rejected' => 'bg-danger',
                            default => 'bg-secondary'
                        } . '">' . match($application['status']) {
                            'pending' => 'Pendiente',
                            'reviewed' => 'Revisado',
                            'accepted' => 'Aceptado',
                            'rejected' => 'Rechazado',
                            default => ucfirst($application['status'])
                        } . '</span>' : 'No aplicó') . '</a>
                    </li>
                </ul>
                <div class="text-center">
                    
                    ' . ($job['link'] ? '<a href="' . htmlspecialchars($job['link']) . '" target="_blank" rel="noopener noreferrer" class="btn btn-warning btn-sm mr-1"><i class="fas fa-external-link-alt"></i> Enlace</a>' : ($application ? '<span class="text-muted">Ya aplicaste a esta oferta</span>' : '<a href="/graduate/apply?job_id=' . $job_id . '" class="btn btn-success btn-sm"><i class="fas fa-paper-plane"></i> Aplicar Ahora</a>')) . '
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Información del Trabajo</h3>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-sm-6">
                        <strong><i class="fas fa-briefcase mr-1"></i> Título del Trabajo</strong>
                        <p class="text-muted">' . htmlspecialchars($job['title']) . '</p>
                        <hr>
                        <strong><i class="fas fa-building mr-1"></i> Empresa</strong>
                        <p class="text-muted">' . htmlspecialchars($job['company_name']) . '</p>
                        <hr>
                        <strong><i class="fas fa-user mr-1"></i> Contacto</strong>
                        <p class="text-muted">' . htmlspecialchars($job['first_name'] . ' ' . $job['last_name']) . '</p>
                        <hr>
                        <strong><i class="fas fa-graduation-cap mr-1"></i> Programa de Estudio</strong>
                        <p class="text-muted">' . htmlspecialchars($job['career_name'] ?: 'General') . '</p>
                        <hr>
                        <strong><i class="fas fa-map-marker-alt mr-1"></i> Lugar</strong>
                        <p class="text-muted">' . htmlspecialchars($job['location'] ?: 'Not specified') . '</p>
                    </div>
                    <div class="col-sm-6">
                        <strong><i class="fas fa-dollar-sign mr-1"></i> Sueldo</strong>
                        <p class="text-muted">' . ($job['salary'] ? 'S/. ' . number_format($job['salary'], 2) : 'Not specified') . '</p>
                        <hr>
                        <strong><i class="fas fa-clock mr-1"></i> Tipo de Trabajo</strong>
                        <p class="text-muted">' . ucfirst($job['job_type']) . '</p>
                        <hr>
                        <strong><i class="fas fa-calendar mr-1"></i> Fecha de Publicación</strong>
                        <p class="text-muted">' . date('d/m/Y', strtotime($job['posted_date'])) . '</p>
                        <hr>
                        <strong><i class="fas fa-calendar-times mr-1"></i> Fecha de Expiración</strong>
                        <p class="text-muted">' . ($job['expiration_date'] ? date('d/m/Y', strtotime($job['expiration_date'])) : 'Sin expiración') . '</p>
                        <hr>
                        <strong><i class="fas fa-info-circle mr-1"></i> Estado</strong>
                        <p class="text-muted"><span class="badge badge-success">Active</span></p>
                    </div>
                </div>
                <hr>
                <strong><i class="fas fa-align-left mr-1"></i> Descripción</strong>
                <p class="text-muted">' . nl2br(htmlspecialchars($job['description'])) . '</p>
                ' . ($job['requirements'] ? '<hr>
                <strong><i class="fas fa-list-check mr-1"></i> Requerimientos</strong>
                <p class="text-muted">' . nl2br(htmlspecialchars($job['requirements'])) . '</p>' : '') . '
            </div>
        </div>
    </div>
</div>';

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