<?php
// Enhanced PDF Generator with TCPDF for CV generation
class EnhancedPDFGenerator {
    
    public function generateCVPDF($app, $cv_data) {
        // Try TCPDF first, fallback to HTML method
        if ($this->hasTCPDF()) {
            return $this->generateWithTCPDF($app, $cv_data);
        } elseif ($this->hasWkhtmltopdf()) {
            return $this->generateWithWkhtmltopdf($app, $cv_data);
        } else {
            return $this->generateHTMLToPDF($app, $cv_data);
        }
    }
    
    private function hasTCPDF() {
        return class_exists('TCPDF') || file_exists(dirname(__FILE__) . '/tcpdf/tcpdf.php');
    }
    
    private function hasWkhtmltopdf() {
        if (!function_exists('exec')) return false;
        exec('wkhtmltopdf --version 2>&1', $output, $return_var);
        return $return_var === 0;
    }
    
    private function generateWithTCPDF($app, $cv_data) {
        // Include TCPDF if available
        if (!class_exists('TCPDF')) {
            $tcpdf_path = dirname(__FILE__) . '/tcpdf/tcpdf.php';
            if (file_exists($tcpdf_path)) {
                require_once $tcpdf_path;
            } else {
                return false; // TCPDF not available
            }
        }
        
        // Create PDF instance
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        // Set document information
        $candidate_name = trim(($app['first_name'] ?? '') . ' ' . ($app['last_name'] ?? ''));
        $pdf->SetCreator('CV Builder System');
        $pdf->SetAuthor($candidate_name);
        $pdf->SetTitle($candidate_name . ' - Curriculum Vitae');
        $pdf->SetSubject('Professional CV');
        
        // Remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        
        // Set margins
        $pdf->SetMargins(20, 20, 20);
        $pdf->SetAutoPageBreak(TRUE, 20);
        
        // Add page
        $pdf->AddPage();
        
        // Add candidate photo if available
        $this->addCandidatePhoto($pdf, $app);
        
        // Generate CV content
        $html = $this->generateComprehensiveCVHTML($app, $cv_data);
        
        // Write HTML content
        $pdf->writeHTML($html, true, false, true, false, '');
        
        // Output PDF
        return $pdf->Output('cv.pdf', 'S');
    }
    
    private function addCandidatePhoto($pdf, $app) {
        if (empty($app['profile_picture'])) return;
        
        $photo_path = UPLOAD_PATH . 'profiles/' . $app['profile_picture'];
        if (file_exists($photo_path)) {
            try {
                // Add photo to top right corner
                $pdf->Image($photo_path, 160, 20, 30, 40, '', '', 'T', false, 300, '', false, false, 1, false, false, false);
            } catch (Exception $e) {
                // Photo failed to load, continue without it
            }
        }
    }
    
    private function generateWithWkhtmltopdf($app, $cv_data) {
        $html = $this->generateComprehensiveCVHTML($app, $cv_data, true);
        
        $tempHtml = tempnam(sys_get_temp_dir(), 'cv_') . '.html';
        $tempPdf = tempnam(sys_get_temp_dir(), 'cv_') . '.pdf';
        
        file_put_contents($tempHtml, $html);
        
        $command = "wkhtmltopdf --page-size A4 --margin-top 15mm --margin-right 15mm --margin-bottom 15mm --margin-left 15mm --enable-local-file-access --quiet \"$tempHtml\" \"$tempPdf\" 2>/dev/null";
        exec($command, $output, $return_var);
        
        if ($return_var === 0 && file_exists($tempPdf)) {
            $pdfContent = file_get_contents($tempPdf);
            unlink($tempHtml);
            unlink($tempPdf);
            return $pdfContent;
        }
        
        // Clean up on failure
        if (file_exists($tempHtml)) unlink($tempHtml);
        if (file_exists($tempPdf)) unlink($tempPdf);
        return false;
    }
    
    private function generateHTMLToPDF($app, $cv_data) {
        // Basic HTML-based PDF (simplified structure)
        return $this->generateComprehensiveCVHTML($app, $cv_data, true);
    }
    
