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

check_role('administrador');

$user = get_logged_in_user();

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

if (!$job_id) {
    header('Location: jobs.php');
    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 = ?");
$stmt->execute([$job_id]);
$job = $stmt->fetch();

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

// Increment view count (only for admin viewing active jobs)
if ($job['status'] === 'active') {
    $stmt = $pdo->prepare("UPDATE jobs SET view_count = view_count + 1 WHERE id = ?");
    $stmt->execute([$job_id]);
}

// Get job statistics
$stats = [];

// Total applications
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM applications WHERE job_id = ?");
$stmt->execute([$job_id]);
$stats['total_applications'] = $stmt->fetch()['total'];

// Pending applications
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM applications WHERE job_id = ? AND status = 'pending'");
$stmt->execute([$job_id]);
$stats['pending_applications'] = $stmt->fetch()['total'];

// Accepted applications
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM applications WHERE job_id = ? AND status = 'accepted'");
$stmt->execute([$job_id]);
$stats['accepted_applications'] = $stmt->fetch()['total'];

// Recent applications
$recent_applications = $pdo->prepare("SELECT a.*, u.first_name, u.last_name, u.email, c.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 c ON (st.career_id = c.id OR g.career_id = c.id) WHERE a.job_id = ? ORDER BY a.applied_date DESC LIMIT 10");
$recent_applications->execute([$job_id]);
$applications_list = $recent_applications->fetchAll(PDO::FETCH_ASSOC);

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

$content = '
<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">' . match($job['status']) {
                            'active' => '<span class="badge badge-success">Activo</span>',
                            'inactive' => '<span class="badge badge-secondary">Inactivo</span>',
                            'filled' => '<span class="badge badge-info">Completado</span>',
                            default => '<span class="badge badge-secondary">' . ucfirst($job['status']) . '</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>Postulantes</b> <a class="float-right"><span class="badge badge-success">' . $stats['total_applications'] . '</span></a>
                    </li>
                </ul>
                <div class="text-center">
                    <a href="' . route_url('admin_jobs') . '" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Volver</a>
                </div>
            </div>
        </div>
        <p></p>
        <!-- Statistics Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Estadistica de Aplicaciones</h3>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3>' . $stats['total_applications'] . '</h3>
                                <p>Total</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3>' . $stats['pending_applications'] . '</h3>
                                <p>Pendientes</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row text-center mt-2">
                    <div class="col-12">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3>' . $stats['accepted_applications'] . '</h3>
                                <p>Acceptados</p>
                            </div>
                        </div>
                    </div>
                </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">' . match($job['job_type']) {
                            'full-time' => 'Tiempo Completo',
                            'part-time' => 'Medio Tiempo',
                            'contract' => 'Contratado',
                            'internship' => 'Pasantia',
                            default => 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">' . match($job['status']) {
                            'active' => '<span class="badge badge-success">Activo</span>',
                            'inactive' => '<span class="badge badge-secondary">Inactivo</span>',
                            'filled' => '<span class="badge badge-info">Completado</span>',
                            default => '<span class="badge badge-secondary">' . ucfirst($job['status']) . '</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>' : '') . '
                ' . ($job['link'] ? '<hr>
                <strong><i class="fas fa-link mr-1"></i> Enlace</strong>
                <p class="text-muted"><a href="' . htmlspecialchars($job['link']) . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($job['link']) . ' <i class="fas fa-external-link-alt"></i></a></p>' : '') . '
            </div>
        </div>

        <!-- Recent Applications -->
        <p></p>
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Postulantes</h3>
                <div class="card-tools">
                    <span class="badge bg-info">' . $stats['total_applications'] . ' Total de Postulntes </span>
                </div>
            </div>
            <div class="card-body">
                ' . (empty($applications_list) ? '<p class="text-muted">No applications yet.</p>' : '') . '';

foreach ($applications_list as $application) {
    $status_badge = match($application['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($application['status']) . '</span>'
    };

    // Get the user ID for the applicant (works for both students and graduates)
    $applicant_user_id = null;
    if ($application['applicant_type'] == 'student') {
        $stmt = $pdo->prepare("SELECT user_id FROM students WHERE id = ?");
        $stmt->execute([$application['applicant_id']]);
        $applicant_user_id = $stmt->fetch()['user_id'];
    } else {
        $stmt = $pdo->prepare("SELECT user_id FROM graduates WHERE id = ?");
        $stmt->execute([$application['applicant_id']]);
        $applicant_user_id = $stmt->fetch()['user_id'];
    }

    $content .= '<div class="d-flex justify-content-between align-items-center border-bottom py-2">
                    <div>
                        <strong>' . htmlspecialchars($application['first_name'] . ' ' . $application['last_name']) . ' (' . match($application['applicant_type']) {
                            'graduate' => 'Egresado',
                            'student' => 'Alumno',
                            default => ucfirst($application['applicant_type'])
                        } . ')</strong><br>
                        <small class="text-muted">' . htmlspecialchars($application['email']) . ' - ' . htmlspecialchars($application['major'] ?: 'No major specified') . '</small><br>
                        <small class="text-muted">Aplico ' . date('d/m/Y H:i', strtotime($application['applied_date'])) . '</small>
                    </div>
                    <div class="text-right">
                        ' . $status_badge . '<br>
                        <a href="' . url('admin/resume.php?id=' . $applicant_user_id) . '" class="btn btn-sm btn-outline-primary mt-1">Ver Detalles</a>
                    </div>
                </div>';
}

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

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