<?php
require_once '../config/config.php';
require_once '../includes/pdf_cv_generator.php';
requireLogin('company');

$database = new Database();
$db = $database->getConnection();

$company_id = $_SESSION['company_id'];
$application_ids_string = $_GET['applications'] ?? '';

if (empty($application_ids_string)) {
    die('No applications specified for download.');
}

// Parse application IDs
$application_ids = array_filter(array_map('intval', explode(',', $application_ids_string)));

if (empty($application_ids)) {
    die('Invalid application IDs provided.');
}

// Get application details and verify they belong to this company
$placeholders = str_repeat('?,', count($application_ids) - 1) . '?';
$params = array_merge([$company_id], $application_ids);

$stmt = $db->prepare("
    SELECT ja.id, ja.candidate_id, ja.resume_id, ja.cover_letter, ja.applied_at, ja.status, 
           COALESCE(ja.total_score, 0) as total_score,
           j.title as job_title, j.description as job_description,
           c.first_name, c.last_name, c.email, c.profile_picture,
           r.title as resume_title, r.file_path as resume_path
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN candidates c ON ja.candidate_id = c.id
    LEFT JOIN resumes r ON ja.resume_id = r.id
    WHERE j.company_id = ? AND ja.id IN ($placeholders)
    ORDER BY ja.applied_at DESC
");

$stmt->execute($params);
$applications = $stmt->fetchAll();

if (empty($applications)) {
    die('No valid applications found for download.');
}

// Create ZIP file
$zip = new ZipArchive();
$zip_filename = 'applications_' . date('Y-m-d_H-i-s') . '.zip';
$zip_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $zip_filename;

if ($zip->open($zip_path, ZipArchive::CREATE) !== TRUE) {
    die('Cannot create ZIP file.');
}

$file_count = 0;
$processed_application_ids = [];

foreach ($applications as $app) {
    // Skip duplicates
    if (in_array($app['id'], $processed_application_ids)) {
        continue;
    }
    $processed_application_ids[] = $app['id'];
    
    $candidate_name = sanitizeFilename(trim($app['first_name'] . '_' . $app['last_name']));
    $job_title_clean = sanitizeFilename($app['job_title']);
    $app_folder = "App_{$app['id']}_{$candidate_name}_{$job_title_clean}";
    
    // Add application summary
    $summary_content = generateApplicationSummary($app);
    $zip->addFromString("{$app_folder}/Application_Summary.txt", $summary_content);
    $file_count++;
    
    // Add comprehensive CV with all sections
    $cv_data = getCVBuilderData($db, $app['candidate_id']);
    $profile_data = getProfileData($db, $app['candidate_id']);
    $qualifications = getQualifications($db, $app['candidate_id']);
    
    // Generate actual PDF CV
    try {
        $pdf_generator = new PDFCVGenerator();
        $pdf_content = $pdf_generator->generateCV($app, $cv_data, $profile_data, $qualifications);
        $cv_pdf_filename = "CV_{$candidate_name}_" . date('Y-m-d') . ".pdf";
        $zip->addFromString("{$app_folder}/{$cv_pdf_filename}", $pdf_content);
        $file_count++;
    } catch (Exception $e) {
        // Fallback to HTML if PDF generation fails
        $cv_html = generateComprehensiveCV($app, $cv_data, $profile_data, $qualifications);
        $cv_html_filename = "CV_{$candidate_name}_" . date('Y-m-d') . ".html";
        $zip->addFromString("{$app_folder}/{$cv_html_filename}", $cv_html);
        $file_count++;
    }
    
    // Add resume if available
    if (!empty($app['resume_path'])) {
        $resume_full_path = UPLOAD_PATH . 'resumes/' . $app['resume_path'];
        if (file_exists($resume_full_path)) {
            $resume_extension = pathinfo($app['resume_path'], PATHINFO_EXTENSION);
            $resume_filename = "Resume_{$candidate_name}.{$resume_extension}";
            $zip->addFile($resume_full_path, "{$app_folder}/{$resume_filename}");
            $file_count++;
        }
    }
    
    // Add profile picture if available
    if (!empty($app['profile_picture'])) {
        $profile_full_path = UPLOAD_PATH . 'profiles/' . $app['profile_picture'];
        if (file_exists($profile_full_path)) {
            $profile_extension = pathinfo($app['profile_picture'], PATHINFO_EXTENSION);
            $profile_filename = "Profile_Photo_{$candidate_name}.{$profile_extension}";
            $zip->addFile($profile_full_path, "{$app_folder}/{$profile_filename}");
            $file_count++;
        }
    }
    
    // Add all attachments (certificates, documents, portfolio, additional resumes)
    $attachments = getAttachments($db, $app['candidate_id']);
    $attachment_counter = [];
    
    foreach ($attachments as $attachment) {
        if (empty($attachment['path'])) continue;
        
        $attachment_type = $attachment['type'];
        
        // Handle different folder structures
        if ($attachment_type === 'certificate') {
            $attachment_path = UPLOAD_PATH . 'certificates/' . $attachment['path'];
        } elseif ($attachment_type === 'document') {
            $attachment_path = UPLOAD_PATH . 'documents/' . $attachment['path'];
        } elseif ($attachment_type === 'resume') {
            $attachment_path = UPLOAD_PATH . 'resumes/' . $attachment['path'];
        } else {
            $attachment_path = UPLOAD_PATH . $attachment_type . 's/' . $attachment['path'];
        }
        
        if (file_exists($attachment_path)) {
            // Initialize counter for this type
            if (!isset($attachment_counter[$attachment_type])) {
                $attachment_counter[$attachment_type] = 1;
            } else {
                $attachment_counter[$attachment_type]++;
            }
            
            $attachment_extension = pathinfo($attachment['path'], PATHINFO_EXTENSION);
            $display_name = $attachment['display_name'] ?? ucfirst($attachment_type);
            $attachment_filename = "{$display_name}_{$attachment_counter[$attachment_type]}.{$attachment_extension}";
            
            $zip->addFile($attachment_path, "{$app_folder}/{$attachment_filename}");
            $file_count++;
        }
    }
}

if ($file_count === 0) {
    $zip->close();
    unlink($zip_path);
    die('No files found to download.');
}

$zip->close();

// Download the ZIP file
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_filename . '"');
header('Content-Length: ' . filesize($zip_path));
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');