    private function generateComprehensiveCVHTML($app, $cv_data, $for_pdf = false) {
        $candidate_name = trim(($app['first_name'] ?? '') . ' ' . ($app['last_name'] ?? ''));
        $email = $app['email'] ?? '';
        $phone = $app['phone'] ?? '';
        
        $html = '<!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>CV - ' . htmlspecialchars($candidate_name) . '</title>
            <style>
                @page { margin: 15mm; size: A4; }
                body { 
                    font-family: "Arial", sans-serif; 
                    font-size: 11px; 
                    line-height: 1.4; 
                    color: #333;
                    margin: 0;
                    padding: 0;
                }
                .header { 
                    text-align: center; 
                    margin-bottom: 20px; 
                    border-bottom: 3px solid #2c3e50; 
                    padding-bottom: 15px;
                    position: relative;
                }';
        
        // Add photo styling if we have a photo
        if (!empty($app['profile_picture']) && $for_pdf) {
            $photo_path = UPLOAD_PATH . 'profiles/' . $app['profile_picture'];
            if (file_exists($photo_path)) {
                $html .= '
                .photo {
                    position: absolute;
                    top: 0;
                    right: 0;
                    width: 80px;
                    height: 100px;
                    border: 2px solid #2c3e50;
                    border-radius: 5px;
                }';
            }
        }
        
        $html .= '
                .header h1 { 
                    margin: 0 80px 5px 0; 
                    color: #2c3e50; 
                    font-size: 24px; 
                    font-weight: bold;
                }
                .header .contact { 
                    margin: 5px 80px 5px 0; 
                    color: #666; 
                    font-size: 10px;
                }
                .section { 
                    margin-bottom: 20px; 
                    page-break-inside: avoid;
                }
                .section h2 { 
                    color: #2c3e50; 
                    border-bottom: 2px solid #3498db; 
                    padding-bottom: 3px; 
                    margin-bottom: 10px; 
                    font-size: 14px;
                    font-weight: bold;
                }
                .item { 
                    margin-bottom: 12px; 
                    padding-left: 10px;
                }
                .item h3 { 
                    margin: 0 0 3px 0; 
                    color: #2c3e50; 
                    font-size: 12px;
                    font-weight: bold;
                }
                .item .meta { 
                    color: #7f8c8d; 
                    font-style: italic; 
                    margin-bottom: 5px; 
                    font-size: 10px;
                }
                .item .description { 
                    margin: 5px 0 0 15px; 
                    font-size: 10px;
                    line-height: 1.3;
                }
                .contact-grid {
                    display: table;
                    width: 100%;
                    margin: 10px 0;
                }
                .contact-row {
                    display: table-row;
                }
                .contact-cell {
                    display: table-cell;
                    padding: 2px 10px 2px 0;
                    font-size: 10px;
                }
                .skills-grid {
                    display: table;
                    width: 100%;
                }
                .skills-row {
                    display: table-row;
                }
                .skills-cell {
                    display: table-cell;
                    padding: 3px 15px 3px 0;
                    font-size: 10px;
                    vertical-align: top;
                }
            </style>
        </head>
        <body>
            <div class="header">';
        
        // Add photo if available
        if (!empty($app['profile_picture']) && $for_pdf) {
            $photo_path = UPLOAD_PATH . 'profiles/' . $app['profile_picture'];
            if (file_exists($photo_path)) {
                // For HTML, use base64 encoding for embedded images
                $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">';
            }
        }
        
        $html .= '<h1>' . htmlspecialchars($candidate_name) . '</h1>';
        
        // Contact information
        $html .= '<div class="contact-grid">';
        if ($email) $html .= '<div class="contact-row"><div class="contact-cell">📧 ' . htmlspecialchars($email) . '</div></div>';
        if ($phone) $html .= '<div class="contact-row"><div class="contact-cell">📞 ' . htmlspecialchars($phone) . '</div></div>';
        if (!empty($app['address'])) $html .= '<div class="contact-row"><div class="contact-cell">📍 ' . htmlspecialchars($app['address']) . '</div></div>';
        if (!empty($app['linkedin_url'])) $html .= '<div class="contact-row"><div class="contact-cell">💼 ' . htmlspecialchars($app['linkedin_url']) . '</div></div>';
        if (!empty($app['portfolio_url'])) $html .= '<div class="contact-row"><div class="contact-cell">🌐 ' . htmlspecialchars($app['portfolio_url']) . '</div></div>';
        $html .= '</div>';
        
        $html .= '</div>';
        
        // Professional Summary (from resume data)
        if (isset($cv_data['resume_summary']) && !empty($cv_data['resume_summary'])) {
            $html .= '<div class="section">
                <h2>Professional Summary</h2>
                <div class="item">
                    <p>' . nl2br(htmlspecialchars($cv_data['resume_summary'])) . '</p>
                </div>
            </div>';
        }
        
        // Skills Section
        if (isset($cv_data['skills']) && !empty($cv_data['skills'])) {
            $html .= '<div class="section">
                <h2>Skills & Competencies</h2>
                <div class="item skills-grid">';
            
            $skills_array = explode(',', $cv_data['skills']);
            $skills_array = array_map('trim', $skills_array);
            
            // Display skills in columns
            $skill_chunks = array_chunk($skills_array, ceil(count($skills_array) / 3));
            foreach ($skill_chunks as $chunk) {
                $html .= '<div class="skills-row">';
                foreach ($chunk as $skill) {
                    $html .= '<div class="skills-cell">• ' . htmlspecialchars($skill) . '</div>';
                }
                $html .= '</div>';
            }
            
            $html .= '</div></div>';
        }
        
        // Languages Section
        if (isset($cv_data['languages']) && !empty($cv_data['languages'])) {
            $html .= '<div class="section">
                <h2>Languages</h2>
                <div class="item">
                    <p>' . nl2br(htmlspecialchars($cv_data['languages'])) . '</p>
                </div>
            </div>';
        }
        
        // Work Experience Section
        if (!empty($cv_data['experience'])) {
            $html .= '<div class="section">
                <h2>Work Experience</h2>';
            foreach ($cv_data['experience'] as $exp) {
                $html .= '<div class="item">
                    <h3>' . htmlspecialchars($exp['position'] ?? 'Position') . '</h3>
                    <div class="meta">' . 
                        htmlspecialchars($exp['company_name'] ?? $exp['company'] ?? 'Company') . ' | ' . 
                        $this->formatDateRange($exp['start_date'] ?? '', $exp['end_date'] ?? '', $exp['is_current'] ?? false);
                
                if (!empty($exp['location'])) {
                    $html .= ' | ' . htmlspecialchars($exp['location']);
                }
                
                $html .= '</div>';
                
                if (!empty($exp['description'])) {
                    $html .= '<div class="description">' . nl2br(htmlspecialchars($exp['description'])) . '</div>';
                }
                $html .= '</div>';
            }
            $html .= '</div>';
        }
        
        // Education Section
        if (!empty($cv_data['education'])) {
            $html .= '<div class="section">
                <h2>Education</h2>';
            foreach ($cv_data['education'] as $edu) {
                $html .= '<div class="item">
                    <h3>' . htmlspecialchars($edu['degree'] ?? 'Degree') . '</h3>
                    <div class="meta">' . 
                        htmlspecialchars($edu['institution'] ?? 'Institution') . ' | ' . 
                        $this->formatDateRange($edu['start_date'] ?? '', $edu['end_date'] ?? '', $edu['is_current'] ?? false);
                
                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="description">' . nl2br(htmlspecialchars($edu['description'])) . '</div>';
                }
                $html .= '</div>';
            }
            $html .= '</div>';
        }
        
