<?php
/**
 * IBVTE Management System - PDF Generator
 * Handles Admit Cards, Certificates, and Affiliation Documents
 * Requires: composer require dompdf/dompdf
 */

if (!defined('IBVTE_ACCESS')) {
    die('Direct access not permitted');
}

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/db.php';

// Autoload dompdf
$autoloadPath = ROOT_PATH . 'vendor/autoload.php';
if (file_exists($autoloadPath)) {
    require_once $autoloadPath;
} else {
    // Fallback - dompdf not installed
    class PDFGeneratorFallback {
        public static function generate() {
            return ['success' => false, 'message' => 'PDF library not installed. Run: composer require dompdf/dompdf'];
        }
    }
}

use Dompdf\Dompdf;
use Dompdf\Options;

class PDFGenerator {
    private $db;
    private $dompdf;
    private static $instance = null;
    
    private function __construct() {
        $this->db = Database::getInstance();
        
        // Check if dompdf is available
        if (class_exists('Dompdf\Dompdf')) {
            $options = new Options();
            $options->set('isRemoteEnabled', true);
            $options->set('isHtml5ParserEnabled', true);
            $options->set('isFontSubsettingEnabled', true);
            $options->set('defaultFont', 'Arial');
            $options->set('chroot', ROOT_PATH);
            
            $this->dompdf = new Dompdf($options);
        }
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    // ============================================
    // ADMIT CARD GENERATION
    // ============================================
    
    /**
     * Generate Admit Card
     */
    public function generateAdmitCard($studentId, $examSession, $examType = 'final') {
        // Check if dompdf is available
        if (!$this->dompdf) {
            return ['success' => false, 'message' => 'PDF library not installed'];
        }
        
        // Fetch student data
        $student = $this->db->fetchOne(
            "SELECT s.*, c.course_name, c.course_code, c.duration_text as duration,
                    u.institution_name, u.institution_code,
                    ac.exam_centre, ac.exam_centre_address, ac.exam_date_from, 
                    ac.exam_date_to, ac.exam_timing, ac.admit_card_number
             FROM students s
             JOIN courses c ON s.course_id = c.id
             JOIN users u ON s.institution_id = u.id
             LEFT JOIN admit_cards ac ON s.id = ac.student_id 
                AND ac.exam_session = ? AND ac.exam_type = ?
             WHERE s.id = ?",
            [$examSession, $examType, $studentId]
        );
        
        if (!$student) {
            return ['success' => false, 'message' => 'Student not found'];
        }
        
        // Generate admit card number if not exists
        if (empty($student['admit_card_number'])) {
            $student['admit_card_number'] = 'ADMT' . date('Y') . str_pad($studentId, 6, '0', STR_PAD_LEFT);
            
            // Save to database
            $this->db->insert('admit_cards', [
                'student_id' => $studentId,
                'admit_card_number' => $student['admit_card_number'],
                'exam_session' => $examSession,
                'exam_type' => $examType,
                'exam_centre' => $student['exam_centre'] ?? 'To be announced',
                'exam_centre_address' => $student['exam_centre_address'] ?? '',
                'exam_date_from' => $student['exam_date_from'] ?? null,
                'exam_date_to' => $student['exam_date_to'] ?? null,
                'exam_timing' => $student['exam_timing'] ?? '10:00 AM - 1:00 PM',
                'generated_at' => date('Y-m-d H:i:s'),
                'generated_by' => $_SESSION['user_id'] ?? null,
                'pdf_path' => '' // Will update after generation
            ]);
        }
        
        // Build HTML
        $html = $this->buildAdmitCardHTML($student);
        
        // Generate PDF
        $filename = generatePdfFilename('admit_card', $student['admit_card_number']);
        $filepath = PDF_GENERATED_PATH . 'admit_cards/' . $filename;
        
        $result = $this->generatePDF($html, $filename, $filepath);
        
        if ($result['success']) {
            // Update database with PDF path
            $this->db->update('admit_cards', 
                ['pdf_path' => $filepath], 
                [
                    'student_id' => $studentId,
                    'exam_session' => $examSession,
                    'exam_type' => $examType
                ]
            );
        }
        
        return $result;
    }
    
    /**
     * Build Admit Card HTML Template
     */
    private function buildAdmitCardHTML($student) {
        $photoPath = !empty($student['photo_path']) ? $student['photo_path'] : 'assets/images/default-avatar.png';
        $qrData = json_encode([
            'admit_card' => $student['admit_card_number'],
            'roll' => $student['roll_number'],
            'name' => $student['full_name']
        ]);
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Admit Card - {$student['admit_card_number']}</title>
            <style>
                @page { margin: 0; size: A4; }
                body { 
                    font-family: Arial, sans-serif; 
                    margin: 0; 
                    padding: 0;
                    background: white;
                }
                .admit-card {
                    width: 210mm;
                    min-height: 297mm;
                    margin: 0 auto;
                    border: 8px double #3b0b7c;
                    padding: 20px;
                    box-sizing: border-box;
                }
                .header {
                    text-align: center;
                    border-bottom: 3px solid #3b0b7c;
                    padding-bottom: 15px;
                    margin-bottom: 20px;
                }
                .logo { height: 80px; margin-bottom: 10px; }
                .header h1 { 
                    color: #3b0b7c; 
                    font-size: 24px; 
                    margin: 5px 0;
                    text-transform: uppercase;
                }
                .header h2 { 
                    color: #666; 
                    font-size: 16px; 
                    margin: 5px 0;
                    font-weight: normal;
                }
                .exam-title {
                    background: linear-gradient(135deg, #3b0b7c, #6c4ab6);
                    color: white;
                    text-align: center;
                    padding: 10px;
                    font-size: 20px;
                    font-weight: bold;
                    margin: 20px 0;
                    border-radius: 5px;
                }
                .details-table {
                    width: 100%;
                    border-collapse: collapse;
                    margin: 20px 0;
                }
                .details-table td {
                    padding: 10px;
                    border: 1px solid #ddd;
                    font-size: 14px;
                }
                .details-table .label {
                    background: #f5f5f5;
                    font-weight: bold;
                    width: 35%;
                    color: #3b0b7c;
                }
                .photo-box {
                    width: 120px;
                    height: 150px;
                    border: 2px solid #3b0b7c;
                    float: right;
                    margin-left: 20px;
                    text-align: center;
                    line-height: 150px;
                    color: #999;
                    font-size: 12px;
                    background: #f9f9f9;
                }
                .photo-box img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
                .exam-schedule {
                    background: #f9f9f9;
                    border: 2px solid #3b0b7c;
                    padding: 15px;
                    margin: 20px 0;
                    border-radius: 5px;
                }
                .exam-schedule h3 {
                    color: #3b0b7c;
                    margin-top: 0;
                    border-bottom: 1px solid #ddd;
                    padding-bottom: 10px;
                }
                .instructions {
                    background: #fff8e1;
                    border: 1px solid #ffc107;
                    padding: 15px;
                    margin: 20px 0;
                    font-size: 12px;
                    border-radius: 5px;
                }
                .instructions h4 {
                    color: #f57c00;
                    margin-top: 0;
                }
                .instructions ol {
                    margin: 0;
                    padding-left: 20px;
                }
                .instructions li {
                    margin: 5px 0;
                }
                .signature-section {
                    margin-top: 40px;
                    display: flex;
                    justify-content: space-between;
                }
                .signature-box {
                    text-align: center;
                    width: 200px;
                }
                .signature-line {
                    border-top: 1px solid #333;
                    margin-top: 50px;
                    padding-top: 5px;
                    font-size: 12px;
                }
                .qr-code {
                    text-align: center;
                    margin-top: 20px;
                }
                .qr-code img {
                    width: 100px;
                    height: 100px;
                }
                .footer {
                    text-align: center;
                    margin-top: 30px;
                    font-size: 11px;
                    color: #666;
                    border-top: 1px solid #ddd;
                    padding-top: 15px;
                }
                .clear { clear: both; }
            </style>
        </head>
        <body>
            <div class='admit-card'>
                <div class='header'>
                    <img src='assets/images/logo.jpeg' class='logo' alt='IBVTE Logo'>
                    <h1>Indian Board of Vocational & Technical Education</h1>
                    <h2>An Autonomous Body Recognized by Government of India</h2>
                    <p>" . INSTITUTION_ADDRESS . "</p>
                </div>
                
                <div class='exam-title'>
                    EXAMINATION ADMIT CARD - " . strtoupper($student['exam_session']) . "
                </div>
                
                <div class='photo-box'>
                    <img src='{$photoPath}' alt='Student Photo'>
                </div>
                
                <table class='details-table'>
                    <tr>
                        <td class='label'>Admit Card No.</td>
                        <td><strong>{$student['admit_card_number']}</strong></td>
                    </tr>
                    <tr>
                        <td class='label'>Registration No.</td>
                        <td>{$student['registration_number']}</td>
                    </tr>
                    <tr>
                        <td class='label'>Roll Number</td>
                        <td>" . formatRollNumber($student['roll_number']) . "</td>
                    </tr>
                    <tr>
                        <td class='label'>Student Name</td>
                        <td><strong>{$student['full_name']}</strong></td>
                    </tr>
                    <tr>
                        <td class='label'>Father's Name</td>
                        <td>{$student['father_name']}</td>
                    </tr>
                    <tr>
                        <td class='label'>Date of Birth</td>
                        <td>" . formatDate($student['date_of_birth']) . "</td>
                    </tr>
                    <tr>
                        <td class='label'>Course</td>
                        <td>{$student['course_name']} ({$student['course_code']})</td>
                    </tr>
                    <tr>
                        <td class='label'>Institution</td>
                        <td>{$student['institution_name']}</td>
                    </tr>
                </table>
                
                <div class='clear'></div>
                
                <div class='exam-schedule'>
                    <h3>Examination Schedule</h3>
                    <table class='details-table'>
                        <tr>
                            <td class='label'>Exam Centre</td>
                            <td>{$student['exam_centre']}</td>
                        </tr>
                        <tr>
                            <td class='label'>Centre Address</td>
                            <td>{$student['exam_centre_address']}</td>
                        </tr>
                        <tr>
                            <td class='label'>Exam Date</td>
                            <td>" . formatDate($student['exam_date_from']) . " to " . formatDate($student['exam_date_to']) . "</td>
                        </tr>
                        <tr>
                            <td class='label'>Exam Timing</td>
                            <td>{$student['exam_timing']}</td>
                        </tr>
                    </table>
                </div>
                
                <div class='instructions'>
                    <h4>Important Instructions:</h4>
                    <ol>
                        <li>Bring this admit card and a valid photo ID proof to the examination center.</li>
                        <li>Reach the examination center at least 30 minutes before the scheduled time.</li>
                        <li>Electronic devices (mobile phones, calculators, smart watches) are strictly prohibited.</li>
                        <li>Follow all COVID-19 guidelines issued by the examination authority.</li>
                        <li>Any kind of malpractice will lead to disqualification.</li>
                    </ol>
                </div>
                
                <div class='signature-section'>
                    <div class='signature-box'>
                        <div class='signature-line'>Student Signature</div>
                    </div>
                    <div class='signature-box'>
                        <div class='qr-code'>
                            <img src='https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=" . urlencode($qrData) . "' alt='QR Code'>
                            <div style='font-size: 10px; margin-top: 5px;'>Scan to Verify</div>
                        </div>
                    </div>
                    <div class='signature-box'>
                        <div class='signature-line'>Controller of Examination</div>
                    </div>
                </div>
                
                <div class='footer'>
                    <p>This admit card is computer generated and does not require signature.</p>
                    <p>For queries, contact: " . INSTITUTION_PHONE . " | Email: " . INSTITUTION_EMAIL . "</p>
                    <p style='margin-top: 10px; font-size: 10px;'>Generated on: " . formatDateTime(date('Y-m-d H:i:s')) . "</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }
    
    // ============================================
    // CERTIFICATE GENERATION
    // ============================================
    
    /**
     * Generate Course Completion Certificate
     */
    public function generateCertificate($studentId, $certificateType = 'course_completion') {
        if (!$this->dompdf) {
            return ['success' => false, 'message' => 'PDF library not installed'];
        }
        
        // Fetch student with result data
        $student = $this->db->fetchOne(
            "SELECT s.*, c.course_name, c.course_code, c.duration_text as duration,
                    u.institution_name, u.institution_code
             FROM students s
             JOIN courses c ON s.course_id = c.id
             JOIN users u ON s.institution_id = u.id
             WHERE s.id = ? AND s.result_declared = 1",
            [$studentId]
        );
        
        if (!$student) {
            return ['success' => false, 'message' => 'Student not found or result not declared'];
        }
        
        // Generate certificate number
        $certificateNumber = 'IBVTE/' . date('Y') . '/' . strtoupper(substr($certificateType, 0, 3)) . '/' . str_pad($studentId, 6, '0', STR_PAD_LEFT);
        
        // Build certificate HTML
        $html = $this->buildCertificateHTML($student, $certificateNumber, $certificateType);
        
        // Generate PDF
        $filename = generatePdfFilename('certificate', $certificateNumber);
        $filepath = PDF_GENERATED_PATH . 'certificates/' . $filename;
        
        $result = $this->generatePDF($html, $filename, $filepath, 'A4', 'landscape');
        
        if ($result['success']) {
            // Save certificate record
            $this->db->insert('certificates', [
                'student_id' => $studentId,
                'certificate_number' => $certificateNumber,
                'certificate_type' => $certificateType,
                'course_id' => $student['course_id'],
                'session_year' => $student['session_year'],
                'issue_date' => date('Y-m-d'),
                'grade_obtained' => $this->getGradeFromPercentage($student['percentage']),
                'division' => $student['division'],
                'percentage' => $student['percentage'],
                'qr_code_data' => json_encode(['cert' => $certificateNumber, 'verify' => APP_URL . 'verify.php?c=' . $certificateNumber]),
                'verification_url' => APP_URL . 'verify.php?c=' . $certificateNumber,
                'generated_at' => date('Y-m-d H:i:s'),
                'generated_by' => $_SESSION['user_id'] ?? null,
                'pdf_path' => $filepath
            ]);
        }
        
        return $result;
    }
    
    /**
     * Build Certificate HTML Template
     */
    private function buildCertificateHTML($student, $certificateNumber, $type) {
        $divisionLabel = getDivisionLabel($student['division']);
        $grade = $this->getGradeFromPercentage($student['percentage']);
        $qrUrl = APP_URL . 'verify.php?c=' . $certificateNumber;
        
        $typeTitles = [
            'course_completion' => 'COURSE COMPLETION CERTIFICATE',
            'diploma' => 'DIPLOMA CERTIFICATE',
            'provisional' => 'PROVISIONAL CERTIFICATE',
            'migration' => 'MIGRATION CERTIFICATE',
            'character' => 'CHARACTER CERTIFICATE'
        ];
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Certificate - {$certificateNumber}</title>
            <style>
                @page { margin: 0; size: A4 landscape; }
                body { 
                    font-family: 'Times New Roman', serif; 
                    margin: 0; 
                    padding: 0;
                }
                .certificate {
                    width: 297mm;
                    height: 210mm;
                    position: relative;
                    background: linear-gradient(135deg, #fff 0%, #f8f4ff 100%);
                    border: 15px solid #3b0b7c;
                    padding: 30px;
                    box-sizing: border-box;
                }
                .border-inner {
                    width: 100%;
                    height: 100%;
                    border: 3px double #ffd700;
                    padding: 20px;
                    box-sizing: border-box;
                }
                .header {
                    text-align: center;
                }
                .logo { height: 60px; margin-bottom: 10px; }
                .header h1 { 
                    color: #3b0b7c; 
                    font-size: 28px; 
                    margin: 5px 0;
                    text-transform: uppercase;
                    letter-spacing: 3px;
                }
                .header h2 { 
                    color: #6c4ab6; 
                    font-size: 16px; 
                    margin: 5px 0;
                    font-weight: normal;
                }
                .govt-recognition {
                    background: #3b0b7c;
                    color: #ffd700;
                    padding: 5px 20px;
                    display: inline-block;
                    margin: 10px 0;
                    font-size: 12px;
                    letter-spacing: 2px;
                }
                .certificate-title {
                    text-align: center;
                    font-size: 24px;
                    color: #3b0b7c;
                    text-transform: uppercase;
                    letter-spacing: 5px;
                    margin: 20px 0;
                    font-weight: bold;
                    border-bottom: 2px solid #ffd700;
                    padding-bottom: 10px;
                }
                .certificate-body {
                    text-align: center;
                    font-size: 18px;
                    line-height: 2;
                    margin: 30px 0;
                }
                .highlight {
                    color: #3b0b7c;
                    font-weight: bold;
                    font-size: 20px;
                }
                .details-box {
                    background: rgba(59, 11, 124, 0.05);
                    border: 1px solid #3b0b7c;
                    padding: 15px;
                    margin: 20px 0;
                    text-align: left;
                    font-size: 14px;
                }
                .details-box table {
                    width: 100%;
                }
                .details-box td {
                    padding: 5px;
                }
                .details-box .label {
                    color: #3b0b7c;
                    font-weight: bold;
                    width: 40%;
                }
                .seal {
                    position: absolute;
                    bottom: 80px;
                    left: 60px;
                    width: 100px;
                    height: 100px;
                    border: 3px solid #3b0b7c;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 10px;
                    color: #3b0b7c;
                    text-align: center;
                    transform: rotate(-15deg);
                }
                .qr-code {
                    position: absolute;
                    bottom: 80px;
                    right: 60px;
                    text-align: center;
                }
                .qr-code img {
                    width: 80px;
                    height: 80px;
                    border: 1px solid #ddd;
                }
                .signature-section {
                    display: flex;
                    justify-content: space-between;
                    margin-top: 50px;
                    padding: 0 50px;
                }
                .signature {
                    text-align: center;
                    width: 200px;
                }
                .signature img {
                    max-width: 150px;
                    max-height: 50px;
                }
                .signature-line {
                    border-top: 1px solid #333;
                    margin-top: 10px;
                    padding-top: 5px;
                    font-size: 12px;
                }
                .certificate-number {
                    position: absolute;
                    top: 40px;
                    right: 50px;
                    font-size: 12px;
                    color: #666;
                }
                .date-section {
                    position: absolute;
                    bottom: 40px;
                    left: 50px;
                    font-size: 12px;
                    color: #666;
                }
                .watermark {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%) rotate(-45deg);
                    font-size: 80px;
                    color: rgba(59, 11, 124, 0.05);
                    font-weight: bold;
                    pointer-events: none;
                    z-index: 0;
                }
            </style>
        </head>
        <body>
            <div class='certificate'>
                <div class='watermark'>IBVTE</div>
                <div class='border-inner'>
                    <div class='certificate-number'>Cert. No: {$certificateNumber}</div>
                    
                    <div class='header'>
                        <img src='assets/images/logo.jpeg' class='logo' alt='IBVTE Logo'>
                        <h1>Indian Board of Vocational & Technical Education</h1>
                        <div class='govt-recognition'>AN AUTONOMOUS BODY RECOGNIZED BY GOVERNMENT OF INDIA</div>
                        <p style='font-size: 12px; color: #666;'>" . INSTITUTION_ADDRESS . "</p>
                    </div>
                    
                    <div class='certificate-title'>" . ($typeTitles[$type] ?? 'CERTIFICATE') . "</div>
                    
                    <div class='certificate-body'>
                        <p>This is to certify that</p>
                        <p class='highlight'>{$student['full_name']}</p>
                        <p>Son/Daughter of <span class='highlight'>{$student['father_name']}</span></p>
                        <p>has successfully completed the course</p>
                        <p class='highlight'>{$student['course_name']}</p>
                        <p>from <span class='highlight'>{$student['institution_name']}</span></p>
                        <p>with <span class='highlight'>{$divisionLabel}</span> ({$student['percentage']}%)</p>
                        <p>in the session <span class='highlight'>{$student['session_year']}</span></p>
                    </div>
                    
                    <div class='details-box'>
                        <table>
                            <tr>
                                <td class='label'>Registration Number:</td>
                                <td>{$student['registration_number']}</td>
                                <td class='label'>Roll Number:</td>
                                <td>" . formatRollNumber($student['roll_number']) . "</td>
                            </tr>
                            <tr>
                                <td class='label'>Grade:</td>
                                <td>{$grade}</td>
                                <td class='label'>Duration:</td>
                                <td>{$student['duration']}</td>
                            </tr>
                        </table>
                    </div>
                    
                    <div class='seal'>
                        Official<br>Seal
                    </div>
                    
                    <div class='qr-code'>
                        <img src='https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode($qrUrl) . "' alt='Verify Certificate'>
                        <div style='font-size: 10px; margin-top: 5px;'>Scan to Verify</div>
                    </div>
                    
                    <div class='signature-section'>
                        <div class='signature'>
                            <div class='signature-line'>Controller of Examination</div>
                            <div style='font-size: 10px; color: #666;'>Date: " . formatDate(date('Y-m-d')) . "</div>
                        </div>
                        <div class='signature'>
                            <div class='signature-line'>Chairman</div>
                            <div style='font-size: 10px; color: #666;'>IBVTE</div>
                        </div>
                        <div class='signature'>
                            <div class='signature-line'>Secretary</div>
                            <div style='font-size: 10px; color: #666;'>IBVTE</div>
                        </div>
                    </div>
                    
                    <div class='date-section'>
                        Date of Issue: " . formatDate(date('Y-m-d')) . "
                    </div>
                </div>
            </div>
        </body>
        </html>
        ";
    }
    
    // ============================================
    // COMMON PDF GENERATION
    // ============================================
    
    /**
     * Generate PDF from HTML
     */
    private function generatePDF($html, $filename, $filepath, $paper = 'A4', $orientation = 'portrait') {
        try {
            $this->dompdf->loadHtml($html);
            $this->dompdf->setPaper($paper, $orientation);
            $this->dompdf->render();
            
            // Save to file
            $output = $this->dompdf->output();
            file_put_contents($filepath, $output);
            
            return [
                'success' => true,
                'filename' => $filename,
                'filepath' => $filepath,
                'url' => str_replace(ROOT_PATH, APP_URL, $filepath)
            ];
        } catch (Exception $e) {
            logError('PDF Generation Failed', ['error' => $e->getMessage(), 'filename' => $filename]);
            return ['success' => false, 'message' => 'PDF generation failed: ' . $e->getMessage()];
        }
    }
    
    /**
     * Stream PDF to browser
     */
    public function streamPDF($filepath, $filename = null) {
        if (!file_exists($filepath)) {
            return ['success' => false, 'message' => 'File not found'];
        }
        
        $filename = $filename ?? basename($filepath);
        
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        header('Cache-Control: private, no-cache, must-revalidate');
        
        readfile($filepath);
        exit;
    }
    
    /**
     * Download PDF
     */
    public function downloadPDF($filepath, $filename = null) {
        if (!file_exists($filepath)) {
            return ['success' => false, 'message' => 'File not found'];
        }
        
        $filename = $filename ?? basename($filepath);
        
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        header('Cache-Control: private, no-cache, must-revalidate');
        
        readfile($filepath);
        exit;
    }
    
    /**
     * Get grade from percentage
     */
    private function getGradeFromPercentage($percentage) {
        if ($percentage >= 90) return 'A+';
        if ($percentage >= 80) return 'A';
        if ($percentage >= 70) return 'B+';
        if ($percentage >= 60) return 'B';
        if ($percentage >= 50) return 'C';
        if ($percentage >= 40) return 'D';
        return 'F';
    }
}

/**
 * Helper function
 */
function PDF() {
    return PDFGenerator::getInstance();
}
