<?php
require_once 'fpdf.php';

class ResumePDFGenerator extends FPDF {
    private $candidateData;
    private $jobTitle;
    private $primaryColor;
    private $headerHeight = 60;
    private $leftColumnWidth = 70;
    
    public function __construct($candidateData, $jobTitle = '') {
        parent::__construct();
        $this->candidateData = $candidateData;
        $this->jobTitle = $jobTitle;
        $this->primaryColor = [255, 165, 0]; // Orange theme
        $this->SetAutoPageBreak(true, 15);
    }
    
    public function generateResume() {
        $this->AddPage();
        $this->drawHeader();
        $this->drawContactInfo();
        $this->drawMainContent();
        return $this->Output('S');
    }
    
    private function drawHeader() {
        // Header background
        $this->SetFillColor($this->primaryColor[0], $this->primaryColor[1], $this->primaryColor[2]);
        $this->Rect(0, 0, 210, $this->headerHeight, 'F');
        
        // Profile photo
        $profilePath = '';
        if (!empty($this->candidateData['profile_picture'])) {
            $profilePath = UPLOAD_PATH . 'profiles/' . $this->candidateData['profile_picture'];
            if (file_exists($profilePath)) {
                // Create circular profile photo effect
                $this->SetXY(15, 10);
                $this->Image($profilePath, 15, 10, 40, 40);
            }
        }
        
        // Name and title
        $this->SetXY(65, 15);
        $this->SetFont('Arial', 'B', 24);
        $this->SetTextColor(255, 255, 255);
        $fullName = trim($this->candidateData['first_name'] . ' ' . $this->candidateData['last_name']);
        $this->Cell(0, 12, $fullName, 0, 1);
        
        if (!empty($this->jobTitle)) {
            $this->SetX(65);
            $this->SetFont('Arial', '', 14);
            $this->Cell(0, 8, 'Applied for: ' . $this->jobTitle, 0, 1);
        }
        
        // Contact info in header
        $this->SetX(65);
        $this->SetFont('Arial', '', 10);
        $contactInfo = [];
        if (!empty($this->candidateData['email'])) {
            $contactInfo[] = $this->candidateData['email'];
        }
        if (!empty($this->candidateData['phone'])) {
            $contactInfo[] = $this->candidateData['phone'];
        }
        $this->Cell(0, 6, implode(' | ', $contactInfo), 0, 1);
        
        if (!empty($this->candidateData['address'])) {
            $this->SetX(65);
            $this->Cell(0, 6, $this->candidateData['address'], 0, 1);
        }
    }
    
    private function drawContactInfo() {
        $this->SetY($this->headerHeight + 10);
        $this->SetTextColor(0, 0, 0);
        
        // Store current position
        $startY = $this->GetY();
        
        // Two-column layout
        $this->drawLeftColumn();
        $leftColumnEndY = $this->GetY();
        
        $this->drawRightColumn();
        $rightColumnEndY = $this->GetY();
        
        // Move to the end of the longer column
        $maxY = max($leftColumnEndY, $rightColumnEndY);
        $this->SetY($maxY + 10);
    }
    
    private function drawLeftColumn() {
        $startY = $this->headerHeight + 10;
        $currentY = $startY;
        
        // Personal Information Section
        $this->SetXY(15, $currentY);
        $this->drawSectionTitle('PERSONAL INFO');
        $currentY = $this->GetY();
        
        $personalInfo = [
            'Date of Birth' => $this->candidateData['date_of_birth'] ?? 'Not provided',
            'Gender' => $this->candidateData['gender'] ?? 'Not specified'
        ];
        
        foreach ($personalInfo as $label => $value) {
            $this->SetXY(15, $currentY);
            $this->drawLeftColumnItem($label, $value);
            $currentY = $this->GetY();
        }
        
        // Application Status
        $currentY += 8;
        $this->SetXY(15, $currentY);
        $this->drawSectionTitle('STATUS');
        $currentY = $this->GetY();
        
        $this->SetXY(15, $currentY);
        $this->drawLeftColumnItem('Application Status', ucfirst($this->candidateData['status'] ?? 'Applied'));
        $currentY = $this->GetY();
        
        $this->SetXY(15, $currentY);
        $this->drawLeftColumnItem('Applied Date', date('M d, Y', strtotime($this->candidateData['applied_at'])));
    }
    
    private function drawRightColumn() {
        $startY = $this->headerHeight + 10;
        $rightX = $this->leftColumnWidth + 25;
        $currentY = $startY;
        
        // Professional Summary
        if (!empty($this->candidateData['summary'])) {
            $this->SetXY($rightX, $currentY);
            $this->drawSectionTitleRight('PROFESSIONAL SUMMARY');
            $currentY = $this->GetY();
            
            $this->SetXY($rightX, $currentY);
            $this->SetFont('Arial', '', 10);
            $this->MultiCell(120, 5, $this->candidateData['summary'], 0, 'L');
            $currentY = $this->GetY() + 8;
        }
        
        
    }
    
