<?php
// Reliable CV Generator - prioritizes working solutions over fancy features
class ReliableCVGenerator {
    
    public function generateCV($app, $cv_data) {
        // Try PDF generation methods in order of reliability
        $methods = [
            'generateHTMLForPrint',  // Most reliable - HTML that prints well
            'generateWithWkhtmltopdf', // If wkhtmltopdf available
            'generateSimplePDF'      // Last resort - basic PDF
        ];
        
        foreach ($methods as $method) {
            try {
                $result = $this->$method($app, $cv_data);
                if ($result !== false) {
                    return $result;
                }
            } catch (Exception $e) {
                // Continue to next method
            }
        }
        
        // If all else fails, return text version
        return $this->generateTextCV($app, $cv_data);
    }
    
    private function generateHTMLForPrint($app, $cv_data) {
        // Generate high-quality HTML optimized for browser printing
        $candidate_name = trim(($app['first_name'] ?? '') . ' ' . ($app['last_name'] ?? ''));
        
        $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>
        @page {
            margin: 0.75in;
            size: A4;
        }
        
        body {
            font-family: "Calibri", "Arial", sans-serif;
            font-size: 11pt;
            line-height: 1.4;
            color: #333;
            margin: 0;
            padding: 0;
        }
        
        .cv-container {
            max-width: 8.5in;
            margin: 0 auto;
            background: white;
        }
        
        .header {
            border-bottom: 3px solid #2c3e50;
            padding-bottom: 20px;
            margin-bottom: 25px;
            position: relative;
            min-height: 140px;
        }
        
        .photo-section {
            position: absolute;
            top: 0;
            right: 0;
            width: 120px;
            height: 140px;
        }
        
        .photo {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border: 2px solid #2c3e50;
            border-radius: 8px;
            background: #f8f9fa;
        }
        
        .no-photo {
            width: 100%;
            height: 100%;
            border: 2px dashed #ccc;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #888;
            font-size: 12px;
            text-align: center;
            background: #f8f9fa;
        }
        
        .header-content {
            margin-right: 140px;
        }
        
        .name {
            font-size: 24pt;
            font-weight: bold;
            color: #2c3e50;
            margin: 0 0 15px 0;
        }
        
        .contact-info {
            font-size: 11pt;
            color: #555;
            line-height: 1.6;
        }
        
        .contact-info div {
            margin: 3px 0;
        }
        
        .section {
            margin-bottom: 25px;
            page-break-inside: avoid;
        }
        
        .section-title {
            font-size: 14pt;
            font-weight: bold;
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
            margin-bottom: 15px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .item {
            margin-bottom: 15px;
            padding-left: 10px;
        }
        
        .item-title {
            font-size: 12pt;
            font-weight: bold;
            color: #2c3e50;
            margin: 0 0 5px 0;
        }
        
        .item-meta {
            font-size: 10pt;
            color: #666;
            font-style: italic;
            margin-bottom: 8px;
        }
        
        .item-description {
            font-size: 11pt;
            color: #444;
            margin: 8px 0 0 15px;
            text-align: justify;
        }
        
        .skills-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 5px;
            margin: 10px 0;
        }
        
        .skill-item {
            font-size: 11pt;
            margin: 3px 0;
        }
        
        .references-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .reference-item {
            break-inside: avoid;
        }
        
        .footer {
            text-align: center;
            margin-top: 40px;
            padding-top: 15px;
            border-top: 1px solid #ccc;
            font-size: 9pt;
            color: #888;
        }
        
        .print-controls {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #007bff;
            color: white;
            padding: 10px 15px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            z-index: 1000;
        }
        
        .print-controls button {
            background: white;
            color: #007bff;
            border: none;
            padding: 8px 15px;
            border-radius: 3px;
            cursor: pointer;
            margin: 0 5px;
            font-weight: bold;
        }
        
        .print-controls button:hover {
            background: #f0f0f0;
        }
        
        @media print {
            .print-controls {
                display: none;
            }
            
            body {
                margin: 0;
                padding: 0;
            }
            
            .cv-container {
                max-width: none;
                margin: 0;
            }
        }
        
        @media screen {
            .cv-container {
                margin: 20px auto;
                padding: 40px;
                box-shadow: 0 0 20px rgba(0,0,0,0.1);
                border-radius: 8px;
            }
        }
    </style>
</head>
<body>
    <div class="print-controls">
        <strong>CV Ready!</strong><br>
        <button onclick="window.print()">🖨️ Print/Save PDF</button>
        <button onclick="downloadHTML()">💾 Save HTML</button>
    </div>
    
    <div class="cv-container">
        <header class="header">
            <div class="photo-section">';
        
        // Add photo or placeholder
        if (!empty($app['profile_picture'])) {
            $photo_path = UPLOAD_PATH . 'profiles/' . $app['profile_picture'];
            if (file_exists($photo_path)) {
                $imageData = base64_encode(file_get_contents($photo_path));
                $imageType = pathinfo($photo_path, PATHINFO_EXTENSION);
                $html .= '<img src="data:image/' . $imageType . ';base64,' . $imageData . '" class="photo" alt="Profile Photo">';
            } else {
                $html .= '<div class="no-photo">Photo<br>Not Found</div>';
            }
        } else {
            $html .= '<div class="no-photo">No Photo<br>Available</div>';
        }
        
        $html .= '</div>
            <div class="header-content">
                <h1 class="name">' . htmlspecialchars($candidate_name) . '</h1>
                <div class="contact-info">';
        
        if (!empty($app['email'])) $html .= '<div>📧 ' . htmlspecialchars($app['email']) . '</div>';
        if (!empty($app['phone'])) $html .= '<div>📞 ' . htmlspecialchars($app['phone']) . '</div>';
        if (!empty($app['address'])) $html .= '<div>📍 ' . htmlspecialchars($app['address']) . '</div>';
        if (!empty($app['linkedin_url'])) $html .= '<div>💼 ' . htmlspecialchars($app['linkedin_url']) . '</div>';
        if (!empty($app['portfolio_url'])) $html .= '<div>🌐 ' . htmlspecialchars($app['portfolio_url']) . '</div>';
        
        $html .= '</div>
            </div>
        </header>';
        
        // Professional Introduction Section (NEW)
        $introduction_content = '';
        if (!empty($app['bio'])) {
            $introduction_content = $app['bio'];
        } elseif (!empty($app['about_me'])) {
            $introduction_content = $app['about_me'];
        } elseif (!empty($cv_data['resume_summary'])) {
            $introduction_content = $cv_data['resume_summary'];
        }
        
        if (!empty($introduction_content)) {
            $html .= '<section class="section">
                <h2 class="section-title">Professional Introduction</h2>
                <div class="item">
                    <p class="item-description" style="font-size: 12pt; text-align: justify; line-height: 1.6;">' . nl2br(htmlspecialchars($introduction_content)) . '</p>
                </div>
            </section>';
        }
        
        // Comprehensive Personal Profile Section
        $html .= '<section class="section">
            <h2 class="section-title">Complete Profile Information</h2>
            <div class="item">';
        
        // Three-column layout for comprehensive information
        $html .= '<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-bottom: 20px;">
            
            <!-- Contact & Communication Column -->
            <div>
                <h4 style="margin: 0 0 12px 0; color: #2c3e50; font-size: 12pt; border-bottom: 1px solid #3498db; padding-bottom: 4px;">Contact Information</h4>';
        
        if (!empty($app['email'])) $html .= '<div style="margin: 6px 0;"><strong>Email:</strong> ' . htmlspecialchars($app['email']) . '</div>';
        if (!empty($app['phone'])) $html .= '<div style="margin: 6px 0;"><strong>Phone:</strong> ' . htmlspecialchars($app['phone']) . '</div>';
        if (!empty($app['address'])) $html .= '<div style="margin: 6px 0;"><strong>Address:</strong> ' . htmlspecialchars($app['address']) . '</div>';
        if (!empty($app['emergency_contact'])) $html .= '<div style="margin: 6px 0;"><strong>Emergency Contact:</strong> ' . htmlspecialchars($app['emergency_contact']) . '</div>';
        
        $html .= '<h4 style="margin: 15px 0 12px 0; color: #2c3e50; font-size: 12pt; border-bottom: 1px solid #3498db; padding-bottom: 4px;">Online Presence</h4>';
        if (!empty($app['linkedin_url'])) $html .= '<div style="margin: 6px 0;"><strong>LinkedIn:</strong> <a href="' . htmlspecialchars($app['linkedin_url']) . '">' . htmlspecialchars($app['linkedin_url']) . '</a></div>';
        if (!empty($app['portfolio_url'])) $html .= '<div style="margin: 6px 0;"><strong>Portfolio:</strong> <a href="' . htmlspecialchars($app['portfolio_url']) . '">' . htmlspecialchars($app['portfolio_url']) . '</a></div>';
        if (!empty($app['website'])) $html .= '<div style="margin: 6px 0;"><strong>Website:</strong> <a href="' . htmlspecialchars($app['website']) . '">' . htmlspecialchars($app['website']) . '</a></div>';
        if (!empty($app['github_url'])) $html .= '<div style="margin: 6px 0;"><strong>GitHub:</strong> <a href="' . htmlspecialchars($app['github_url']) . '">' . htmlspecialchars($app['github_url']) . '</a></div>';
        
        $html .= '</div>
            
            <!-- Personal Details Column -->
            <div>
                <h4 style="margin: 0 0 12px 0; color: #2c3e50; font-size: 12pt; border-bottom: 1px solid #3498db; padding-bottom: 4px;">Personal Details</h4>';
        
        if (!empty($app['date_of_birth']) && $app['date_of_birth'] !== '0000-00-00') {
            $html .= '<div style="margin: 6px 0;"><strong>Date of Birth:</strong> ' . date('F j, Y', strtotime($app['date_of_birth'])) . '</div>';
        }
        if (!empty($app['nationality'])) $html .= '<div style="margin: 6px 0;"><strong>Nationality:</strong> ' . htmlspecialchars($app['nationality']) . '</div>';
        if (!empty($app['gender'])) $html .= '<div style="margin: 6px 0;"><strong>Gender:</strong> ' . ucfirst(htmlspecialchars($app['gender'])) . '</div>';
        if (!empty($app['marital_status'])) $html .= '<div style="margin: 6px 0;"><strong>Marital Status:</strong> ' . ucfirst(str_replace('_', ' ', htmlspecialchars($app['marital_status']))) . '</div>';
        // Smart document display based on nationality for HR teams
        $nationality = strtolower($app['nationality'] ?? '');
        $is_south_african = (strpos($nationality, 'south african') !== false || 
                           strpos($nationality, 'south africa') !== false || 
                           $nationality === 'south african' || 
                           $nationality === 'sa' || 
                           $nationality === 'rsa');
        
        if ($is_south_african) {
            // For South African candidates, prioritize ID number
            if (!empty($app['id_number']) && !preg_match('/password|login|auth/i', 'id_number')) {
                $html .= '<div style="margin: 6px 0;"><strong>South African ID:</strong> ' . htmlspecialchars($app['id_number']) . '</div>';
            }
        } else {
            // For foreign nationals, prioritize passport number
            if (!empty($app['passport_number'])) {
                $html .= '<div style="margin: 6px 0;"><strong>Passport Number:</strong> ' . htmlspecialchars($app['passport_number']) . '</div>';
            }
        }
        
        // Show additional document if available (but not both if one is primary)
        if ($is_south_african && !empty($app['passport_number'])) {
            $html .= '<div style="margin: 6px 0;"><strong>Passport:</strong> ' . htmlspecialchars($app['passport_number']) . '</div>';
        } elseif (!$is_south_african && !empty($app['id_number']) && !preg_match('/password|login|auth/i', 'id_number')) {
            $html .= '<div style="margin: 6px 0;"><strong>National ID:</strong> ' . htmlspecialchars($app['id_number']) . '</div>';
        }
        if (!empty($app['drivers_license'])) $html .= '<div style="margin: 6px 0;"><strong>Driver\'s License:</strong> ' . htmlspecialchars($app['drivers_license']) . '</div>';
        
        $html .= '<h4 style="margin: 15px 0 12px 0; color: #2c3e50; font-size: 12pt; border-bottom: 1px solid #3498db; padding-bottom: 4px;">Physical Attributes</h4>';
        if (!empty($app['height'])) $html .= '<div style="margin: 6px 0;"><strong>Height:</strong> ' . htmlspecialchars($app['height']) . '</div>';
        if (!empty($app['weight'])) $html .= '<div style="margin: 6px 0;"><strong>Weight:</strong> ' . htmlspecialchars($app['weight']) . '</div>';
        
        $html .= '</div>
            
            <!-- Professional & Work Column -->
            <div>
                <h4 style="margin: 0 0 12px 0; color: #2c3e50; font-size: 12pt; border-bottom: 1px solid #3498db; padding-bottom: 4px;">Work Authorization</h4>';
        
        if (!empty($app['work_permit_status'])) $html .= '<div style="margin: 6px 0;"><strong>Work Status:</strong> ' . ucfirst(str_replace('_', ' ', htmlspecialchars($app['work_permit_status']))) . '</div>';
        if (!empty($app['visa_status'])) $html .= '<div style="margin: 6px 0;"><strong>Visa Status:</strong> ' . htmlspecialchars($app['visa_status']) . '</div>';
        if (!empty($app['availability'])) $html .= '<div style="margin: 6px 0;"><strong>Availability:</strong> ' . htmlspecialchars($app['availability']) . '</div>';
        if (!empty($app['notice_period'])) $html .= '<div style="margin: 6px 0;"><strong>Notice Period:</strong> ' . htmlspecialchars($app['notice_period']) . '</div>';
        if (!empty($app['willing_to_relocate'])) $html .= '<div style="margin: 6px 0;"><strong>Willing to Relocate:</strong> ' . (($app['willing_to_relocate'] == 1) ? 'Yes' : 'No') . '</div>';
        if (!empty($app['travel_availability'])) $html .= '<div style="margin: 6px 0;"><strong>Travel Availability:</strong> ' . htmlspecialchars($app['travel_availability']) . '</div>';
        
        $html .= '<h4 style="margin: 15px 0 12px 0; color: #2c3e50; font-size: 12pt; border-bottom: 1px solid #3498db; padding-bottom: 4px;">Career Expectations</h4>';
        if (!empty($app['preferred_salary'])) $html .= '<div style="margin: 6px 0;"><strong>Expected Salary:</strong> ' . htmlspecialchars($app['preferred_salary']) . '</div>';
        if (!empty($app['current_salary'])) $html .= '<div style="margin: 6px 0;"><strong>Current Salary:</strong> ' . htmlspecialchars($app['current_salary']) . '</div>';
        if (!empty($app['experience_years']) && is_numeric($app['experience_years'])) {
            $html .= '<div style="margin: 6px 0;"><strong>Total Experience:</strong> ' . $app['experience_years'] . ' years</div>';
        }
        if (!empty($app['preferred_job_type'])) $html .= '<div style="margin: 6px 0;"><strong>Preferred Job Type:</strong> ' . ucfirst(str_replace('_', ' ', htmlspecialchars($app['preferred_job_type']))) . '</div>';
        if (!empty($app['preferred_location'])) $html .= '<div style="margin: 6px 0;"><strong>Preferred Location:</strong> ' . htmlspecialchars($app['preferred_location']) . '</div>';
        
        $html .= '</div>
        </div>';
        
        // Career Objective/Goals Section
        if (!empty($app['career_objective']) || !empty($app['career_goal'])) {
            $objective = $app['career_objective'] ?? $app['career_goal'];
            $html .= '<div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-left: 4px solid #3498db; border-radius: 4px;">
                <h4 style="margin: 0 0 10px 0; color: #2c3e50; font-size: 12pt;">Career Objective</h4>
                <p style="margin: 0; font-style: italic; color: #555; text-align: justify; line-height: 1.5;">' . nl2br(htmlspecialchars($objective)) . '</p>
            </div>';
        }
        
        // Additional Profile Information
        $additional_info = [];
        if (!empty($app['hobbies'])) $additional_info['Hobbies & Interests'] = $app['hobbies'];
        if (!empty($app['volunteer_work'])) $additional_info['Volunteer Experience'] = $app['volunteer_work'];
        if (!empty($app['achievements'])) $additional_info['Notable Achievements'] = $app['achievements'];
        if (!empty($app['references_statement'])) $additional_info['References Statement'] = $app['references_statement'];
        
        if (!empty($additional_info)) {
            $html .= '<div style="margin-top: 20px;">';
            foreach ($additional_info as $label => $content) {
                $html .= '<div style="margin-bottom: 15px;">
                    <h4 style="margin: 0 0 8px 0; color: #2c3e50; font-size: 12pt;">' . $label . '</h4>
                    <p style="margin: 0; color: #555; text-align: justify; line-height: 1.4;">' . nl2br(htmlspecialchars($content)) . '</p>
                </div>';
            }
            $html .= '</div>';
        }
        
        $html .= '</div>
        </section>';
        
        // Professional Summary
        if (!empty($cv_data['resume_summary'])) {
            $html .= '<section class="section">
                <h2 class="section-title">Professional Summary</h2>
                <div class="item">
                    <p class="item-description">' . nl2br(htmlspecialchars($cv_data['resume_summary'])) . '</p>
                </div>
            </section>';
        }
        
        // Comprehensive Skills Section
        if (!empty($cv_data['skills'])) {
            $html .= '<section class="section">
                <h2 class="section-title">Skills & Competencies</h2>
                <div class="item">';
            
            $skills_array = array_filter(array_map('trim', explode(',', $cv_data['skills'])));
            
            // Categorize skills automatically based on common patterns
            $skill_categories = [
                'Technical Skills' => [],
                'Programming Languages' => [],
                'Software & Tools' => [],
                'Management & Leadership' => [],
                'Communication & Interpersonal' => [],
                'General Skills' => []
            ];
            
            // Common skill patterns for categorization
            $technical_keywords = ['SQL', 'Database', 'Server', 'Network', 'Cloud', 'AWS', 'Azure', 'Docker', 'Git', 'API', 'REST', 'HTML', 'CSS', 'Bootstrap', 'React', 'Vue', 'Angular'];
            $programming_keywords = ['PHP', 'JavaScript', 'Python', 'Java', 'C++', 'C#', 'Ruby', 'Go', 'Swift', 'Kotlin', 'TypeScript', 'Node.js', 'Laravel', 'Django', 'Spring'];
            $software_keywords = ['Excel', 'Word', 'PowerPoint', 'Photoshop', 'Illustrator', 'AutoCAD', 'SPSS', 'Tableau', 'Power BI', 'Salesforce', 'SAP', 'Oracle', 'MySQL'];
            $management_keywords = ['Management', 'Leadership', 'Project Management', 'Team Lead', 'Supervision', 'Strategic Planning', 'Budget', 'PMP', 'Agile', 'Scrum'];
            $communication_keywords = ['Communication', 'Presentation', 'Writing', 'Public Speaking', 'Negotiation', 'Customer Service', 'Training', 'Collaboration'];
            
            foreach ($skills_array as $skill) {
                $skill_lower = strtolower($skill);
                $categorized = false;
                
                // Check technical skills
                foreach ($technical_keywords as $keyword) {
                    if (stripos($skill, $keyword) !== false) {
                        $skill_categories['Technical Skills'][] = $skill;
                        $categorized = true;
                        break;
                    }
                }
                
                // Check programming languages
                if (!$categorized) {
                    foreach ($programming_keywords as $keyword) {
                        if (stripos($skill, $keyword) !== false) {
                            $skill_categories['Programming Languages'][] = $skill;
                            $categorized = true;
                            break;
                        }
                    }
                }
                
                // Check software & tools
                if (!$categorized) {
                    foreach ($software_keywords as $keyword) {
                        if (stripos($skill, $keyword) !== false) {
                            $skill_categories['Software & Tools'][] = $skill;
                            $categorized = true;
                            break;
                        }
                    }
                }
                
                // Check management skills
                if (!$categorized) {
                    foreach ($management_keywords as $keyword) {
                        if (stripos($skill, $keyword) !== false) {
                            $skill_categories['Management & Leadership'][] = $skill;
                            $categorized = true;
                            break;
                        }
                    }
                }
                
                // Check communication skills
                if (!$categorized) {
                    foreach ($communication_keywords as $keyword) {
                        if (stripos($skill, $keyword) !== false) {
                            $skill_categories['Communication & Interpersonal'][] = $skill;
                            $categorized = true;
                            break;
                        }
                    }
                }
                
                // If not categorized, add to general skills
                if (!$categorized) {
                    $skill_categories['General Skills'][] = $skill;
                }
            }
            
            // Display categorized skills
            $html .= '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px;">';
            
            $column1 = [];
            $column2 = [];
            $column_toggle = 0;
            
            foreach ($skill_categories as $category => $skills) {
                if (!empty($skills)) {
                    $category_html = '<div style="margin-bottom: 20px;">
                        <h4 style="margin: 0 0 10px 0; color: #2c3e50; font-size: 11pt; border-bottom: 1px solid #3498db; padding-bottom: 3px;">' . $category . '</h4>
                        <div style="display: flex; flex-wrap: wrap; gap: 8px;">';
                    
                    foreach ($skills as $skill) {
                        $category_html .= '<span style="background: #e7f3ff; padding: 4px 10px; border-radius: 15px; font-size: 10pt; border: 1px solid #b3d7ff; white-space: nowrap;">• ' . htmlspecialchars($skill) . '</span>';
                    }
                    
                    $category_html .= '</div></div>';
                    
                    if ($column_toggle % 2 == 0) {
                        $column1[] = $category_html;
                    } else {
                        $column2[] = $category_html;
                    }
                    $column_toggle++;
                }
            }
            
            $html .= '<div>' . implode('', $column1) . '</div>';
            $html .= '<div>' . implode('', $column2) . '</div>';
            
            $html .= '</div></div>
            </section>';
        }
        
        // Languages
        if (!empty($cv_data['languages'])) {
            $html .= '<section class="section">
                <h2 class="section-title">Languages</h2>
                <div class="item">
                    <p class="item-description">' . nl2br(htmlspecialchars($cv_data['languages'])) . '</p>
                </div>
            </section>';
        }
        
        // Work Experience
        if (!empty($cv_data['experience'])) {
            $html .= '<section class="section">
                <h2 class="section-title">Professional Experience</h2>';
            
            foreach ($cv_data['experience'] as $exp) {
                $html .= '<div class="item">
                    <h3 class="item-title">' . htmlspecialchars($exp['position'] ?? 'Position') . '</h3>
                    <div class="item-meta">';
                
                $company = $exp['company_name'] ?? $exp['company'] ?? 'Company';
                $html .= htmlspecialchars($company);
                
                $start_date = $exp['start_date'] ?? '';
                $end_date = $exp['end_date'] ?? '';
                $is_current = $exp['is_current'] ?? false;
                
                if ($start_date) {
                    $start = date('M Y', strtotime($start_date));
                    $end = $is_current ? 'Present' : ($end_date ? date('M Y', strtotime($end_date)) : 'Present');
                    $html .= ' | ' . $start . ' - ' . $end;
                }
                
                if (!empty($exp['location'])) {
                    $html .= ' | ' . htmlspecialchars($exp['location']);
                }
                
                $html .= '</div>';
                
                if (!empty($exp['description'])) {
                    $html .= '<div class="item-description">' . nl2br(htmlspecialchars($exp['description'])) . '</div>';
                }
                
                $html .= '</div>';
            }
            
            $html .= '</section>';
        }
        
        // Education
        if (!empty($cv_data['education'])) {
            $html .= '<section class="section">
                <h2 class="section-title">Education</h2>';
            
            foreach ($cv_data['education'] as $edu) {
                $html .= '<div class="item">
                    <h3 class="item-title">' . htmlspecialchars($edu['degree'] ?? 'Degree') . '</h3>
                    <div class="item-meta">';
                
                $institution = $edu['institution'] ?? 'Institution';
                $html .= htmlspecialchars($institution);
                
                $start_date = $edu['start_date'] ?? '';
                $end_date = $edu['end_date'] ?? '';
                $is_current = $edu['is_current'] ?? false;
                
                if ($start_date) {
                    $start = date('M Y', strtotime($start_date));
                    $end = $is_current ? 'Present' : ($end_date ? date('M Y', strtotime($end_date)) : 'Present');
                    $html .= ' | ' . $start . ' - ' . $end;
                }
                
                if (!empty($edu['field_of_study'])) {
                    $html .= ' | ' . htmlspecialchars($edu['field_of_study']);
                }
                
                if (!empty($edu['grade'])) {
                    $html .= ' | GPA: ' . htmlspecialchars($edu['grade']);
                }
                
                $html .= '</div>';
                
                if (!empty($edu['description'])) {
                    $html .= '<div class="item-description">' . nl2br(htmlspecialchars($edu['description'])) . '</div>';
                }
                
                $html .= '</div>';
            }
            
            $html .= '</section>';
        }
        
        // Certificates
        if (!empty($cv_data['certificates'])) {
            $html .= '<section class="section">
                <h2 class="section-title">Certifications & Licenses</h2>';
            
            foreach ($cv_data['certificates'] as $cert) {
                $html .= '<div class="item">
                    <h3 class="item-title">' . htmlspecialchars($cert['name'] ?? $cert['title'] ?? 'Certificate') . '</h3>
                    <div class="item-meta">';
                
                if (!empty($cert['issuing_organization'])) {
                    $html .= htmlspecialchars($cert['issuing_organization']);
                }
                
                $issue_date = $cert['issue_date'] ?? '';
                $expiry_date = $cert['expiry_date'] ?? '';
                
                if ($issue_date) {
                    $html .= ' | Issued: ' . date('M Y', strtotime($issue_date));
                    if ($expiry_date) {
                        $html .= ' | Expires: ' . date('M Y', strtotime($expiry_date));
                    }
                }
                
                if (!empty($cert['credential_id'])) {
                    $html .= ' | ID: ' . htmlspecialchars($cert['credential_id']);
                }
                
                $html .= '</div>';
                
                if (!empty($cert['description'])) {
                    $html .= '<div class="item-description">' . nl2br(htmlspecialchars($cert['description'])) . '</div>';
                }
                
                $html .= '</div>';
            }
            
            $html .= '</section>';
        }
        
        // References
        if (!empty($cv_data['references'])) {
            $html .= '<section class="section">
                <h2 class="section-title">Professional References</h2>
                <div class="references-grid">';
            
            foreach ($cv_data['references'] as $ref) {
                $html .= '<div class="reference-item">
                    <h3 class="item-title">' . htmlspecialchars($ref['name'] ?? 'Reference') . '</h3>
                    <div class="item-meta">';
                
                $ref_details = [];
                if (!empty($ref['position'])) $ref_details[] = $ref['position'];
                if (!empty($ref['company'])) $ref_details[] = $ref['company'];
                
                if (!empty($ref_details)) {
                    $html .= implode(' | ', array_map('htmlspecialchars', $ref_details));
                }
                
                if (!empty($ref['relationship'])) {
                    $html .= '<br>Relationship: ' . htmlspecialchars($ref['relationship']);
                }
                
                $html .= '</div>';
                
                if (!empty($ref['email']) || !empty($ref['phone'])) {
                    $html .= '<div class="item-description">';
                    if (!empty($ref['email'])) $html .= '📧 ' . htmlspecialchars($ref['email']) . '<br>';
                    if (!empty($ref['phone'])) $html .= '📞 ' . htmlspecialchars($ref['phone']);
                    $html .= '</div>';
                }
                
                $html .= '</div>';
            }
            
            $html .= '</div>
            </section>';
        }
        
        // Footer
        $html .= '<footer class="footer">
            <p>Generated on ' . date('F j, Y \a\t g:i A') . ' | CV Builder Professional Resume System</p>
            <p style="font-style: italic; margin-top: 10px;">
                To save as PDF: Use your browser\'s Print function (Ctrl+P or Cmd+P) and select "Save as PDF"
            </p>
        </footer>
    </div>
    
    <script>
        function downloadHTML() {
            const element = document.createElement("a");
            const file = new Blob([document.documentElement.outerHTML], {type: "text/html"});
            element.href = URL.createObjectURL(file);
            element.download = "CV_' . sanitizeFilename($candidate_name) . '_' . date('Y-m-d') . '.html";
            document.body.appendChild(element);
            element.click();
            document.body.removeChild(element);
        }
        
        // Auto-print option
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get("autoprint") === "true") {
            setTimeout(() => window.print(), 1000);
        }
    </script>
</body>
</html>';
        
