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

check_role('alumno');

$user = get_logged_in_user();

// Get student profile for the logged-in user
$stmt = $pdo->prepare("SELECT * FROM students WHERE user_id = ?");
$stmt->execute([$user['id']]);
$student = $stmt->fetch();

// Get student's languages
$stmt = $pdo->prepare("SELECT * FROM student_languages WHERE student_id = ? ORDER BY created_at DESC");
$stmt->execute([$student['id'] ?? null]);
$student_languages = $stmt->fetchAll();

// Get student's trainings
$stmt = $pdo->prepare("SELECT * FROM student_trainings WHERE student_id = ? ORDER BY start_date DESC");
$stmt->execute([$student['id'] ?? null]);
$student_trainings = $stmt->fetchAll();

// Get student's work experience
$stmt = $pdo->prepare("SELECT * FROM student_work_experience WHERE student_id = ? ORDER BY start_date DESC");
$stmt->execute([$student['id'] ?? null]);
$student_experience = $stmt->fetchAll();

// Get career information
$stmt = $pdo->prepare("SELECT c.name as career_name FROM careers c WHERE c.id = ?");
$stmt->execute([$student['career_id'] ?? null]);
$career = $stmt->fetch();

// Generate PDF Resume
if (isset($_GET['download'])) {
    generatePDF($user, $student, $student_languages, $student_trainings, $student_experience, $career);
    exit;
}

$page_title = 'Mi Resumen';

$content = '
<div class="row">
    <div class="col-md-12">
        <div class="card card-modern">
            <div class="card-header bg-gradient-primary text-white">
                <h3 class="card-title mb-0">
                    <i class="fas fa-file-alt mr-2"></i>Mi Resumen Profesional
                </h3>
                <div class="card-tools">
                    <div class="stats-badge">
                        <i class="fas fa-language text-info mr-1"></i>
                        <span class="badge badge-light">' . count($student_languages) . ' Idiomas</span>
                        <i class="fas fa-graduation-cap text-success ml-2 mr-1"></i>
                        <span class="badge badge-light">' . count($student_trainings) . ' Capacitaciones</span>
                        <i class="fas fa-briefcase text-warning ml-2 mr-1"></i>
                        <span class="badge badge-light">' . count($student_experience) . ' Experiencias</span>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <!-- Profile Photo Section -->
                    <div class="col-lg-3 col-md-4 mb-4">
                        <div class="profile-photo-section">
                            <div class="text-center">
                                <div class="photo-container">
                                    <img src="' . ((isset($user['photo']) && $user['photo']) ? '../' . htmlspecialchars($user['photo']) : '../assets/img/avatar.png') . '" alt="Graduate Photo" class="profile-photo">
                                    ' . ((isset($user['photo']) && $user['photo']) ? '<div class="photo-status"><i class="fas fa-check-circle text-success"></i> Foto incluida en PDF</div>' : '<div class="photo-status"><i class="fas fa-exclamation-triangle text-warning"></i> <a href="' . route_url('student_profile') . '" class="text-decoration-none">Subir foto</a></div>') . '
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Personal Information Section -->
                    <div class="col-lg-4 col-md-8 mb-4">
                        <div class="info-section">
                            <h5 class="section-title">
                                <i class="fas fa-user-circle text-primary mr-2"></i>Información Personal
                            </h5>
                            <div class="info-grid">
                                <div class="info-item">
                                    <span class="info-label">Nombre:</span>
                                    <span class="info-value">' . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) . '</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">Email:</span>
                                    <span class="info-value">' . htmlspecialchars($user['email']) . '</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">Programa de Estudio:</span>
                                    <span class="info-value">' . htmlspecialchars($career['career_name'] ?? 'No especificado') . '</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">DNI:</span>
                                    <span class="info-value">' . htmlspecialchars($student['dni'] ?? 'No especificado') . '</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">Fecha de Nacimiento:</span>
                                    <span class="info-value">' . ($student['birth_date'] ? date('d/m/Y', strtotime($student['birth_date'])) : 'No especificado') . '</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">Dirección:</span>
                                    <span class="info-value">' . htmlspecialchars($student['address'] ?? 'No especificado') . '</span>
                                </div>
                                <div class="info-item">
                                    <span class="info-label">Año de Egreso:</span>
                                    <span class="info-value">' . htmlspecialchars($student['graduation_year'] ?? 'No especificado') . '</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Certificates Section -->
                    <div class="col-lg-5 col-md-12">
                        <div class="certificates-section">
                            <!-- Languages -->
                            <div class="certificate-block">
                                <h6 class="certificate-title">
                                    <i class="fas fa-language text-info mr-2"></i>Idiomas
                                    <span class="badge badge-info ml-2">' . count($student_languages) . '</span>
                                </h6>
                                <div class="certificate-list">';