    private function drawMainContent() {
        // Continue in full width for work experience, education, etc.
        // Position is already set correctly by drawContactInfo()
        
        // Cover Letter Section (formatted like work experience)
        if (!empty($this->candidateData['cover_letter'])) {
            $this->drawFullWidthSectionTitle('COVER LETTER');
            $this->drawCoverLetter($this->candidateData['cover_letter']);
        }
        
        // Skills Section (formatted like work experience)
        if (!empty($this->candidateData['skills'])) {
            $this->drawFullWidthSectionTitle('KEY SKILLS');
            $this->drawSkills($this->candidateData['skills']);
        }
        
        // Work Experience Section
        if (isset($this->candidateData['work_experience']) && !empty($this->candidateData['work_experience'])) {
            $this->drawFullWidthSectionTitle('WORK EXPERIENCE');
            foreach ($this->candidateData['work_experience'] as $exp) {
                $this->drawWorkExperience($exp);
            }
        }
        
        // Education Section
        if (isset($this->candidateData['education']) && !empty($this->candidateData['education'])) {
            $this->drawFullWidthSectionTitle('EDUCATION');
            foreach ($this->candidateData['education'] as $edu) {
                $this->drawEducation($edu);
            }
        }
        
        // Certificates Section
        if (isset($this->candidateData['certificates']) && !empty($this->candidateData['certificates'])) {
            $this->drawFullWidthSectionTitle('CERTIFICATES & QUALIFICATIONS');
            foreach ($this->candidateData['certificates'] as $cert) {
                $this->drawCertificate($cert);
            }
        }
        
        // Documents Section
        if (isset($this->candidateData['documents']) && !empty($this->candidateData['documents'])) {
            $this->drawFullWidthSectionTitle('ADDITIONAL DOCUMENTS');
            $this->SetFont('Arial', '', 9);
            foreach ($this->candidateData['documents'] as $doc) {
                $this->SetX(15);
                $docType = ucfirst($doc['document_type']);
                $docTitle = $doc['title'];
                $this->Cell(0, 5, "• {$docType}: {$docTitle}", 0, 1);
            }
        }
    }
    
    private function drawSectionTitle($title) {
        $this->SetFont('Arial', 'B', 11);
        $this->SetTextColor($this->primaryColor[0], $this->primaryColor[1], $this->primaryColor[2]);
        $this->SetX(15);
        $this->Cell(0, 6, $title, 0, 1);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(2);
    }
    
    private function drawSectionTitleRight($title) {
        $this->SetFont('Arial', 'B', 14);
        $this->SetTextColor($this->primaryColor[0], $this->primaryColor[1], $this->primaryColor[2]);
        $this->Cell(0, 8, $title, 0, 1);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(3);
    }
    
    private function drawFullWidthSectionTitle($title) {
        $this->SetFont('Arial', 'B', 14);
        $this->SetTextColor($this->primaryColor[0], $this->primaryColor[1], $this->primaryColor[2]);
        $this->SetX(15);
        $this->Cell(0, 8, $title, 0, 1);
        
        // Draw underline
        $this->SetDrawColor($this->primaryColor[0], $this->primaryColor[1], $this->primaryColor[2]);
        $this->Line(15, $this->GetY(), 195, $this->GetY());
        $this->SetTextColor(0, 0, 0);
        $this->Ln(5);
    }
    
    private function drawLeftColumnItem($label, $value) {
        $startX = 15;
        $startY = $this->GetY();
        
        $this->SetXY($startX, $startY);
        $this->SetFont('Arial', 'B', 9);
        $this->Cell($this->leftColumnWidth - 5, 4, $label . ':', 0, 1);
        
        $this->SetX($startX);
        $this->SetFont('Arial', '', 9);
        $this->MultiCell($this->leftColumnWidth - 5, 4, $value, 0, 'L');
        $this->SetY($this->GetY() + 2);
    }
    
    private function drawCoverLetter($coverLetter) {
        $this->SetX(15);
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(0, 6, 'Letter of Interest', 0, 1);
        
        $this->SetX(15);
        $this->SetFont('Arial', 'I', 10);
        $this->Cell(0, 5, 'Submitted with application', 0, 1);
        
        $this->SetX(15);
        $this->SetFont('Arial', '', 10);
        $this->MultiCell(180, 5, $coverLetter, 0, 'L');
        $this->Ln(3);
    }
    