        // Certificates Section
        if (!empty($cv_data['certificates'])) {
            $html .= '<div class="section">
                <h2>Certificates & Licenses</h2>';
            foreach ($cv_data['certificates'] as $cert) {
                $html .= '<div class="item">
                    <h3>' . htmlspecialchars($cert['name'] ?? $cert['title'] ?? 'Certificate') . '</h3>
                    <div class="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="description">' . nl2br(htmlspecialchars($cert['description'])) . '</div>';
                }
                $html .= '</div>';
            }
            $html .= '</div>';
        }
        
        // References Section
        if (!empty($cv_data['references'])) {
            $html .= '<div class="section">
                <h2>Professional References</h2>';
            foreach ($cv_data['references'] as $ref) {
                $html .= '<div class="item">
                    <h3>' . htmlspecialchars($ref['name'] ?? 'Reference') . '</h3>
                    <div class="meta">';
                
                $ref_details = [];
                if (!empty($ref['position'])) $ref_details[] = $ref['position'];
                if (!empty($ref['company'])) $ref_details[] = $ref['company'];
                if (!empty($ref['relationship'])) $ref_details[] = '(' . $ref['relationship'] . ')';
                
                $html .= implode(' | ', array_map('htmlspecialchars', $ref_details));
                
                $html .= '</div>';
                
                $contact_info = [];
                if (!empty($ref['email'])) $contact_info[] = '📧 ' . $ref['email'];
                if (!empty($ref['phone'])) $contact_info[] = '📞 ' . $ref['phone'];
                
                if (!empty($contact_info)) {
                    $html .= '<div class="description">' . implode(' | ', array_map('htmlspecialchars', $contact_info)) . '</div>';
                }
                
                $html .= '</div>';
            }
            $html .= '</div>';
        }
        
        // Footer
        $html .= '<div style="text-align: center; margin-top: 30px; padding-top: 15px; border-top: 1px solid #bdc3c7; font-size: 9px; color: #7f8c8d;">
            <p>Generated on ' . date('F j, Y \a\t g:i A') . ' | CV Builder Professional Resume System</p>
        </div>';
        
        $html .= '</body></html>';
        
        return $html;
    }
    
    private function formatDateRange($start_date, $end_date, $is_current = false) {
        $start = $start_date ? date('M Y', strtotime($start_date)) : 'Unknown';
        
        if ($is_current) {
            return $start . ' - Present';
        } elseif ($end_date) {
            $end = date('M Y', strtotime($end_date));
            return $start . ' - ' . $end;
        } else {
            return $start;
        }
    }
}
?>