readfile($zip_path);
unlink($zip_path);
exit;

// Helper functions
function sanitizeFilename($filename) {
    return preg_replace('/[^a-zA-Z0-9_-]/', '_', $filename);
}

function generateApplicationSummary($app) {
    $content = "APPLICATION SUMMARY\n";
    $content .= "==================\n\n";
    $content .= "Candidate: " . $app['first_name'] . " " . $app['last_name'] . "\n";
    $content .= "Email: " . $app['email'] . "\n";
    $content .= "Position: " . $app['job_title'] . "\n";
    $content .= "Application Date: " . $app['applied_at'] . "\n";
    $content .= "Status: " . ucfirst($app['status']) . "\n";
    $content .= "Score: " . $app['total_score'] . "\n\n";
    
    if (!empty($app['cover_letter'])) {
        $content .= "COVER LETTER:\n";
        $content .= "-------------\n";
        $content .= $app['cover_letter'] . "\n\n";
    }
    
    return $content;
}

function getCVBuilderData($db, $candidate_id) {
    $cv_data = ['has_data' => false];
    
    try {
        // Get education data
        $stmt = $db->prepare("SELECT * FROM education WHERE candidate_id = ? ORDER BY start_date DESC");
        $stmt->execute([$candidate_id]);
        $cv_data['education'] = $stmt->fetchAll();
        
        // Get work experience data
        $stmt = $db->prepare("SELECT * FROM work_experience WHERE candidate_id = ? ORDER BY start_date DESC");
        $stmt->execute([$candidate_id]);
        $cv_data['experience'] = $stmt->fetchAll();
        
        // Get references data
        try {
            $stmt = $db->prepare("SELECT * FROM work_references WHERE candidate_id = ? ORDER BY created_at DESC");
            $stmt->execute([$candidate_id]);
            $cv_data['references'] = $stmt->fetchAll();
        } catch (PDOException $e) {
            $cv_data['references'] = [];
        }
        
        // Get skills data
        try {
            $stmt = $db->prepare("SELECT * FROM skills WHERE candidate_id = ? ORDER BY created_at DESC");
            $stmt->execute([$candidate_id]);
            $cv_data['skills'] = $stmt->fetchAll();
        } catch (PDOException $e) {
            $cv_data['skills'] = [];
        }
        
        // Get achievements/awards
        try {
            $stmt = $db->prepare("SELECT * FROM achievements WHERE candidate_id = ? ORDER BY date_achieved DESC");
            $stmt->execute([$candidate_id]);
            $cv_data['achievements'] = $stmt->fetchAll();
        } catch (PDOException $e) {
            $cv_data['achievements'] = [];
        }
        
        // Get languages
        try {
            $stmt = $db->prepare("SELECT * FROM languages WHERE candidate_id = ? ORDER BY proficiency_level DESC");
            $stmt->execute([$candidate_id]);
            $cv_data['languages'] = $stmt->fetchAll();
        } catch (PDOException $e) {
            $cv_data['languages'] = [];
        }
        
        // Check if we have any CV builder data
        if (!empty($cv_data['education']) || !empty($cv_data['experience']) || !empty($cv_data['references']) || 
            !empty($cv_data['skills']) || !empty($cv_data['achievements']) || !empty($cv_data['languages'])) {
            $cv_data['has_data'] = true;
        }
        
    } catch (PDOException $e) {
        // Return empty data on error
        $cv_data = ['has_data' => false, 'education' => [], 'experience' => [], 'references' => [], 'skills' => [], 'achievements' => [], 'languages' => []];
    }
    
    return $cv_data;
}