if (count($student_languages) > 0) {
    foreach ($student_languages as $lang) {
        if ($lang['certificate_file']) {
            $content .= '<a href="../' . htmlspecialchars($lang['certificate_file']) . '" target="_blank" class="btn btn-sm btn-outline-info mb-2 mr-2">
                            <i class="fas fa-eye mr-1"></i>' . htmlspecialchars($lang['language_name']) . '
                         </a>';
        }
    }
} else {
    $content .= '<p class="text-muted small mb-0">No hay idiomas registrados</p>';
}

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

                            <!-- Trainings -->
                            <div class="certificate-block">
                                <h6 class="certificate-title">
                                    <i class="fas fa-graduation-cap text-success mr-2"></i>Capacitaciones
                                    <span class="badge badge-success ml-2">' . count($student_trainings) . '</span>
                                </h6>
                                <div class="certificate-list">';
if (count($student_trainings) > 0) {
    foreach ($student_trainings as $training) {
        if ($training['certificate_file']) {
            $content .= '<a href="../' . htmlspecialchars($training['certificate_file']) . '" target="_blank" class="btn btn-sm btn-outline-success mb-2 mr-2">
                            <i class="fas fa-eye mr-1"></i>' . htmlspecialchars($training['training_name']) . '
                         </a>';
        }
    }
} else {
    $content .= '<p class="text-muted small mb-0">No hay capacitaciones registradas</p>';
}

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

                            <!-- Work Experience -->
                            <div class="certificate-block">
                                <h6 class="certificate-title">
                                    <i class="fas fa-briefcase text-warning mr-2"></i>Experiencia Laboral
                                    <span class="badge badge-warning ml-2">' . count($student_experience) . '</span>
                                </h6>
                                <div class="certificate-list">';
if (count($student_experience) > 0) {
    foreach ($student_experience as $exp) {
        if ($exp['certificate_file']) {
            $content .= '<a href="../' . htmlspecialchars($exp['certificate_file']) . '" target="_blank" class="btn btn-sm btn-outline-warning mb-2 mr-2">
                            <i class="fas fa-eye mr-1"></i>' . htmlspecialchars($exp['job_title']) . '
                         </a>';
        }
    }
} else {
    $content .= '<p class="text-muted small mb-0">No hay experiencias laborales registradas</p>';
}

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

                <!-- Professional Summary Section -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="summary-section">
                            <h5 class="section-title">
                                <i class="fas fa-file-alt text-primary mr-2"></i>Resumen Profesional
                            </h5>
                            <div class="summary-content">
                                ' . (trim($student['resume'] ?? '') ? nl2br(htmlspecialchars($student['resume'])) : '<p class="text-muted">No hay resumen profesional registrado. <a href="' . route_url('student_profile') . '">Agregar resumen</a></p>') . '
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card-footer bg-light">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="action-buttons">
                        <a href="' . route_url('student_dashboard') . '" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left mr-2"></i>Volver
                        </a>
                    </div>
                    <div class="download-section">
                        <a href="resume.php?download=1" class="btn btn-success btn-lg">
                            <i class="fas fa-file-pdf mr-2"></i>Generar & Descargar PDF
                        </a>
                        <small class="text-muted ml-2">El PDF incluirá toda tu información profesional</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>';

