<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';

// Try to load TCPDF
$tcpdfLoaded = false;
$vendorAutoload = __DIR__ . '/../../vendor/autoload.php';
if (file_exists($vendorAutoload)) {
    require_once $vendorAutoload;
    if (class_exists('TCPDF')) { $tcpdfLoaded = true; }
}
if (!$tcpdfLoaded) {
    $candidates = [
        __DIR__ . '/../../vendor/tecnickcom/tcpdf/tcpdf.php',
        __DIR__ . '/../../assets/vendor/libs/tcpdf/tcpdf.php'
    ];
    foreach ($candidates as $p) {
        if (file_exists($p)) { require_once $p; $tcpdfLoaded = true; break; }
    }
}

try {
    $academicYear = trim($_GET['academic_year'] ?? '');
    $examDate = trim($_GET['exam_date'] ?? '');
    $session = trim($_GET['session'] ?? '');
    
    if (!$academicYear || !$examDate) {
        throw new Exception('Academic Year and Exam Date are required');
    }
    
    // Get college information
    $collegeInfo = $pdo->query("SELECT * FROM tbl_branch LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    $collegeName = str_replace('Monark', '', $collegeInfo['branch_name'] ?? 'Autonomous College');
    
    // Get report data (same as generate_report.php)
    // Handle both formats: "2000-2001" and "2000-2001 Even/Odd"
    if (strpos($academicYear, ' ') !== false) {
        // Format: "2000-2001 Even" - extract base year
        $baseYear = explode(' ', $academicYear)[0];
        $whereConditions = [
            '(e.academic_year = ? OR e.academic_year = ?)',
            'et.exam_date = ?'
        ];
        $bindings = [$academicYear, $baseYear, $examDate];
    } else {
        // Format: "2000-2001" - match exact or with term
        $whereConditions = [
            '(e.academic_year = ? OR e.academic_year LIKE ?)',
            'et.exam_date = ?'
        ];
        $bindings = [$academicYear, $academicYear . ' %', $examDate];
    }
    
    if ($session) {
        $whereConditions[] = 'et.session = ?';
        $bindings[] = $session;
    }
    
    $whereClause = 'WHERE ' . implode(' AND ', $whereConditions);
    
    $stmt = $pdo->prepare("
        SELECT 
            id.duty_id,
            id.staff_id,
            id.role,
            id.status,
            s.staff_code,
            CONCAT(s.first_name, ' ', s.last_name) as invigilator_name,
            s.email,
            s.phone,
            h.hall_name,
            et.exam_date,
            et.session,
            et.start_time,
            et.end_time,
            ha.allocation_id,
            ha.num_students as total_students
        FROM invigilation_duty id
        JOIN staff s ON id.staff_id = s.staff_id
        JOIN halls h ON id.hall_id = h.hall_id
        JOIN exam_timetable et ON id.timetable_id = et.timetable_id
        JOIN exam_subjects es ON et.exam_subject_id = es.exam_subject_id
        JOIN exams e ON es.exam_id = e.exam_id
        JOIN hall_allocations ha ON id.timetable_id = ha.timetable_id AND id.hall_id = ha.hall_id
        $whereClause
        ORDER BY h.hall_name, id.role DESC, s.first_name
    ");
    
    $stmt->execute($bindings);
    $invigilators = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($invigilators)) {
        throw new Exception('No invigilator data found for the selected criteria');
    }
    
    // Process data for printing
    $processedData = [];
    $hallsCovered = [];
    $subjectsCovered = [];
    $totalStudents = 0;
    
    foreach ($invigilators as $invigilator) {
        $allocationId = $invigilator['allocation_id'];
        $hallName = $invigilator['hall_name'];
        
        // Get subjects for this allocation
        $subjectsStmt = $pdo->prepare("
            SELECT 
                s.subject_code,
                s.subject_name,
                COUNT(ss.seating_id) as student_count
            FROM student_seating ss
            JOIN student_registrations sr ON ss.registration_id = sr.registration_id
            JOIN exam_subjects es ON sr.exam_subject_id = es.exam_subject_id
            JOIN subjects s ON es.subject_id = s.subject_id
            WHERE ss.allocation_id = ?
            GROUP BY s.subject_id, s.subject_code, s.subject_name
            ORDER BY s.subject_code
        ");
        
        $subjectsStmt->execute([$allocationId]);
        $subjects = $subjectsStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get question papers
        $questionPapers = [];
        foreach ($subjects as $subject) {
            $questionPapers[] = [
                'subject_code' => $subject['subject_code'],
                'count' => ceil($subject['student_count'] / 10)
            ];
        }
        
        $processedData[] = [
            'staff_code' => $invigilator['staff_code'],
            'invigilator_name' => $invigilator['invigilator_name'],
            'role' => $invigilator['role'],
            'hall_name' => $hallName,
            'exam_date' => $invigilator['exam_date'],
            'session' => $invigilator['session'],
            'subjects' => $subjects,
            'question_papers' => $questionPapers,
            'total_students' => $invigilator['total_students']
        ];
        
        if (!in_array($hallName, $hallsCovered)) {
            $hallsCovered[] = $hallName;
        }
        
        foreach ($subjects as $subject) {
            if (!in_array($subject['subject_code'], $subjectsCovered)) {
                $subjectsCovered[] = $subject['subject_code'];
            }
        }
        
        $totalStudents += $invigilator['total_students'];
    }
    
    // Generate PDF if TCPDF is available
    if ($tcpdfLoaded) {
        $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
        $pdf->SetCreator('Autonomous College');
        $pdf->SetAuthor('Autonomous College');
        $pdf->SetTitle('Invigilator Report - ' . $examDate);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetMargins(15, 15, 15);
        $pdf->SetAutoPageBreak(true, 15);
        $pdf->AddPage();
        
        // Generate HTML content
        $html = generateInvigilatorReportHTML($collegeName, $academicYear, $examDate, $session, $processedData, count($hallsCovered), count($subjectsCovered), $totalStudents);
        
        $pdf->writeHTML($html, true, false, true, false, '');
        
        // Draw border frame
        $n = $pdf->getNumPages();
        for ($p=1; $p<=$n; $p++) {
            $pdf->setPage($p);
            $pdf->SetDrawColor(50,50,50);
            $pdf->Rect(10, 10, $pdf->getPageWidth()-20, $pdf->getPageHeight()-20);
        }
        
        $filename = 'Invigilator_Report_' . $examDate . '_' . date('Y-m-d_H-i-s') . '.pdf';
        
        // Log the report printing
        write_audit_log($pdo, [
            'module' => 'Hall Allocations & Invigilation',
            'action' => 'create',
            'entity_table' => 'invigilator_reports',
            'entity_id' => 'print_' . $examDate . '_' . ($session ?: 'all'),
            'after_data' => [
                'academic_year' => $academicYear,
                'exam_date' => $examDate,
                'session' => $session,
                'filename' => $filename,
                'format' => 'PDF',
                'halls_covered' => count($hallsCovered),
                'subjects_covered' => count($subjectsCovered),
                'total_students' => $totalStudents
            ],
            'message' => 'Printed invigilator report as PDF'
        ]);
        
        $pdf->Output($filename, 'D');
        exit;
    } else {
        // Fallback to HTML
        header('Content-Type: text/html');
        
        // Log the HTML report generation
        write_audit_log($pdo, [
            'module' => 'Hall Allocations & Invigilation',
            'action' => 'create',
            'entity_table' => 'invigilator_reports',
            'entity_id' => 'html_' . $examDate . '_' . ($session ?: 'all'),
            'after_data' => [
                'academic_year' => $academicYear,
                'exam_date' => $examDate,
                'session' => $session,
                'format' => 'HTML',
                'halls_covered' => count($hallsCovered),
                'subjects_covered' => count($subjectsCovered),
                'total_students' => $totalStudents
            ],
            'message' => 'Generated invigilator report as HTML (TCPDF not available)'
        ]);
        
        echo generateInvigilatorReportHTML($collegeName, $academicYear, $examDate, $session, $processedData, count($hallsCovered), count($subjectsCovered), $totalStudents);
        exit;
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

function generateInvigilatorReportHTML($collegeName, $academicYear, $examDate, $session, $data, $hallsCovered, $subjectsCovered, $totalStudents) {
    $html = '<style>
        @page { size: A4; margin: 15mm; }
        body{font-family:Arial, sans-serif; font-size:10px; line-height:1.3; margin:0; padding:0; color:#000;}
        h1{font-size:16px;margin:0 0 10px 0; font-weight:bold; color:#000; text-align:center;}
        h2{font-size:12px;margin:0 0 8px 0; font-weight:bold; color:#000;}
        table{width:100%;border-collapse:collapse;font-size:9px; margin-bottom:10px;}
        th,td{border:1px solid #000;padding:3px;}
        .header-info{margin-bottom:15px; text-align:center;}
        .summary{margin-bottom:15px;}
        .summary-item{display:inline-block; margin-right:20px; font-weight:bold;}
        .invigilator-table th{background:#f0f0f0; font-weight:bold; text-align:center;}
        .invigilator-table td{text-align:left;}
        .role-chief{font-weight:bold; color:#000;}
        .role-invigilator{color:#666;}
        .subjects{font-size:8px;}
        .question-papers{font-size:8px;}
    </style>';
    
    $html .= '<div class="header-info">';
    $html .= '<h1>' . htmlspecialchars($collegeName) . '</h1>';
    $html .= '<h2>INVIGILATOR REPORT</h2>';
    $html .= '<div><strong>Academic Year:</strong> ' . htmlspecialchars($academicYear) . ' | ';
    $html .= '<strong>Exam Date:</strong> ' . htmlspecialchars($examDate) . ' | ';
    $html .= '<strong>Session:</strong> ' . htmlspecialchars($session ?: 'All') . '</div>';
    $html .= '</div>';
    
    $html .= '<div class="summary">';
    $html .= '<div class="summary-item">Total Invigilators: ' . count($data) . '</div>';
    $html .= '<div class="summary-item">Halls Covered: ' . $hallsCovered . '</div>';
    $html .= '<div class="summary-item">Subjects: ' . $subjectsCovered . '</div>';
    $html .= '<div class="summary-item">Total Students: ' . $totalStudents . '</div>';
    $html .= '</div>';
    
    $html .= '<table class="invigilator-table">';
    $html .= '<thead>';
    $html .= '<tr>';
    $html .= '<th style="width:15%;">Invigilator Name</th>';
    $html .= '<th style="width:8%;">Code</th>';
    $html .= '<th style="width:8%;">Role</th>';
    $html .= '<th style="width:12%;">Hall/Room</th>';
    $html .= '<th style="width:8%;">Date</th>';
    $html .= '<th style="width:6%;">Session</th>';
    $html .= '<th style="width:20%;">Subjects & Count</th>';
    $html .= '<th style="width:15%;">Question Papers</th>';
    $html .= '<th style="width:8%;">Students</th>';
    $html .= '</tr>';
    $html .= '</thead>';
    $html .= '<tbody>';
    
    foreach ($data as $item) {
        $roleClass = $item['role'] === 'Chief Invigilator' ? 'role-chief' : 'role-invigilator';
        
        // Format subjects
        $subjectsText = '';
        foreach ($item['subjects'] as $subject) {
            $subjectsText .= $subject['subject_code'] . ' (' . $subject['student_count'] . '), ';
        }
        $subjectsText = rtrim($subjectsText, ', ');
        
        // Format question papers
        $qpText = '';
        foreach ($item['question_papers'] as $qp) {
            $qpText .= $qp['subject_code'] . '-' . $qp['count'] . ', ';
        }
        $qpText = rtrim($qpText, ', ');
        
        $html .= '<tr>';
        $html .= '<td class="' . $roleClass . '">' . htmlspecialchars($item['invigilator_name']) . '</td>';
        $html .= '<td>' . htmlspecialchars($item['staff_code']) . '</td>';
        $html .= '<td>' . htmlspecialchars($item['role']) . '</td>';
        $html .= '<td>' . htmlspecialchars($item['hall_name']) . '</td>';
        $html .= '<td>' . htmlspecialchars($item['exam_date']) . '</td>';
        $html .= '<td>' . htmlspecialchars($item['session']) . '</td>';
        $html .= '<td class="subjects">' . htmlspecialchars($subjectsText) . '</td>';
        $html .= '<td class="question-papers">' . htmlspecialchars($qpText) . '</td>';
        $html .= '<td>' . $item['total_students'] . '</td>';
        $html .= '</tr>';
    }
    
    $html .= '</tbody>';
    $html .= '</table>';
    
    $html .= '<div style="margin-top:20px; text-align:center; font-size:9px;">';
    $html .= '<div>Generated on: ' . date('d-m-Y H:i:s') . '</div>';
    $html .= '<div>Report prepared by: ' . htmlspecialchars($collegeName) . '</div>';
    $html .= '</div>';
    
    return $html;
}
?>