function getProfileData($db, $candidate_id) {
    try {
        $stmt = $db->prepare("SELECT * FROM candidates WHERE id = ?");
        $stmt->execute([$candidate_id]);
        return $stmt->fetch() ?: [];
    } catch (PDOException $e) {
        return [];
    }
}

function getQualifications($db, $candidate_id) {
    $qualifications = [];
    
    // Get certifications/qualifications
    try {
        $stmt = $db->prepare("SELECT * FROM certificates WHERE candidate_id = ? ORDER BY issue_date DESC");
        $stmt->execute([$candidate_id]);
        $qualifications['certificates'] = $stmt->fetchAll();
    } catch (PDOException $e) {
        $qualifications['certificates'] = [];
    }
    
    // Get additional qualifications if they have a separate table
    try {
        $stmt = $db->prepare("SELECT * FROM qualifications WHERE candidate_id = ? ORDER BY date_obtained DESC");
        $stmt->execute([$candidate_id]);
        $qualifications['qualifications'] = $stmt->fetchAll();
    } catch (PDOException $e) {
        $qualifications['qualifications'] = [];
    }
    
    return $qualifications;
}

function generateCVText($app, $cv_data) {
    $candidate_name = trim($app['first_name'] . ' ' . $app['last_name']);
    
    $content = "CURRICULUM VITAE\n";
    $content .= "================\n\n";
    $content .= "Name: $candidate_name\n";
    $content .= "Email: " . $app['email'] . "\n";
    $content .= "Position Applied For: " . $app['job_title'] . "\n";
    $content .= "Application Date: " . $app['applied_at'] . "\n\n";
    
    // Add work experience
    if (!empty($cv_data['experience'])) {
        $content .= "WORK EXPERIENCE:\n";
        $content .= "----------------\n";
        foreach ($cv_data['experience'] as $exp) {
            $content .= "• " . ($exp['position'] ?? 'Position') . " at " . ($exp['company_name'] ?? 'Company') . "\n";
            $content .= "  " . ($exp['start_date'] ?? '') . " - " . ($exp['end_date'] ?? 'Present') . "\n";
            if (!empty($exp['description'])) {
                $content .= "  " . $exp['description'] . "\n";
            }
            $content .= "\n";
        }
    }
    
    // Add education
    if (!empty($cv_data['education'])) {
        $content .= "EDUCATION:\n";
        $content .= "----------\n";
        foreach ($cv_data['education'] as $edu) {
            $content .= "• " . ($edu['degree'] ?? 'Degree') . " at " . ($edu['institution'] ?? 'Institution') . "\n";
            $content .= "  " . ($edu['start_date'] ?? '') . " - " . ($edu['end_date'] ?? '') . "\n";
            if (!empty($edu['description'])) {
                $content .= "  " . $edu['description'] . "\n";
            }
            $content .= "\n";
        }
    }
    
    // Add references
    if (!empty($cv_data['references'])) {
        $content .= "REFERENCES:\n";
        $content .= "-----------\n";
        foreach ($cv_data['references'] as $ref) {
            $content .= "• " . ($ref['name'] ?? 'Reference') . " - " . ($ref['position'] ?? '') . "\n";
            $content .= "  " . ($ref['company'] ?? '') . "\n";
            $content .= "  Email: " . ($ref['email'] ?? '') . "\n";
            $content .= "  Phone: " . ($ref['phone'] ?? '') . "\n";
            $content .= "\n";
        }
    }
    
    return $content;
}

