<?php
require_once '../../config/config.php';

try {
    // Get filter parameters
    $academicYear = isset($_GET['academic_year']) ? trim($_GET['academic_year']) : '';
    $courseId = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;
    $hallId = isset($_GET['hall_id']) ? (int)$_GET['hall_id'] : 0;
    $examDate = isset($_GET['exam_date']) ? trim($_GET['exam_date']) : '';
    $session = isset($_GET['session']) ? trim($_GET['session']) : '';
    $staffId = isset($_GET['staff_id']) ? (int)$_GET['staff_id'] : 0;
    $role = isset($_GET['role']) ? trim($_GET['role']) : '';
    $status = isset($_GET['status']) ? trim($_GET['status']) : '';

    // Build WHERE clause
    $where = [];
    $bindings = [];

    // Add filter conditions
    if ($hallId > 0) {
        $where[] = 'id.hall_id = ?';
        $bindings[] = $hallId;
    }

    if ($examDate !== '') {
        $where[] = 'id.exam_date = ?';
        $bindings[] = $examDate;
    }

    if ($session !== '') {
        $where[] = 'id.session = ?';
        $bindings[] = $session;
    }

    if ($staffId > 0) {
        $where[] = 'id.staff_id = ?';
        $bindings[] = $staffId;
    }

    if ($role !== '') {
        $where[] = 'id.role = ?';
        $bindings[] = $role;
    }

    if ($status !== '') {
        $where[] = 'id.status = ?';
        $bindings[] = $status;
    }

    $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    // Get invigilation duties data
    $sql = "SELECT 
                id.duty_id,
                id.hall_id,
                id.exam_date,
                id.session,
                id.staff_id,
                id.role,
                id.status,
                id.created_at,
                h.hall_name,
                h.capacity,
                s.first_name,
                s.last_name,
                s.staff_code,
                ha.num_students
            FROM invigilation_duties id
            LEFT JOIN halls h ON id.hall_id = h.hall_id
            LEFT JOIN staff s ON id.staff_id = s.staff_id
            LEFT JOIN hall_allocations ha ON id.allocation_id = ha.allocation_id
            $whereClause
            ORDER BY id.exam_date DESC, id.session, h.hall_name, id.role, s.first_name";

    $stmt = $pdo->prepare($sql);
    foreach ($bindings as $index => $value) {
        $stmt->bindValue($index + 1, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Debug information
    if (isset($_GET['debug']) && $_GET['debug'] === '1') {
        echo "<h3>Debug Information:</h3>";
        echo "<p><strong>SQL Query:</strong> " . $sql . "</p>";
        echo "<p><strong>Bindings:</strong> " . print_r($bindings, true) . "</p>";
        echo "<p><strong>Data Count:</strong> " . count($data) . "</p>";
        echo "<p><strong>Data:</strong></p>";
        echo "<pre>" . print_r($data, true) . "</pre>";
        exit;
    }

    // Get college information for header
    $collegeInfo = null;
    if (!empty($data)) {
        // Try to get college info from staff table
        $collegeSql = "SELECT DISTINCT col.college_id, col.college_name, col.college_code, 
                              col.address, col.location, col.logo, col.seal
                       FROM staff s
                       LEFT JOIN colleges col ON s.college_id = col.college_id
                       WHERE s.staff_id = ?
                       LIMIT 1";

        $stmtCollege = $pdo->prepare($collegeSql);
        $stmtCollege->execute([$data[0]['staff_id']]);
        $collegeData = $stmtCollege->fetch(PDO::FETCH_ASSOC);
        
        if ($collegeData) {
            $collegeInfo = [
                'college_id' => $collegeData['college_id'],
                'college_name' => $collegeData['college_name'],
                'college_code' => $collegeData['college_code'],
                'address' => $collegeData['address'],
                'location' => $collegeData['location'],
                'logo' => $collegeData['logo'],
                'seal' => $collegeData['seal']
            ];
        }
    }

    // Get exam details for header
    $examDetails = null;
    if (!empty($data)) {
        $examDetails = [
            'exam_date' => $data[0]['exam_date'],
            'session' => $data[0]['session']
        ];
    }

    // Generate HTML report
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Invigilation Duties Report</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 15px;
                background-color: white;
                font-size: 12px;
            }
            .report-container {
                max-width: 1200px;
                margin: 0 auto;
                background-color: white;
            }
            .header {
                text-align: center;
                margin-bottom: 20px;
                border-bottom: 2px solid #000;
                padding-bottom: 15px;
            }
            .header-top {
                display: flex;
                justify-content: center;
                align-items: flex-start;
                margin-bottom: 10px;
            }
            .college-logo {
                width: 80px;
                height: 80px;
                object-fit: contain;
                margin-right: 20px;
            }
            .header-center {
                flex: 1;
                text-align: center;
            }
            .proforma {
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 10px;
                text-decoration: underline;
            }
            .college-info {
                margin-bottom: 10px;
            }
            .college-name {
                font-size: 18px;
                font-weight: bold;
                color: #000;
                margin-bottom: 5px;
            }
            .college-address {
                font-size: 12px;
                color: #333;
                margin-bottom: 3px;
            }
            .college-location {
                font-size: 12px;
                color: #333;
            }
            .report-title {
                font-size: 14px;
                font-weight: bold;
                margin-bottom: 10px;
                text-decoration: underline;
            }
            .exam-details {
                font-size: 12px;
                margin-bottom: 10px;
            }
            .invigilation-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
                border: 2px solid #000;
            }
            .invigilation-table th,
            .invigilation-table td {
                border: 1px solid #000;
                padding: 8px;
                text-align: center;
                font-size: 12px;
                vertical-align: middle;
            }
            .invigilation-table th {
                background-color: #f0f0f0;
                font-weight: bold;
                font-size: 13px;
            }
            .date-session-header {
                writing-mode: vertical-rl;
                text-orientation: mixed;
                width: 80px;
                padding: 20px 5px;
            }
            .hall-header {
                width: 100px;
            }
            .staff-header {
                width: 150px;
            }
            .role-header {
                width: 120px;
            }
            .students-header {
                width: 80px;
            }
            .status-header {
                width: 100px;
            }
            .role-badge {
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: bold;
            }
            .role-chief {
                background-color: #dc3545;
                color: white;
            }
            .role-invigilator {
                background-color: #007bff;
                color: white;
            }
            .role-squad {
                background-color: #17a2b8;
                color: white;
            }
            .status-badge {
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: bold;
            }
            .status-assigned {
                background-color: #28a745;
                color: white;
            }
            .status-present {
                background-color: #007bff;
                color: white;
            }
            .status-absent {
                background-color: #dc3545;
                color: white;
            }
            .session-badge {
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: bold;
            }
            .session-fn {
                background-color: #007bff;
                color: white;
            }
            .session-an {
                background-color: #ffc107;
                color: black;
            }
            .footer {
                margin-top: 30px;
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
            }
            .footer-left {
                text-align: left;
            }
            .footer-right {
                text-align: right;
            }
            .signature-line {
                border-bottom: 1px solid #000;
                width: 200px;
                margin-top: 5px;
            }
            @media print {
                body {
                    background-color: white;
                    padding: 10px;
                    margin: 0;
                }
                .report-container {
                    max-width: none;
                }
            }
        </style>
    </head>
    <body>
        <div class="report-container">
            <!-- Header -->
            <div class="header">
                <div class="header-top">
                    <div class="college-logo-section">
                        <?php if ($collegeInfo && $collegeInfo['logo']): ?>
                            <img src="../../data/college/<?php echo htmlspecialchars($collegeInfo['logo']); ?>" alt="College Logo" class="college-logo" onerror="this.style.display='none';">
                        <?php else: ?>
                            <div class="college-logo" style="display: flex; align-items: center; justify-content: center; color: #999; font-size: 10px;">LOGO</div>
                        <?php endif; ?>
                    </div>
                    <div class="header-center">
                        <div class="proforma">INVIGILATION DUTIES REPORT</div>
                        <?php if ($collegeInfo): ?>
                            <div class="college-info">
                                <div class="college-name"><?php echo htmlspecialchars($collegeInfo['college_name']); ?></div>
                                <?php if ($collegeInfo['address']): ?>
                                    <div class="college-address"><?php echo htmlspecialchars($collegeInfo['address']); ?></div>
                                <?php endif; ?>
                                <?php if ($collegeInfo['location']): ?>
                                    <div class="college-location"><?php echo htmlspecialchars($collegeInfo['location']); ?></div>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <div class="college-name">ANNA UNIVERSITY, CHENNAI - 25</div>
                        <?php endif; ?>
                        <div class="report-title">Invigilation Duties Assignment Report</div>
                        <?php if ($collegeInfo): ?>
                            <div class="exam-details">
                                <strong>Centre: <?php echo htmlspecialchars($collegeInfo['college_code']); ?>-<?php echo htmlspecialchars($collegeInfo['college_name']); ?></strong>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>


            <!-- Invigilation Duties Table -->
            <table class="invigilation-table">
                <thead>
                    <tr>
                        <th class="date-session-header">Date & Session</th>
                        <th class="hall-header">Hall</th>
                        <th class="staff-header">Staff Name</th>
                        <th class="staff-header">Staff Code</th>
                        <th class="role-header">Role</th>
                        <th class="students-header">Students</th>
                        <th class="status-header">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($data)): ?>
                        <?php foreach ($data as $row): ?>
                        <tr>
                            <td>
                                <?php echo date('d-m-Y', strtotime($row['exam_date'])); ?><br>
                                <span class="session-badge session-<?php echo strtolower($row['session']); ?>">
                                    <?php echo $row['session']; ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($row['hall_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['staff_code']); ?></td>
                            <td>
                                <span class="role-badge role-<?php echo strtolower(str_replace(' ', '-', $row['role'])); ?>">
                                    <?php echo htmlspecialchars($row['role']); ?>
                                </span>
                            </td>
                            <td><?php echo $row['num_students'] ?? '-'; ?></td>
                            <td>
                                <span class="status-badge status-<?php echo strtolower($row['status']); ?>">
                                    <?php echo htmlspecialchars($row['status']); ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 20px; color: #666;">No invigilation duties found for the selected criteria</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Footer -->
            <div class="footer">
                <div class="footer-left">
                    <div>Date: _______________</div>
                    <div>Station: <?php echo $collegeInfo ? htmlspecialchars($collegeInfo['location']) : 'Nagapattinam'; ?></div>
                </div>
                <div class="footer-right">
                    <div>Signature of Chief Superintendent</div>
                    <div class="signature-line"></div>
                    <div style="margin-top: 5px;">with college seal</div>
                </div>
            </div>
        </div>

        <script>
            // Auto-print when page loads
            window.onload = function() {
                // Small delay to ensure page is fully loaded
                setTimeout(function() {
                    window.print();
                }, 500);
            };
            
            // Also handle print on key press (Ctrl+P)
            document.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'p') {
                    e.preventDefault();
                    window.print();
                }
            });
        </script>
    </body>
    </html>
    <?php

} catch (Exception $e) {
    echo "<h1>Error</h1>";
    echo "<p>An error occurred: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><strong>Debug Info:</strong></p>";
    echo "<ul>";
    echo "<li>Academic Year: " . htmlspecialchars($_GET['academic_year'] ?? 'Not set') . "</li>";
    echo "<li>Course ID: " . htmlspecialchars($_GET['course_id'] ?? 'Not set') . "</li>";
    echo "<li>Hall ID: " . htmlspecialchars($_GET['hall_id'] ?? 'Not set') . "</li>";
    echo "<li>Exam Date: " . htmlspecialchars($_GET['exam_date'] ?? 'Not set') . "</li>";
    echo "<li>Session: " . htmlspecialchars($_GET['session'] ?? 'Not set') . "</li>";
    echo "<li>Staff ID: " . htmlspecialchars($_GET['staff_id'] ?? 'Not set') . "</li>";
    echo "<li>Role: " . htmlspecialchars($_GET['role'] ?? 'Not set') . "</li>";
    echo "<li>Status: " . htmlspecialchars($_GET['status'] ?? 'Not set') . "</li>";
    echo "</ul>";
    echo "<p><strong>Stack Trace:</strong></p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}
?>
