<?php
// Simple PDF class using PHP's built-in functionality
class SimplePDFGenerator {
    private $content = '';
    
    public function __construct() {
        // We'll use wkhtmltopdf or create a basic PDF structure
    }
    
    public function generatePDFFromHTML($html, $filename) {
        // Try different methods to generate PDF
        
        // Method 1: Use wkhtmltopdf if available
        if ($this->hasWkhtmltopdf()) {
            return $this->generateWithWkhtmltopdf($html, $filename);
        }
        
        // Method 2: Create a simple PDF structure
        return $this->createSimplePDF($html, $filename);
    }
    
    private function hasWkhtmltopdf() {
        exec('wkhtmltopdf --version 2>&1', $output, $return_var);
        return $return_var === 0;
    }
    
    private function generateWithWkhtmltopdf($html, $filename) {
        $tempHtml = tempnam(sys_get_temp_dir(), 'report_') . '.html';
        $tempPdf = tempnam(sys_get_temp_dir(), 'report_') . '.pdf';
        
        file_put_contents($tempHtml, $html);
        
        $command = "wkhtmltopdf --page-size A4 --margin-top 0.75in --margin-right 0.75in --margin-bottom 0.75in --margin-left 0.75in \"$tempHtml\" \"$tempPdf\"";
        exec($command, $output, $return_var);
        
        if ($return_var === 0 && file_exists($tempPdf)) {
            $pdfContent = file_get_contents($tempPdf);
            unlink($tempHtml);
            unlink($tempPdf);
            return $pdfContent;
        }
        
        unlink($tempHtml);
        return false;
    }
    
    private function createSimplePDF($html, $filename) {
        // Create a basic PDF structure manually
        // This is a very simplified PDF - for production use a proper library
        
        $pdfContent = "%PDF-1.4\n";
        $pdfContent .= "1 0 obj\n";
        $pdfContent .= "<<\n";
        $pdfContent .= "/Type /Catalog\n";
        $pdfContent .= "/Pages 2 0 R\n";
        $pdfContent .= ">>\n";
        $pdfContent .= "endobj\n";
        
        $pdfContent .= "2 0 obj\n";
        $pdfContent .= "<<\n";
        $pdfContent .= "/Type /Pages\n";
        $pdfContent .= "/Kids [3 0 R]\n";
        $pdfContent .= "/Count 1\n";
        $pdfContent .= ">>\n";
        $pdfContent .= "endobj\n";
        
        $pdfContent .= "3 0 obj\n";
        $pdfContent .= "<<\n";
        $pdfContent .= "/Type /Page\n";
        $pdfContent .= "/Parent 2 0 R\n";
        $pdfContent .= "/MediaBox [0 0 612 792]\n";
        $pdfContent .= "/Contents 4 0 R\n";
        $pdfContent .= "/Resources << /Font << /F1 5 0 R >> >>\n";
        $pdfContent .= ">>\n";
        $pdfContent .= "endobj\n";
        
        // Extract text content from HTML (basic)
        $textContent = strip_tags($html);
        $textContent = preg_replace('/\s+/', ' ', $textContent);
        $textContent = substr($textContent, 0, 1000); // Limit content
        
        $streamContent = "BT\n/F1 12 Tf\n50 750 Td\n($textContent) Tj\nET";
        $streamLength = strlen($streamContent);
        
        $pdfContent .= "4 0 obj\n";
        $pdfContent .= "<<\n";
        $pdfContent .= "/Length $streamLength\n";
        $pdfContent .= ">>\n";
        $pdfContent .= "stream\n";
        $pdfContent .= $streamContent . "\n";
        $pdfContent .= "endstream\n";
        $pdfContent .= "endobj\n";
        
        $pdfContent .= "5 0 obj\n";
        $pdfContent .= "<<\n";
        $pdfContent .= "/Type /Font\n";
        $pdfContent .= "/Subtype /Type1\n";
        $pdfContent .= "/BaseFont /Helvetica\n";
        $pdfContent .= ">>\n";
        $pdfContent .= "endobj\n";
        
        $pdfContent .= "xref\n";
        $pdfContent .= "0 6\n";
        $pdfContent .= "0000000000 65535 f \n";
        $pdfContent .= "0000000009 65535 n \n";
        $pdfContent .= "0000000058 65535 n \n";
        $pdfContent .= "0000000115 65535 n \n";
        $pdfContent .= "0000000251 65535 n \n";
        $pdfContent .= "0000000350 65535 n \n";
        $pdfContent .= "trailer\n";
        $pdfContent .= "<<\n";
        $pdfContent .= "/Size 6\n";
        $pdfContent .= "/Root 1 0 R\n";
        $pdfContent .= ">>\n";
        $pdfContent .= "startxref\n";
        $pdfContent .= "435\n";
        $pdfContent .= "%%EOF\n";
        
        return $pdfContent;
    }
}