function getAttachments($db, $candidate_id) {
    $attachments = [];
    
    // Get certificates using correct table structure
    try {
        $stmt = $db->prepare("SELECT id, file_path as path, title as name, 'certificate' as type, issuing_organization, issue_date FROM certificates WHERE candidate_id = ?");
        $stmt->execute([$candidate_id]);
        $certificates = $stmt->fetchAll();
        foreach ($certificates as $cert) {
            $cert['display_name'] = sanitizeFilename(($cert['name'] ?? 'Certificate') . '_' . ($cert['issuing_organization'] ?? ''));
            $attachments[] = $cert;
        }
    } catch (PDOException $e) {
        // Table might not exist or different structure
    }
    
    // Get documents from candidate_documents table
    try {
        $stmt = $db->prepare("SELECT id, file_path as path, title as name, 'document' as type, document_type FROM candidate_documents WHERE candidate_id = ?");
        $stmt->execute([$candidate_id]);
        $documents = $stmt->fetchAll();
        foreach ($documents as $doc) {
            $doc['display_name'] = sanitizeFilename(($doc['name'] ?? 'Document') . '_' . ($doc['document_type'] ?? ''));
            $attachments[] = $doc;
        }
    } catch (PDOException $e) {
        // Table might not exist
    }
    
    // Get additional resumes (if candidate uploaded multiple)
    try {
        $stmt = $db->prepare("SELECT id, file_path as path, title as name, 'resume' as type FROM resumes WHERE candidate_id = ? AND file_path IS NOT NULL AND file_path != ''");
        $stmt->execute([$candidate_id]);
        $resumes = $stmt->fetchAll();
        foreach ($resumes as $resume) {
            $resume['display_name'] = sanitizeFilename($resume['name'] ?? 'Resume');
            $attachments[] = $resume;
        }
    } catch (PDOException $e) {
        // Table might not exist
    }
    
    return $attachments;
}

