<?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.');
}

// Get graduate's applications statistics
$stmt = $pdo->prepare("SELECT
    COUNT(*) as total_applications,
    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_applications,
    COUNT(CASE WHEN status = 'reviewed' THEN 1 END) as reviewed_applications,
    COUNT(CASE WHEN status = 'accepted' THEN 1 END) as accepted_applications,
    COUNT(CASE WHEN status = 'rejected' THEN 1 END) as rejected_applications
FROM applications WHERE applicant_id = ? AND applicant_type = 'graduate'");
$stmt->execute([$graduate['id']]);
$application_stats = $stmt->fetch();

// Calculate profile completion percentage
$profile_completion = 0;
$total_fields = 0;

// Check basic user info (required)
$user_fields = ['first_name', 'last_name', 'email'];
foreach ($user_fields as $field) {
    $total_fields++;
    if (!empty($user[$field])) $profile_completion++;
}

// Check graduate profile fields
$graduate_fields = ['dni', 'birth_date', 'address', 'phone', 'graduation_year', 'current_position', 'company'];
foreach ($graduate_fields as $field) {
    $total_fields++;
    if (!empty($graduate[$field])) $profile_completion++;
}

// Check if career is selected
$total_fields++;
if (!empty($graduate['career_id'])) $profile_completion++;

// Check if photo is uploaded
$total_fields++;
if (!empty($user['photo'])) $profile_completion++;

// Check languages (at least one)
$stmt = $pdo->prepare("SELECT COUNT(*) FROM graduate_languages WHERE graduate_id = ?");
$stmt->execute([$graduate['id']]);
$has_languages = $stmt->fetchColumn() > 0;
$total_fields++;
if ($has_languages) $profile_completion++;

// Check trainings (at least one)
$stmt = $pdo->prepare("SELECT COUNT(*) FROM graduate_trainings WHERE graduate_id = ?");
$stmt->execute([$graduate['id']]);
$has_trainings = $stmt->fetchColumn() > 0;
$total_fields++;
if ($has_trainings) $profile_completion++;

// Check work experience (at least one)
$stmt = $pdo->prepare("SELECT COUNT(*) FROM graduate_work_experience WHERE graduate_id = ?");
$stmt->execute([$graduate['id']]);
$has_experience = $stmt->fetchColumn() > 0;
$total_fields++;
if ($has_experience) $profile_completion++;

$completion_percentage = $total_fields > 0 ? round(($profile_completion / $total_fields) * 100) : 0;

// Get jobs for graduate's career
$stmt = $pdo->prepare("SELECT COUNT(*) FROM jobs WHERE status = 'active' AND career_id = ?");
$stmt->execute([$graduate['career_id']]);
$career_jobs = $stmt->fetchColumn();

// Get recommended jobs (5 most recent jobs from graduate's career, not applied to yet)
$stmt = $pdo->prepare("
    SELECT j.*, c.company_name, c.logo as company_logo, 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.status = 'active'
    AND (j.expiration_date IS NULL OR j.expiration_date >= CURDATE())
    AND j.career_id = ?
    AND j.id NOT IN (
        SELECT job_id FROM applications
        WHERE applicant_id = ? AND applicant_type = 'graduate'
    )
    ORDER BY j.posted_date DESC
    LIMIT 5
");
$stmt->execute([$graduate['career_id'], $graduate['id']]);
$recommended_jobs = $stmt->fetchAll();

// Get most viewed jobs from graduate's career
$stmt = $pdo->prepare("
    SELECT j.title, j.view_count, c.company_name
    FROM jobs j
    JOIN companies c ON j.company_id = c.id
    WHERE j.career_id = ? AND j.status = 'active'
    AND (j.expiration_date IS NULL OR j.expiration_date >= CURDATE())
    ORDER BY j.view_count DESC
    LIMIT 10
");
$stmt->execute([$graduate['career_id']]);
$most_viewed_jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$page_title = 'Dashboard de Egresado';

$content = '
<div class="row">
    <div class="col-lg-3 col-6">
        <div class="small-box text-bg-danger">
            <div class="inner">
                <h3><a href="' . route_url('graduate_jobs') . '" class="text-white text-decoration-none">' . $career_jobs . '</a></h3>
                <p><a href="' . route_url('graduate_jobs') . '" class="text-white text-decoration-none">Total de Ofertas</a></p>
            </div>
            <div class="icon">

            </div>
        </div>
    </div>
    <div class="col-lg-3 col-6">
        <div class="small-box text-bg-info">
            <div class="inner">
                <h3>' . $application_stats['total_applications'] . '</h3>
                <p>Total de Postulaciones</p>
            </div>
            <div class="icon">

            </div>
        </div>
    </div>
    <div class="col-lg-3 col-6">
        <div class="small-box text-bg-success">
            <div class="inner">
                <h3>' . $application_stats['accepted_applications'] . '</h3>
                <p>Postulaciones Aceptadas</p>
            </div>
            <div class="icon">

            </div>
        </div>
    </div>
    <div class="col-lg-3 col-6">
        <div class="small-box text-bg-warning">
            <div class="inner">
                <h3>' . $application_stats['pending_applications'] . '</h3>
                <p>Postulaciones Pendientes</p>
            </div>
            <div class="icon">

            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Mi Perfil</h3>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="text-center">
                            <div class="chart-container" style="position: relative; width: 120px; height: 120px; margin: 0 auto;">
                                <canvas id="profileCompletionChart" style="max-width: 100%; max-height: 100%;"></canvas>
                                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 18px; font-weight: bold; color: #495057;">
                                    ' . $completion_percentage . '%
                                </div>
                            </div>
                            <p class="mt-2 mb-1"><strong>Perfil Completado</strong></p>
                            <small class="text-muted">' . $profile_completion . ' de ' . $total_fields . ' campos completados</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h5>Accesos Rápidos</h5>
                        <div class="d-grid gap-2">
                            <a href="' . route_url('graduate_profile') . '" class="btn btn-primary btn-sm">
                                <i class="fas fa-user-edit"></i> Editar Perfil
                            </a>
                            <a href="' . route_url('graduate_languages') . '" class="btn btn-info btn-sm">
                                <i class="fas fa-language"></i> Idiomas
                            </a>
                            <a href="' . route_url('graduate_trainings') . '" class="btn btn-success btn-sm">
                                <i class="fas fa-graduation-cap"></i> Capacitación
                            </a>
                            <a href="' . route_url('graduate_work_experience') . '" class="btn btn-warning btn-sm">
                                <i class="fas fa-briefcase"></i> Experiencia Laboral
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Estado de Postulaciones</h3>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="text-center">
                            <div class="chart-container" style="position: relative; width: 120px; height: 120px; margin: 0 auto;">
                                <canvas id="applicationsChart" style="max-width: 100%; max-height: 100%;"></canvas>
                            </div>
                            <p class="mt-2 mb-1"><strong>Postulaciones</strong></p>
                            <small class="text-muted">Total: ' . $application_stats['total_applications'] . '</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h5>Resumen</h5>
                        <div class="mb-2">
                            <span class="badge badge-success">Aceptadas: ' . $application_stats['accepted_applications'] . '</span>
                        </div>
                        <div class="mb-2">
                            <span class="badge badge-warning">Pendientes: ' . $application_stats['pending_applications'] . '</span>
                        </div>
                        <div class="mb-2">
                            <span class="badge badge-danger">Rechazadas: ' . $application_stats['rejected_applications'] . '</span>
                        </div>
                        <div class="mb-2">
                            <span class="badge badge-info">Revisadas: ' . $application_stats['reviewed_applications'] . '</span>
                        </div>
                        <div class="mt-3">
                            <a href="' . route_url('graduate_applications') . '" class="btn btn-primary btn-sm btn-block">
                                <i class="fas fa-list"></i> Ver Todas las Postulaciones
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mt-3">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Ofertas Más Vistas de tu Carrera</h3>
            </div>
            <div class="card-body">
                <canvas id="mostViewedChart" style="height: 200px;"></canvas>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Ofertas Recomendadas</h3>
            </div>
            <div class="card-body">
                ' . (empty($recommended_jobs) ? '<p class="text-muted">No hay ofertas recomendadas disponibles en este momento.</p>' : '') . '';

$display_jobs = array_slice($recommended_jobs, 0, 5);
foreach ($display_jobs as $job) {
    $company_logo = $job['company_logo'] ? '<img src="' . url($job['company_logo']) . '" class="img-fluid" style="max-height: 40px;" alt="Company Logo">' : '<i class="fas fa-building text-muted"></i>';

    $content .= '<div class="d-flex align-items-center border-bottom py-2">
                    <div class="flex-shrink-0 mr-3">
                        ' . $company_logo . '
                    </div>
                    <div class="flex-grow-1">
                        <strong class="text-truncate d-block" style="max-width: 200px;" title="' . htmlspecialchars($job['title']) . '">' . htmlspecialchars($job['title']) . '</strong>
                        <small class="text-muted">' . htmlspecialchars($job['company_name']) . '</small>
                    </div>
                    <div class="flex-shrink-0">
                        <a href="' . route_url('graduate_view_job', ['id' => $job['id']]) . '" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-eye"></i>
                        </a>
                    </div>
                </div>';
}

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // Profile Completion Donut Chart
    const profileCompletionCtx = document.getElementById("profileCompletionChart").getContext("2d");
    const completionPercentage = ' . $completion_percentage . ';
    const remainingPercentage = 100 - completionPercentage;

    new Chart(profileCompletionCtx, {
        type: "doughnut",
        data: {
            datasets: [{
                data: [completionPercentage, remainingPercentage],
                backgroundColor: [
                    "#007bff", // Primary blue for completed
                    "#e9ecef"  // Light gray for remaining
                ],
                borderWidth: 0,
                cutout: "70%" // Creates the donut effect
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    enabled: false
                }
            }
        }
    });

    // Applications Status Donut Chart
    const applicationsCtx = document.getElementById("applicationsChart").getContext("2d");
    const totalApplications = ' . $application_stats['total_applications'] . ';
    const acceptedApplications = ' . $application_stats['accepted_applications'] . ';
    const pendingApplications = ' . $application_stats['pending_applications'] . ';
    const rejectedApplications = ' . $application_stats['rejected_applications'] . ';
    const reviewedApplications = ' . $application_stats['reviewed_applications'] . ';

    // Calculate percentages
    const acceptedPercent = totalApplications > 0 ? Math.round((acceptedApplications / totalApplications) * 100) : 0;
    const pendingPercent = totalApplications > 0 ? Math.round((pendingApplications / totalApplications) * 100) : 0;
    const rejectedPercent = totalApplications > 0 ? Math.round((rejectedApplications / totalApplications) * 100) : 0;
    const reviewedPercent = totalApplications > 0 ? Math.round((reviewedApplications / totalApplications) * 100) : 0;

    new Chart(applicationsCtx, {
        type: "doughnut",
        data: {
            datasets: [{
                data: [acceptedPercent, pendingPercent, rejectedPercent, reviewedPercent],
                backgroundColor: [
                    "#28a745", // Green for accepted
                    "#ffc107", // Yellow for pending
                    "#dc3545", // Red for rejected
                    "#17a2b8"  // Blue for reviewed
                ],
                borderWidth: 0,
                cutout: "70%"
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const labels = ["Aceptadas", "Pendientes", "Rechazadas", "Revisadas"];
                            const values = [' . $application_stats['accepted_applications'] . ', ' . $application_stats['pending_applications'] . ', ' . $application_stats['rejected_applications'] . ', ' . $application_stats['reviewed_applications'] . '];
                            return labels[context.dataIndex] + ": " + values[context.dataIndex];
                        }
                    }
                }
            }
        }
    });

    // Most Viewed Jobs Bar Chart
    const mostViewedCtx = document.getElementById("mostViewedChart").getContext("2d");
    const mostViewedData = ' . json_encode($most_viewed_jobs) . ';
    new Chart(mostViewedCtx, {
        type: "bar",
        data: {
            labels: mostViewedData.map(item => {
                // Truncate long titles
                const title = item.title;
                return title.length > 20 ? title.substring(0, 20) + "..." : title;
            }),
            datasets: [{
                label: "Vistas",
                data: mostViewedData.map(item => item.view_count),
                backgroundColor: "rgba(0, 123, 255, 0.6)",
                borderColor: "#007bff",
                borderWidth: 1,
                borderRadius: 4,
                borderSkipped: false,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                },
                x: {
                    ticks: {
                        maxRotation: 45,
                        minRotation: 45
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        title: function(context) {
                            return mostViewedData[context[0].dataIndex].title;
                        },
                        label: function(context) {
                            const job = mostViewedData[context.dataIndex];
                            return [
                                "Vistas: " + job.view_count,
                                "Empresa: " + job.company_name
                            ];
                        }
                    }
                }
            }
        }
    });
});
</script>';

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