$content .= '
<style>
/* Modern Resume Card Styling */
.card-modern {
    border: none;
    border-radius: 20px;
    box-shadow: 0 10px 40px rgba(121, 183, 145, 0.15);
    overflow: hidden;
    background: linear-gradient(145deg, #ffffff, var(--mint-cream));
    position: relative;
}
.card-modern::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, var(--cambridge-blue), var(--celadon));
}
.card-modern .card-header {
    background: #9BABBF !important;
    border: none;
    padding: 2rem 1.5rem 1.5rem;
    position: relative;
}
.card-modern .card-header::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60%;
    height: 3px;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 2px;
}
.card-modern .card-body {
    padding: 2rem 1.5rem;
    background: linear-gradient(180deg, rgba(237, 244, 237, 0.3), rgba(255, 255, 255, 0.8));
}
.card-modern .card-footer {
    border: none;
    padding: 1.5rem;
    background: var(--mint-cream);
    border-top: 2px solid var(--celadon);
}
.profile-photo-section {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}
.photo-container {
    position: relative;
    display: inline-block;
}
.profile-photo {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid var(--celadon);
    box-shadow: 0 8px 25px rgba(121, 183, 145, 0.2);
    transition: all 0.3s ease;
}
.profile-photo:hover {
    transform: scale(1.05);
    box-shadow: 0 12px 35px rgba(121, 183, 145, 0.3);
}
.photo-status {
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%);
    background: white;
    padding: 0.25rem 0.75rem;
    border-radius: 15px;
    font-size: 0.75rem;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    white-space: nowrap;
}
.info-section {
    height: 100%;
    display: flex;
    flex-direction: column;
}
.section-title {
    color: var(--caput-mortuum);
    font-weight: 600;
    margin-bottom: 1.5rem;
    font-size: 1.1rem;
    border-bottom: 2px solid var(--celadon);
    padding-bottom: 0.5rem;
}
.info-grid {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
}
.info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem;
    background: rgba(237, 244, 237, 0.3);
    border-radius: 8px;
    border-left: 3px solid var(--celadon);
    transition: all 0.3s ease;
}
.info-item:hover {
    background: rgba(237, 244, 237, 0.5);
    transform: translateX(2px);
}
.info-label {
    font-weight: 600;
    color: var(--caput-mortuum);
    font-size: 0.875rem;
}
.info-value {
    color: var(--black-bean);
    font-weight: 500;
    text-align: right;
    flex: 1;
    margin-left: 1rem;
}
.certificates-section {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}
.certificate-block {
    background: rgba(237, 244, 237, 0.2);
    border-radius: 12px;
    padding: 1rem;
    border: 1px solid var(--celadon);
    transition: all 0.3s ease;
}
.certificate-block:hover {
    background: rgba(237, 244, 237, 0.4);
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(121, 183, 145, 0.1);
}
.certificate-title {
    color: var(--caput-mortuum);
    font-weight: 600;
    margin-bottom: 0.75rem;
    font-size: 1rem;
}
.certificate-list {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
}
.summary-section {
    background: rgba(237, 244, 237, 0.2);
    border-radius: 12px;
    padding: 1.5rem;
    border: 1px solid var(--celadon);
}
.summary-content {
    margin-top: 1rem;
    line-height: 1.6;
}
.stats-badge {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    flex-wrap: wrap;
}
.stats-badge .badge {
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    font-weight: 500;
}
@media (max-width: 768px) {
    .card-modern .card-header,
    .card-modern .card-body,
    .card-modern .card-footer {
        padding: 1rem;
    }
    .profile-photo {
        width: 120px;
        height: 120px;
    }
    .info-grid {
        gap: 0.5rem;
    }
    .info-item {
        padding: 0.5rem;
        flex-direction: column;
        align-items: flex-start;
    }
    .info-value {
        margin-left: 0;
        margin-top: 0.25rem;
        text-align: left;
    }
    .certificates-section {
        gap: 1rem;
    }
    .certificate-block {
        padding: 0.75rem;
    }
}
</style>';

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