function generateComprehensiveCV($app, $cv_data, $profile_data, $qualifications = []) {
    $candidate_name = trim($app['first_name'] . ' ' . $app['last_name']);
    $profile_image = '';
    
    // Include profile image if available
    if (!empty($app['profile_picture'])) {
        $profile_path = UPLOAD_PATH . 'profiles/' . $app['profile_picture'];
        if (file_exists($profile_path)) {
            $base64_image = base64_encode(file_get_contents($profile_path));
            $image_info = getimagesize($profile_path);
            $mime_type = $image_info['mime'];
            $profile_image = "data:$mime_type;base64,$base64_image";
        }
    }
    
    $html = '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CV - ' . htmlspecialchars($candidate_name) . '</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #fff;
        }
        .header {
            text-align: center;
            border-bottom: 3px solid #2c3e50;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .profile-image {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            object-fit: cover;
            margin: 0 auto 20px;
            display: block;
            border: 4px solid #3498db;
        }
        .name {
            font-size: 2.5em;
            font-weight: bold;
            color: #2c3e50;
            margin: 10px 0;
        }
        .contact-info {
            font-size: 1.1em;
            color: #666;
            margin: 5px 0;
        }
        .section {
            margin: 30px 0;
        }
        .section-title {
            font-size: 1.4em;
            font-weight: bold;
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
            margin-bottom: 15px;
        }
        .item {
            margin: 15px 0;
            padding: 15px;
            background: #f8f9fa;
            border-left: 4px solid #3498db;
            border-radius: 5px;
        }
        .item-title {
            font-weight: bold;
            color: #2c3e50;
            font-size: 1.1em;
        }
        .item-subtitle {
            color: #666;
            font-style: italic;
            margin: 5px 0;
        }
        .item-date {
            color: #888;
            font-size: 0.9em;
            float: right;
        }
        .item-description {
            margin-top: 10px;
            text-align: justify;
        }
        .skills-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
        }
        .skill-item {
            background: #e3f2fd;
            padding: 8px 12px;
            border-radius: 20px;
            text-align: center;
            font-weight: 500;
        }
        .personal-info {
            background: #f1f8e9;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        .personal-info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }
        .info-item {
            display: flex;
            align-items: center;
        }
        .info-label {
            font-weight: bold;
            color: #2c3e50;
            margin-right: 10px;
            min-width: 100px;
        }
        @media print {
            body { margin: 0; padding: 15px; }
            .section { page-break-inside: avoid; }
        }
    </style>
</head>
<body>
    <div class="header">';
    
    if ($profile_image) {
        $html .= '<img src="' . $profile_image . '" alt="Profile Picture" class="profile-image">';
    }
    
    $html .= '<div class="name">' . htmlspecialchars($candidate_name) . '</div>
        <div class="contact-info">📧 ' . htmlspecialchars($app['email']) . '</div>';
    
    if (!empty($profile_data['phone'])) {
        $html .= '<div class="contact-info">📞 ' . htmlspecialchars($profile_data['phone']) . '</div>';
    }
    if (!empty($profile_data['address'])) {
        $html .= '<div class="contact-info">📍 ' . htmlspecialchars($profile_data['address']) . '</div>';
    }
    
    $html .= '<div class="contact-info"><strong>Position Applied For:</strong> ' . htmlspecialchars($app['job_title']) . '</div>
    </div>';

    // Personal Information Section
    if (!empty($profile_data)) {
        $html .= '<div class="section">
            <div class="section-title">Personal Information</div>
            <div class="personal-info">
                <div class="personal-info-grid">';
        
        $personal_fields = [
            'date_of_birth' => 'Date of Birth',
            'gender' => 'Gender',
            'nationality' => 'Nationality',
            'id_number' => 'ID Number',
            'passport_number' => 'Passport Number',
            'country' => 'Country',
            'candidate_type' => 'Candidate Type'
        ];
        
        foreach ($personal_fields as $field => $label) {
            if (!empty($profile_data[$field])) {
                $html .= '<div class="info-item">
                    <span class="info-label">' . $label . ':</span>
                    <span>' . htmlspecialchars($profile_data[$field]) . '</span>
                </div>';
            }
        }
        
        $html .= '</div></div></div>';
    }

    // Work Experience
    if (!empty($cv_data['experience'])) {
        $html .= '<div class="section">
            <div class="section-title">Work Experience</div>';
        foreach ($cv_data['experience'] as $exp) {
            $html .= '<div class="item">
                <div class="item-date">' . htmlspecialchars($exp['start_date'] ?? '') . ' - ' . htmlspecialchars($exp['end_date'] ?? 'Present') . '</div>
                <div class="item-title">' . htmlspecialchars($exp['position'] ?? '') . '</div>
                <div class="item-subtitle">' . htmlspecialchars($exp['company_name'] ?? '') . '</div>';
            if (!empty($exp['description'])) {
                $html .= '<div class="item-description">' . nl2br(htmlspecialchars($exp['description'])) . '</div>';
            }
            $html .= '</div>';
        }
        $html .= '</div>';
    }

    // Education
    if (!empty($cv_data['education'])) {
        $html .= '<div class="section">
            <div class="section-title">Education</div>';
        foreach ($cv_data['education'] as $edu) {
            $html .= '<div class="item">
                <div class="item-date">' . htmlspecialchars($edu['start_date'] ?? '') . ' - ' . htmlspecialchars($edu['end_date'] ?? '') . '</div>
                <div class="item-title">' . htmlspecialchars($edu['degree'] ?? '') . '</div>
                <div class="item-subtitle">' . htmlspecialchars($edu['institution'] ?? '') . '</div>';
            if (!empty($edu['description'])) {
                $html .= '<div class="item-description">' . nl2br(htmlspecialchars($edu['description'])) . '</div>';
            }
            $html .= '</div>';
        }
        $html .= '</div>';
    }

    // Skills
    if (!empty($cv_data['skills'])) {
        $html .= '<div class="section">
            <div class="section-title">Skills</div>
            <div class="skills-grid">';
        foreach ($cv_data['skills'] as $skill) {
            $html .= '<div class="skill-item">' . htmlspecialchars($skill['skill_name'] ?? $skill['name'] ?? '') . '</div>';
        }
        $html .= '</div></div>';
    }

    // Languages
    if (!empty($cv_data['languages'])) {
        $html .= '<div class="section">
            <div class="section-title">Languages</div>';
        foreach ($cv_data['languages'] as $lang) {
            $html .= '<div class="item">
                <div class="item-title">' . htmlspecialchars($lang['language'] ?? '') . '</div>
                <div class="item-subtitle">Proficiency: ' . htmlspecialchars($lang['proficiency_level'] ?? '') . '</div>
            </div>';
        }
        $html .= '</div>';
    }

    // Qualifications & Certifications
    if (!empty($qualifications['certificates'])) {
        $html .= '<div class="section">
            <div class="section-title">Qualifications & Certifications</div>';
        foreach ($qualifications['certificates'] as $cert) {
            $html .= '<div class="item">
                <div class="item-date">' . htmlspecialchars($cert['issue_date'] ?? '') . '</div>
                <div class="item-title">' . htmlspecialchars($cert['title'] ?? '') . '</div>
                <div class="item-subtitle">' . htmlspecialchars($cert['issuing_organization'] ?? '') . '</div>';
            if (!empty($cert['description'])) {
                $html .= '<div class="item-description">' . nl2br(htmlspecialchars($cert['description'])) . '</div>';
            }
            if (!empty($cert['credential_id'])) {
                $html .= '<div class="contact-info">📜 Credential ID: ' . htmlspecialchars($cert['credential_id']) . '</div>';
            }
            if (!empty($cert['expiry_date'])) {
                $html .= '<div class="contact-info">📅 Expires: ' . htmlspecialchars($cert['expiry_date']) . '</div>';
            }
            $html .= '</div>';
        }
        $html .= '</div>';
    }

    // Additional Qualifications
    if (!empty($qualifications['qualifications'])) {
        $html .= '<div class="section">
            <div class="section-title">Additional Qualifications</div>';
        foreach ($qualifications['qualifications'] as $qual) {
            $html .= '<div class="item">
                <div class="item-date">' . htmlspecialchars($qual['date_obtained'] ?? '') . '</div>
                <div class="item-title">' . htmlspecialchars($qual['qualification_name'] ?? $qual['name'] ?? '') . '</div>
                <div class="item-subtitle">' . htmlspecialchars($qual['institution'] ?? '') . '</div>';
            if (!empty($qual['description'])) {
                $html .= '<div class="item-description">' . nl2br(htmlspecialchars($qual['description'])) . '</div>';
            }
            $html .= '</div>';
        }
        $html .= '</div>';
    }

    // Achievements
    if (!empty($cv_data['achievements'])) {
        $html .= '<div class="section">
            <div class="section-title">Achievements & Awards</div>';
        foreach ($cv_data['achievements'] as $achievement) {
            $html .= '<div class="item">
                <div class="item-date">' . htmlspecialchars($achievement['date_achieved'] ?? '') . '</div>
                <div class="item-title">' . htmlspecialchars($achievement['title'] ?? '') . '</div>';
            if (!empty($achievement['description'])) {
                $html .= '<div class="item-description">' . nl2br(htmlspecialchars($achievement['description'])) . '</div>';
            }
            $html .= '</div>';
        }
        $html .= '</div>';
    }

    // References
    if (!empty($cv_data['references'])) {
        $html .= '<div class="section">
            <div class="section-title">References</div>';
        foreach ($cv_data['references'] as $ref) {
            $html .= '<div class="item">
                <div class="item-title">' . htmlspecialchars($ref['name'] ?? '') . '</div>
                <div class="item-subtitle">' . htmlspecialchars($ref['position'] ?? '') . ' at ' . htmlspecialchars($ref['company'] ?? '') . '</div>
                <div class="contact-info">📧 ' . htmlspecialchars($ref['email'] ?? '') . '</div>';
            if (!empty($ref['phone'])) {
                $html .= '<div class="contact-info">📞 ' . htmlspecialchars($ref['phone']) . '</div>';
            }
            $html .= '</div>';
        }
        $html .= '</div>';
    }

    $html .= '</body></html>';
    return $html;
}