    private function drawSkills($skillsString) {
        $skills = explode(',', $skillsString);
        
        // Group skills by categories if possible (basic categorization)
        $techSkills = [];
        $softSkills = [];
        $otherSkills = [];
        
        foreach ($skills as $skill) {
            $skill = trim($skill);
            $skillLower = strtolower($skill);
            
            // Basic categorization based on common patterns
            if (preg_match('/\b(php|javascript|python|java|html|css|sql|mysql|react|vue|angular|node|laravel|django|bootstrap|git|docker|aws|azure)\b/i', $skillLower)) {
                $techSkills[] = $skill;
            } elseif (preg_match('/\b(communication|leadership|teamwork|management|problem solving|analytical|creative)\b/i', $skillLower)) {
                $softSkills[] = $skill;
            } else {
                $techSkills[] = $skill; // Default to technical
            }
        }
        
        // Display Technical Skills
        if (!empty($techSkills)) {
            $this->SetX(15);
            $this->SetFont('Arial', 'B', 12);
            $this->Cell(0, 6, 'Technical Skills', 0, 1);
            
            $this->SetX(15);
            $this->SetFont('Arial', '', 10);
            $techSkillsText = '• ' . implode('  • ', $techSkills);
            $this->MultiCell(180, 5, $techSkillsText, 0, 'L');
            $this->Ln(3);
        }
        
        // Display Soft Skills if any were identified
        if (!empty($softSkills)) {
            $this->SetX(15);
            $this->SetFont('Arial', 'B', 12);
            $this->Cell(0, 6, 'Core Competencies', 0, 1);
            
            $this->SetX(15);
            $this->SetFont('Arial', '', 10);
            $softSkillsText = '• ' . implode('  • ', $softSkills);
            $this->MultiCell(180, 5, $softSkillsText, 0, 'L');
            $this->Ln(3);
        }
    }
    
    private function drawWorkExperience($exp) {
        $this->SetX(15);
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(0, 6, $exp['position'] . ' at ' . $exp['company_name'], 0, 1);
        
        $this->SetX(15);
        $this->SetFont('Arial', 'I', 10);
        $period = $exp['start_date'];
        if ($exp['is_current']) {
            $period .= ' - Present';
        } elseif (!empty($exp['end_date'])) {
            $period .= ' - ' . $exp['end_date'];
        }
        $this->Cell(0, 5, $period, 0, 1);
        
        if (!empty($exp['description'])) {
            $this->SetX(15);
            $this->SetFont('Arial', '', 10);
            $this->MultiCell(180, 5, $exp['description'], 0, 'L');
        }
        $this->Ln(3);
    }
    
    private function drawEducation($edu) {
        $this->SetX(15);
        $this->SetFont('Arial', 'B', 12);
        $degree = !empty($edu['degree']) ? $edu['degree'] : 'Education';
        if (!empty($edu['field_of_study'])) {
            $degree .= ' in ' . $edu['field_of_study'];
        }
        $this->Cell(0, 6, $degree, 0, 1);
        
        $this->SetX(15);
        $this->SetFont('Arial', '', 10);
        $this->Cell(0, 5, $edu['institution'], 0, 1);
        
        $this->SetX(15);
        $this->SetFont('Arial', 'I', 9);
        $period = '';
        if (!empty($edu['start_date']) || !empty($edu['end_date'])) {
            $period = ($edu['start_date'] ?? '') . ' - ' . ($edu['end_date'] ?? '');
        }
        if (!empty($edu['grade'])) {
            $period .= (!empty($period) ? ' | ' : '') . 'Grade: ' . $edu['grade'];
        }
        if (!empty($period)) {
            $this->Cell(0, 4, $period, 0, 1);
        }
        
        if (!empty($edu['description'])) {
            $this->SetX(15);
            $this->SetFont('Arial', '', 9);
            $this->MultiCell(180, 4, $edu['description'], 0, 'L');
        }
        $this->Ln(3);
    }
    
    private function drawCertificate($cert) {
        $this->SetX(15);
        $this->SetFont('Arial', 'B', 11);
        $this->Cell(0, 5, $cert['title'], 0, 1);
        
        $this->SetX(15);
        $this->SetFont('Arial', '', 10);
        if (!empty($cert['issuing_organization'])) {
            $this->Cell(0, 4, 'Issued by: ' . $cert['issuing_organization'], 0, 1);
        }
        
        $this->SetX(15);
        $this->SetFont('Arial', 'I', 9);
        $certInfo = [];
        if (!empty($cert['issue_date'])) {
            $certInfo[] = 'Issued: ' . date('M Y', strtotime($cert['issue_date']));
        }
        if (!empty($cert['expiry_date'])) {
            $certInfo[] = 'Expires: ' . date('M Y', strtotime($cert['expiry_date']));
        }
        if (!empty($cert['credential_id'])) {
            $certInfo[] = 'ID: ' . $cert['credential_id'];
        }
        
        if (!empty($certInfo)) {
            $this->Cell(0, 4, implode(' | ', $certInfo), 0, 1);
        }
        
        if (!empty($cert['description'])) {
            $this->SetX(15);
            $this->SetFont('Arial', '', 9);
            $this->MultiCell(180, 4, $cert['description'], 0, 'L');
        }
        $this->Ln(2);
    }
    
    // Add footer with page numbers
    public function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(128, 128, 128);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . ' | Generated by Recruitment System', 0, 0, 'C');
    }
}

// Function to generate PDF for a candidate
function generateCandidateResumePDF($candidateData, $jobTitle = '') {
    try {
        $pdf = new ResumePDFGenerator($candidateData, $jobTitle);
        return $pdf->generateResume();
    } catch (Exception $e) {
        error_log("PDF Generation Error: " . $e->getMessage());
        return false;
    }
}
?>