function generatePDF($user, $student, $languages, $trainings, $experience, $career) {
    // Create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // Set document information
    $pdf->SetCreator('Bolsa de Trabajo System');
    $pdf->SetAuthor($user['first_name'] . ' ' . $user['last_name']);
    $pdf->SetTitle('CV - ' . $user['first_name'] . ' ' . $user['last_name']);
    $pdf->SetSubject('Professional Resume');

    // Remove default header/footer
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);

    // Set margins
    $pdf->SetMargins(15, 15, 15);

    // Set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, 15);

    // Add a page
    $pdf->AddPage();

    // Set font
    $pdf->SetFont('helvetica', '', 10);

    // Header - Photo and Name/Contact Info
    if ($user['photo'] && file_exists('../' . $user['photo'])) {
        // Add photo (positioned on the left)
        $pdf->Image('../' . $user['photo'], 15, 15, 30, 30, '', '', '', false, 300, '', false, false, 0, false, false, false);

        // Name (positioned to the right of photo)
        $pdf->SetXY(50, 13);
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->Cell(0, 8, $user['first_name'] . ' ' . $user['last_name'], 0, 1);

        // Contact info aligned with the name
        $pdf->SetFont('helvetica', '', 10);
        $pdf->SetXY(50, 21); // Align with the name line (moved up 2 points)
        $pdf->Cell(0, 5, $user['email'], 0, 1);

        if ($student['phone']) {
            $pdf->SetXY(50, 26); // Moved up 2 points
            $pdf->Cell(0, 5, 'Celular: ' . $student['phone'], 0, 1);
        }
        if ($student['address']) {
            $current_y = 26; // Moved up 2 points from 28
            if ($student['phone']) $current_y += 5;
            $pdf->SetXY(50, $current_y);
            $pdf->MultiCell(0, 10, 'Dirección: ' . $student['address'], 0, 'L');
        }
        $pdf->Ln(5);
    } else {
        // No photo - center the name and contact info
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->Cell(0, 10, $user['first_name'] . ' ' . $user['last_name'], 0, 1, 'C');
        $pdf->SetFont('helvetica', '', 10);
        $pdf->Cell(0, 5, $user['email'], 0, 1, 'C');
        if ($student['phone']) {
            $pdf->Cell(0, 5, 'Phone: ' . $student['phone'], 0, 1, 'C');
        }
        if ($student['address']) {
            $pdf->MultiCell(0, 5, 'Address: ' . $student['address'], 0, 'C');
        }
        $pdf->Ln(5);
    }

    // Professional Summary
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'RESUMEN PROFESIONAL', 0, 1);
    $pdf->SetFont('helvetica', '', 10);

    // Use the resume field from students table, or fallback to auto-generated summary
    $summary = $student['resume'];
    if (empty(trim($summary))) {
        // Fallback to auto-generated summary if resume field is empty
        $summary = 'Professional ' . ($career['career_name'] ?? 'graduate') . ' with expertise in their field. ';
        if (count($languages) > 0) {
            $summary .= 'Multilingual with proficiency in ' . count($languages) . ' language(s). ';
        }
        if (count($trainings) > 0) {
            $summary .= 'Completed ' . count($trainings) . ' professional training program(s). ';
        }
        if (count($experience) > 0) {
            $summary .= 'Brings ' . count($experience) . ' work experience(s) to contribute to organizational success.';
        }
    }

    $pdf->MultiCell(0, 5, $summary, 0, 'L');
    $pdf->Ln(3);

    // Languages Section
    if (count($languages) > 0) {
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'IDIOMAS', 0, 1);
        $pdf->SetFont('helvetica', '', 10);

        foreach ($languages as $lang) {
            $lang_info = $lang['language_name'];
            if ($lang['proficiency_level']) {
                $lang_info .= ' (' . $lang['proficiency_level'] . ')';
            }
            if ($lang['reading_level'] || $lang['writing_level'] || $lang['speaking_level']) {
                $skills = [];
                if ($lang['reading_level']) $skills[] = 'R: ' . $lang['reading_level'];
                if ($lang['writing_level']) $skills[] = 'W: ' . $lang['writing_level'];
                if ($lang['speaking_level']) $skills[] = 'S: ' . $lang['speaking_level'];
                $lang_info .= ' - ' . implode(', ', $skills);
            }
            $pdf->Cell(0, 5, '• ' . $lang_info, 0, 1);
        }
        $pdf->Ln(3);
    }

    // Education & Training Section
    if (count($trainings) > 0) {
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'CAPACITACIONES', 0, 1);
        $pdf->SetFont('helvetica', '', 10);

        foreach ($trainings as $training) {
            $pdf->SetFont('helvetica', 'B', 10);
            $pdf->Cell(0, 5, $training['training_name'], 0, 1);

            $pdf->SetFont('helvetica', 'I', 9);
            $institution = $training['institution'] ?: 'Not specified';
            $type = ucfirst($training['training_type']);
            $pdf->Cell(0, 4, $institution . ' - ' . $type, 0, 1);

            if ($training['start_date'] || $training['end_date']) {
                $dates = '';
                if ($training['start_date']) $dates .= date('M Y', strtotime($training['start_date']));
                if ($training['end_date']) $dates .= ' - ' . date('M Y', strtotime($training['end_date']));
                $pdf->Cell(0, 4, $dates, 0, 1);
            }

            if ($training['description']) {
                $pdf->SetFont('helvetica', '', 9);
                $pdf->MultiCell(0, 4, $training['description'], 0, 'L');
            }

            if ($training['skills_acquired']) {
                $pdf->SetFont('helvetica', '', 9);
                $pdf->Cell(0, 4, 'Skills: ' . $training['skills_acquired'], 0, 1);
            }

            $pdf->Ln(2);
        }
        $pdf->Ln(3);
    }

    // Work Experience Section
    if (count($experience) > 0) {
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'EXPERIENCIA LABORAL', 0, 1);
        $pdf->SetFont('helvetica', '', 10);

        foreach ($experience as $exp) {
            $pdf->SetFont('helvetica', 'B', 10);
            $pdf->Cell(0, 5, $exp['job_title'], 0, 1);

            $pdf->SetFont('helvetica', 'I', 9);
            $company = $exp['company_name'];
            $type = ucfirst($exp['employment_type']);
            $location = $exp['location'] ? ' - ' . $exp['location'] : '';
            $pdf->Cell(0, 4, $company . ' (' . $type . ')' . $location, 0, 1);

            // Dates
            $dates = '';
            if ($exp['start_date']) $dates .= date('M Y', strtotime($exp['start_date']));
            if ($exp['current_job']) {
                $dates .= ' - Present';
            } elseif ($exp['end_date']) {
                $dates .= ' - ' . date('M Y', strtotime($exp['end_date']));
            }
            $pdf->Cell(0, 4, $dates, 0, 1);

            if ($exp['description']) {
                $pdf->SetFont('helvetica', '', 9);
                $pdf->MultiCell(0, 4, $exp['description'], 0, 'L');
            }

            if ($exp['achievements']) {
                $pdf->SetFont('helvetica', '', 9);
                $pdf->Cell(0, 4, 'Achievements: ' . $exp['achievements'], 0, 1);
            }

            if ($exp['skills_used']) {
                $pdf->SetFont('helvetica', '', 9);
                $pdf->Cell(0, 4, 'Skills Used: ' . $exp['skills_used'], 0, 1);
            }

            $pdf->Ln(2);
        }
        $pdf->Ln(3);
    }

    // Skills Section
    $all_skills = [];

    // Collect skills from trainings
    foreach ($trainings as $training) {
        if ($training['skills_acquired']) {
            $skills = explode(',', $training['skills_acquired']);
            $all_skills = array_merge($all_skills, array_map('trim', $skills));
        }
    }

    // Collect skills from work experience
    foreach ($experience as $exp) {
        if ($exp['skills_used']) {
            $skills = explode(',', $exp['skills_used']);
            $all_skills = array_merge($all_skills, array_map('trim', $skills));
        }
    }

    // Skills are now collected from trainings and work experience tables

    $unique_skills = array_unique(array_filter($all_skills));

    if (count($unique_skills) > 0) {
        $pdf->SetFont('helvetica', 'B', 12);
        $pdf->Cell(0, 8, 'SKILLS & COMPETENCIES', 0, 1);
        $pdf->SetFont('helvetica', '', 10);

        $skill_chunks = array_chunk($unique_skills, 4);
        foreach ($skill_chunks as $chunk) {
            $pdf->Cell(0, 5, '• ' . implode(' • ', $chunk), 0, 1);
        }
        $pdf->Ln(3);
    }


    // Additional Information
    $pdf->SetFont('helvetica', 'B', 12);
    $pdf->Cell(0, 8, 'INFORMACIÓN ADICIONAL', 0, 1);
    $pdf->SetFont('helvetica', '', 10);


    $additional_info[] = 'Programa de Estudio: ' . ($career['career_name'] ?? 'Not specified');
    if ($student['graduation_year']) {
        $additional_info[] = 'Expected Graduation: ' . $student['graduation_year'];
    }
    $additional_info[] = 'Idiomas: ' . count($languages);
    $additional_info[] = 'Capacitaciones: ' . count($trainings);
    $additional_info[] = 'Experiencia Laboral: ' . count($experience) . ' position(s)';

    foreach ($additional_info as $info) {
        $pdf->Cell(0, 5, '• ' . $info, 0, 1);
    }

    // Output the PDF
    $filename = 'CV-' . $user['first_name'] . '_' . $user['last_name'] . '.pdf';
    $pdf->Output($filename, 'D');
}
?>