function generatePDFReadyCV($app, $cv_data, $profile_data, $qualifications = []) {
    // Generate a version optimized for PDF printing/conversion
    $html = generateComprehensiveCV($app, $cv_data, $profile_data, $qualifications);
    
    // Add PDF-specific styles for better printing
    $pdf_styles = '<style>
        @media print {
            body { 
                font-size: 11pt; 
                margin: 0;
                padding: 0;
                background: white !important;
            }
            .header { 
                margin-bottom: 15pt; 
                border-bottom: 2pt solid #000 !important;
            }
            .section { 
                margin: 12pt 0; 
                page-break-inside: avoid;
            }
            .item { 
                margin: 8pt 0; 
                page-break-inside: avoid;
                background: white !important;
                border: none !important;
                padding: 5pt !important;
            }
            .profile-image {
                width: 80px !important;
                height: 80px !important;
                border: 2px solid #000 !important;
            }
            .section-title {
                border-bottom: 1pt solid #000 !important;
                color: #000 !important;
                font-size: 12pt !important;
            }
            .personal-info {
                background: white !important;
                border: 1pt solid #ccc !important;
            }
            .skills-grid {
                display: block !important;
            }
            .skill-item {
                display: inline-block !important;
                background: #f0f0f0 !important;
                margin: 2pt !important;
                border: 1pt solid #ccc !important;
                color: #000 !important;
            }
        }
        @page {
            margin: 0.5in;
            size: A4;
        }
        /* Force black text for PDF */
        * {
            color-adjust: exact !important;
            -webkit-print-color-adjust: exact !important;
        }
    </style>';
    
    return str_replace('</head>', $pdf_styles . '</head>', $html);
}
?>