        return [
            'content' => $html, 
            'filename' => 'CV_Builder_' . sanitizeFilename($candidate_name) . '_' . date('Y-m-d') . '.html'
        ];
    }
    
    private function generateWithWkhtmltopdf($app, $cv_data) {
        if (!function_exists('exec')) return false;
        
        exec('wkhtmltopdf --version 2>&1', $output, $return_var);
        if ($return_var !== 0) return false;
        
        // Generate HTML first
        $html_result = $this->generateHTMLForPrint($app, $cv_data);
        if (!$html_result) return false;
        
        $tempHtml = tempnam(sys_get_temp_dir(), 'cv_') . '.html';
        $tempPdf = tempnam(sys_get_temp_dir(), 'cv_') . '.pdf';
        
        file_put_contents($tempHtml, $html_result['content']);
        
        $command = "wkhtmltopdf --page-size A4 --margin-top 0.75in --margin-right 0.75in --margin-bottom 0.75in --margin-left 0.75in --quiet \"$tempHtml\" \"$tempPdf\" 2>/dev/null";
        exec($command, $output, $return_var);
        
        if ($return_var === 0 && file_exists($tempPdf)) {
            $pdfContent = file_get_contents($tempPdf);
            $filename = str_replace('.html', '.pdf', $html_result['filename']);
            
            unlink($tempHtml);
            unlink($tempPdf);
            
            return ['content' => $pdfContent, 'filename' => $filename];
        }
        
        // Clean up on failure
        if (file_exists($tempHtml)) unlink($tempHtml);
        if (file_exists($tempPdf)) unlink($tempPdf);
        
        return false;
    }
    
    private function generateSimplePDF($app, $cv_data) {
        // This would need a proper PDF library - return false for now
        return false;
    }
    
    private function generateTextCV($app, $cv_data) {
        $candidate_name = trim(($app['first_name'] ?? '') . ' ' . ($app['last_name'] ?? ''));
        
        $text = str_repeat("=", 70) . "\n";
        $text .= "                      CURRICULUM VITAE\n";
        $text .= str_repeat("=", 70) . "\n\n";
        
        $text .= "PERSONAL INFORMATION\n";
        $text .= str_repeat("-", 25) . "\n";
        $text .= "Name: " . strtoupper($candidate_name) . "\n";
        if (!empty($app['email'])) $text .= "Email: {$app['email']}\n";
        if (!empty($app['phone'])) $text .= "Phone: {$app['phone']}\n";
        if (!empty($app['address'])) $text .= "Address: {$app['address']}\n";
        if (!empty($app['linkedin_url'])) $text .= "LinkedIn: {$app['linkedin_url']}\n";
        if (!empty($app['portfolio_url'])) $text .= "Portfolio: {$app['portfolio_url']}\n";
        $text .= "\n";
        
        // Add all other sections in text format...
        // (Implementation similar to previous text generation but more structured)
        
        $filename = 'CV_Builder_' . sanitizeFilename($candidate_name) . '_' . date('Y-m-d') . '.txt';
        return ['content' => $text, 'filename' => $filename];
    }
}

// Ensure sanitizeFilename function is available
if (!function_exists('sanitizeFilename')) {
    function sanitizeFilename($filename) {
        $filename = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $filename);
        $filename = preg_replace('/_{2,}/', '_', $filename);
        return trim($filename, '_');
    }
}
?>