// Better approach: Use DOMPDF or TCPDF
// Let's download and include TCPDF
class PDFReportGenerator {
    private $data;
    private $title;
    private $period;
    private $company;
    
    public function __construct($reportData, $reportTitle, $period, $companyName) {
        $this->data = $reportData;
        $this->title = $reportTitle;
        $this->period = $period;
        $this->company = $companyName;
    }
    
    public function generate() {
        // Generate HTML content first
        $htmlContent = $this->generateHTMLForPDF();
        
        // Try to convert to actual PDF
        $pdfGenerator = new SimplePDFGenerator();
        $pdfContent = $pdfGenerator->generatePDFFromHTML($htmlContent, 'report');
        
        if ($pdfContent !== false) {
            return $pdfContent;
        }
        
        // If PDF generation fails, throw exception to trigger fallback
        throw new Exception('PDF generation failed');
    }
    
    private function generateWithTCPDF() {
        require_once(dirname(__FILE__) . '/tcpdf/tcpdf.php');
        
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        // Set document information
        $pdf->SetCreator('HR Analytics System');
        $pdf->SetAuthor($this->company);
        $pdf->SetTitle($this->title);
        
        // Set margins
        $pdf->SetMargins(20, 30, 20);
        $pdf->SetHeaderMargin(10);
        $pdf->SetFooterMargin(10);
        
        // Add a page
        $pdf->AddPage();
        
        // Set font
        $pdf->SetFont('helvetica', 'B', 20);
        
        // Title
        $pdf->Cell(0, 15, $this->title, 0, 1, 'C');
        $pdf->Ln(5);
        
        $pdf->SetFont('helvetica', '', 12);
        $pdf->Cell(0, 10, $this->company, 0, 1, 'C');
        $pdf->Cell(0, 10, 'Generated on ' . date('F j, Y'), 0, 1, 'C');
        $pdf->Cell(0, 10, 'Period: ' . $this->period, 0, 1, 'C');
        $pdf->Ln(10);
        
        // Add metrics
        if (isset($this->data['metrics'])) {
            $pdf->SetFont('helvetica', 'B', 16);
            $pdf->Cell(0, 10, 'Recruitment Summary', 0, 1);
            $pdf->Ln(5);
            
            $pdf->SetFont('helvetica', '', 12);
            $pdf->Cell(45, 10, 'Applications Received:', 0, 0);
            $pdf->Cell(20, 10, $this->data['metrics']['application_received']['total'] ?? 0, 0, 1);
            
            $pdf->Cell(45, 10, 'Shortlisted:', 0, 0);
            $pdf->Cell(20, 10, $this->data['metrics']['shortlisted']['total'] ?? 0, 0, 1);
            
            $pdf->Cell(45, 10, 'Interviewed:', 0, 0);
            $pdf->Cell(20, 10, $this->data['metrics']['interviewed']['total'] ?? 0, 0, 1);
            
            $pdf->Cell(45, 10, 'Hired:', 0, 0);
            $pdf->Cell(20, 10, $this->data['metrics']['hired']['total'] ?? 0, 0, 1);
        }
        
        // Add conversion rates
        if (isset($this->data['conversion'])) {
            $pdf->Ln(10);
            $pdf->SetFont('helvetica', 'B', 16);
            $pdf->Cell(0, 10, 'Conversion Rates', 0, 1);
            $pdf->Ln(5);
            
            $pdf->SetFont('helvetica', '', 12);
            $pdf->Cell(60, 10, 'Application to Shortlist:', 0, 0);
            $pdf->Cell(20, 10, ($this->data['conversion']['application_to_shortlist'] ?? 0) . '%', 0, 1);
            
            $pdf->Cell(60, 10, 'Shortlist to Interview:', 0, 0);
            $pdf->Cell(20, 10, ($this->data['conversion']['shortlist_to_interview'] ?? 0) . '%', 0, 1);
            
            $pdf->Cell(60, 10, 'Interview to Hire:', 0, 0);
            $pdf->Cell(20, 10, ($this->data['conversion']['interview_to_hire'] ?? 0) . '%', 0, 1);
            
            $pdf->Cell(60, 10, 'Overall Conversion:', 0, 0);
            $pdf->Cell(20, 10, ($this->data['conversion']['application_to_hire'] ?? 0) . '%', 0, 1);
        }
        
        // Add hiring funnel table
        if (isset($this->data['funnel']) && !empty($this->data['funnel'])) {
            $pdf->Ln(10);
            $pdf->SetFont('helvetica', 'B', 16);
            $pdf->Cell(0, 10, 'Hiring Funnel Analysis', 0, 1);
            $pdf->Ln(5);
            
            // Table header
            $pdf->SetFont('helvetica', 'B', 10);
            $pdf->Cell(60, 10, 'Job Position', 1, 0, 'C');
            $pdf->Cell(25, 10, 'Applications', 1, 0, 'C');
            $pdf->Cell(25, 10, 'Shortlisted', 1, 0, 'C');
            $pdf->Cell(25, 10, 'Interviewed', 1, 0, 'C');
            $pdf->Cell(20, 10, 'Hired', 1, 0, 'C');
            $pdf->Cell(25, 10, 'Success %', 1, 1, 'C');
            
            // Table content
            $pdf->SetFont('helvetica', '', 9);
            foreach ($this->data['funnel'] as $job) {
                $successRate = $job['applications'] > 0 ? round(($job['hired'] / $job['applications']) * 100, 1) : 0;
                $pdf->Cell(60, 8, substr($job['job_title'], 0, 25), 1, 0);
                $pdf->Cell(25, 8, $job['applications'], 1, 0, 'C');
                $pdf->Cell(25, 8, $job['shortlisted'] ?? 0, 1, 0, 'C');
                $pdf->Cell(25, 8, $job['interviewed'] ?? 0, 1, 0, 'C');
                $pdf->Cell(20, 8, $job['hired'], 1, 0, 'C');
                $pdf->Cell(25, 8, $successRate . '%', 1, 1, 'C');
            }
        }
        
        return $pdf->Output('report.pdf', 'S');
    }
    
    private function generateHTMLForPDF() {
        $html = '<!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>' . htmlspecialchars($this->title) . '</title>
            <style>
                @page { margin: 1in; size: A4; }
                body { font-family: Arial, sans-serif; font-size: 12px; line-height: 1.4; }
                .header { text-align: center; margin-bottom: 30px; border-bottom: 2px solid #333; padding-bottom: 20px; }
                .section { margin-bottom: 25px; }
                .section h2 { color: #333; border-bottom: 1px solid #ccc; padding-bottom: 5px; }
                table { width: 100%; border-collapse: collapse; margin: 15px 0; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f5f5f5; font-weight: bold; }
                .metrics { display: flex; justify-content: space-around; margin: 20px 0; }
                .metric { text-align: center; }
                .metric-number { font-size: 24px; font-weight: bold; color: #0066cc; }
                .metric-label { font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>' . htmlspecialchars($this->title) . '</h1>
                <p><strong>' . htmlspecialchars($this->company) . '</strong></p>
                <p>Generated on ' . date('F j, Y \a\t g:i A') . '</p>
                <p>Period: ' . htmlspecialchars($this->period) . '</p>
            </div>';

        if (isset($this->data['metrics'])) {
            $html .= '<div class="section">
                <h2>Recruitment Summary</h2>
                <div class="metrics">
                    <div class="metric">
                        <div class="metric-number">' . ($this->data['metrics']['application_received']['total'] ?? 0) . '</div>
                        <div class="metric-label">Applications</div>
                    </div>
                    <div class="metric">
                        <div class="metric-number">' . ($this->data['metrics']['shortlisted']['total'] ?? 0) . '</div>
                        <div class="metric-label">Shortlisted</div>
                    </div>
                    <div class="metric">
                        <div class="metric-number">' . ($this->data['metrics']['interviewed']['total'] ?? 0) . '</div>
                        <div class="metric-label">Interviewed</div>
                    </div>
                    <div class="metric">
                        <div class="metric-number">' . ($this->data['metrics']['hired']['total'] ?? 0) . '</div>
                        <div class="metric-label">Hired</div>
                    </div>
                </div>
            </div>';
        }

        if (isset($this->data['conversion'])) {
            $html .= '<div class="section">
                <h2>Conversion Rates</h2>
                <table>
                    <tr>
                        <th>Conversion Stage</th>
                        <th>Rate</th>
                    </tr>
                    <tr>
                        <td>Application → Shortlist</td>
                        <td>' . ($this->data['conversion']['application_to_shortlist'] ?? 0) . '%</td>
                    </tr>
                    <tr>
                        <td>Shortlist → Interview</td>
                        <td>' . ($this->data['conversion']['shortlist_to_interview'] ?? 0) . '%</td>
                    </tr>
                    <tr>
                        <td>Interview → Hire</td>
                        <td>' . ($this->data['conversion']['interview_to_hire'] ?? 0) . '%</td>
                    </tr>
                    <tr>
                        <td><strong>Overall Conversion</strong></td>
                        <td><strong>' . ($this->data['conversion']['application_to_hire'] ?? 0) . '%</strong></td>
                    </tr>
                </table>
            </div>';
        }

        if (isset($this->data['funnel']) && !empty($this->data['funnel'])) {
            $html .= '<div class="section">
                <h2>Hiring Funnel Analysis</h2>
                <table>
                    <thead>
                        <tr>
                            <th>Job Position</th>
                            <th>Applications</th>
                            <th>Shortlisted</th>
                            <th>Interviewed</th>
                            <th>Hired</th>
                            <th>Success Rate</th>
                        </tr>
                    </thead>
                    <tbody>';
            
            foreach ($this->data['funnel'] as $job) {
                $successRate = $job['applications'] > 0 ? round(($job['hired'] / $job['applications']) * 100, 1) : 0;
                $html .= '<tr>
                    <td>' . htmlspecialchars($job['job_title']) . '</td>
                    <td>' . $job['applications'] . '</td>
                    <td>' . ($job['shortlisted'] ?? 0) . '</td>
                    <td>' . ($job['interviewed'] ?? 0) . '</td>
                    <td>' . $job['hired'] . '</td>
                    <td>' . $successRate . '%</td>
                </tr>';
            }
            
            $html .= '</tbody></table></div>';
        }

        $html .= '<div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #ccc; font-size: 10px; color: #666;">
            <p>Report generated by HR Analytics System</p>
            <p>To convert to PDF: Press Ctrl+P (Windows) or Cmd+P (Mac) and select "Save as PDF"</p>
        </div>
        </body>
        </html>';

        return $html;
    }
}
?>