<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in and is admin or teacher
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    header('Location: ../login.php');
    exit();
}

// Get filters
$search_class = isset($_GET['search_class']) ? (int)$_GET['search_class'] : 0;
$search_section = isset($_GET['search_section']) ? $_GET['search_section'] : '';
$search_session = isset($_GET['search_session']) ? $_GET['search_session'] : date('Y');
$search_exam = isset($_GET['search_exam']) ? (int)$_GET['search_exam'] : 0;
$search_subject = isset($_GET['search_subject']) ? (int)$_GET['search_subject'] : 0;
$exam_date = isset($_GET['exam_date']) ? $_GET['exam_date'] : date('Y-m-d');

// Get data for dropdowns
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$sessions = $pdo->query("SELECT DISTINCT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
if (empty($sessions)) {
    // Fallback to get sessions from students table if academic_sessions table doesn't exist
    $sessions = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC")->fetchAll(PDO::FETCH_COLUMN);
    $formatted_sessions = [];
    foreach ($sessions as $session) {
        $formatted_sessions[] = ['session_name' => $session];
    }
    $sessions = $formatted_sessions;
}
$exams = $pdo->query("SELECT id, name, exam_date FROM exams WHERE status = 'active' ORDER BY exam_date DESC")->fetchAll();
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();

// Get students based on filters
$students = [];
if ($search_class || $search_session) {
    $sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.class_id, 
                   c.name as class_name, c.section
            FROM students s
            JOIN classes c ON s.class_id = c.id
            WHERE s.status = 'active'";
    
    $params = [];
    if ($search_class) {
        $sql .= " AND s.class_id = ?";
        $params[] = $search_class;
    }
    if ($search_session) {
        $sql .= " AND s.session = ?";
        $params[] = $search_session;
    }
    if ($search_section) {
        $sql .= " AND c.section = ?";
        $params[] = $search_section;
    }
    
    $sql .= " ORDER BY c.name, c.section, s.roll_number, s.first_name";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
}

// Get exam information if exam is selected
$exam_info = null;
if ($search_exam) {
    $stmt = $pdo->prepare("SELECT name, exam_date, start_time, end_time FROM exams WHERE id = ?");
    $stmt->execute([$search_exam]);
    $exam_info = $stmt->fetch();
} elseif ($exam_date) {
    $stmt = $pdo->prepare("SELECT id, name, exam_date, start_time, end_time FROM exams WHERE exam_date = ?");
    $stmt->execute([$exam_date]);
    $exam_info = $stmt->fetch();
}

// Get subject name if subject is selected
$subject_name = '';
if ($search_subject) {
    $stmt = $pdo->prepare("SELECT name FROM subjects WHERE id = ?");
    $stmt->execute([$search_subject]);
    $subject_name = $stmt->fetchColumn();
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পরীক্ষার হাজিরা শীট - স্কুল ম্যানেজমেন্ট সিস্টেম</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @media print {
            body {
                background-color: white;
                padding: 0;
                margin: 0;
            }
            .no-print {
                display: none !important;
            }
            .print-container {
                box-shadow: none !important;
                margin: 0 !important;
                padding: 0 !important;
            }
        }
        
        .print-container {
            max-width: 21cm; /* A4 width */
            margin: 20px auto;
            padding: 20px;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            min-height: 29.7cm; /* A4 height */
        }
        
        .attendance-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        .attendance-table th, .attendance-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
            vertical-align: middle;
        }
        
        .attendance-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        
        .student-name-cell {
            text-align: left;
            min-width: 150px;
        }
        
        .signature-cell {
            height: 50px;
        }
        
        .header-info {
            margin-bottom: 20px;
        }
        
        .school-name {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 5px;
        }
        
        .report-title {
            font-size: 20px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 15px;
            text-decoration: underline;
        }
        
        .filter-info {
            text-align: center;
            margin-bottom: 15px;
            font-size: 16px;
        }
        
        .responsive-table {
            overflow-x: auto;
        }
        
        .exam-info-box {
            background-color: #e7f3ff;
            border: 1px solid #b8daff;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .exam-info-item {
            margin-bottom: 5px;
        }
        
        .exam-date-cell {
            background-color: #fff3cd;
            font-weight: bold;
        }
        
        .subject-cell {
            background-color: #d1ecf1;
            font-weight: bold;
        }
        
        .time-cell {
            background-color: #f8d7da;
            font-weight: bold;
        }
    </style>
</head>
<body class="bg-light">
    <div class="print-container">
        <div class="header-info">
            <div class="school-name">বিদ্যা মন্দির উচ্চ বিদ্যালয়</div>
            <div class="report-title">পরীক্ষার হাজিরা শীট</div>
            <div class="filter-info">
                <?php if ($search_class): ?>
                    <?php 
                    $class_info = null;
                    foreach ($classes as $class) {
                        if ($class['id'] == $search_class) {
                            $class_info = $class;
                            break;
                        }
                    }
                    if ($class_info) echo "ক্লাস: " . $class_info['name'] . ' - ' . $class_info['section'];
                    ?>
                <?php endif; ?>
                
                <?php if ($search_session): ?>
                    | সেশন: <?php echo $search_session; ?>
                <?php endif; ?>
                
                <?php if ($search_exam && $exam_info): ?>
                    | পরীক্ষা: <?php echo $exam_info['name']; ?>
                <?php elseif ($exam_date): ?>
                    | পরীক্ষার তারিখ: <?php echo $exam_date; ?>
                <?php endif; ?>
                
                <?php if ($search_subject && $subject_name): ?>
                    | বিষয়: <?php echo $subject_name; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="exam-info-box">
            <div class="row">
                <div class="col-md-3 exam-info-item">
                    <strong>পরীক্ষার তারিখ:</strong>
                    <?php echo $exam_info ? date('d/m/Y', strtotime($exam_info['exam_date'])) : ($exam_date ? date('d/m/Y', strtotime($exam_date)) : 'নির্বাচন করুন'); ?>
                </div>
                <div class="col-md-3 exam-info-item">
                    <strong>পরীক্ষার সময়:</strong>
                    <?php echo $exam_info ? $exam_info['start_time'] . ' - ' . $exam_info['end_time'] : 'নির্বাচন করুন'; ?>
                </div>
                <div class="col-md-3 exam-info-item">
                    <strong>পরীক্ষার নাম:</strong>
                    <?php echo $exam_info ? $exam_info['name'] : 'নির্বাচন করুন'; ?>
                </div>
                <div class="col-md-3 exam-info-item">
                    <strong>বিষয়:</strong>
                    <?php echo $subject_name ?: 'নির্বাচন করুন'; ?>
                </div>
            </div>
        </div>
        
        <div class="responsive-table">
            <?php if (!empty($students)): ?>
                <?php foreach ($students as $index => $student): ?>
                    <div class="mb-4">
                        <h5>ছাত্র/ছাত্রী: <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?> | রোল: <?php echo $student['roll_number']; ?> | ক্লাস: <?php echo $student['class_name'] . ' - ' . $student['section']; ?></h5>
                        
                        <table class="attendance-table">
                            <thead>
                                <tr>
                                    <th>ক্রমিক নং</th>
                                    <th class="student-name-cell">ছাত্র/ছাত্রীর নাম</th>
                                    <th>রোল</th>
                                    <th class="exam-date-cell">পরীক্ষার তারিখ</th>
                                    <th class="subject-cell">পরীক্ষার বিষয়</th>
                                    <th class="time-cell">পরীক্ষার সময়</th>
                                    <th>ছাত্র/ছাত্রীর<br>হাজিরা</th>
                                    <th>কক্ষপরি<br>হাজিরা</th>
                                    <th>স্বাক্ষর</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><?php echo $index + 1; ?></td>
                                    <td class="student-name-cell"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></td>
                                    <td><?php echo $student['roll_number']; ?></td>
                                    <td class="exam-date-cell"><?php echo $exam_info ? date('d/m/Y', strtotime($exam_info['exam_date'])) : ($exam_date ? date('d/m/Y', strtotime($exam_date)) : ''); ?></td>
                                    <td class="subject-cell"><?php echo $subject_name ?: 'নির্বাচন করুন'; ?></td>
                                    <td class="time-cell"><?php echo $exam_info ? $exam_info['start_time'] . ' - ' . $exam_info['end_time'] : ''; ?></td>
                                    <td>
                                        <select class="form-select form-select-sm">
                                            <option value="">নির্বাচন করুন</option>
                                            <option value="present">উপস্থিত</option>
                                            <option value="absent">অনুপস্থিত</option>
                                            <option value="late">বিলম্বে</option>
                                        </select>
                                    </td>
                                    <td>
                                        <select class="form-select form-select-sm">
                                            <option value="">নির্বাচন করুন</option>
                                            <option value="present">উপস্থিত</option>
                                            <option value="absent">অনুপস্থিত</option>
                                        </select>
                                    </td>
                                    <td></td>
                                </tr>
                            </tbody>
                        </table>
                        
                        <!-- Signature section for each student -->
                        <div class="mt-3" style="margin-top: 30px;">
                            <div class="row">
                                <div class="col-6 text-center">
                                    <div class="signature-cell">&nbsp;</div>
                                    <div>ছাত্র/ছাত্রীর স্বাক্ষর</div>
                                </div>
                                <div class="col-6 text-center">
                                    <div class="signature-cell">&nbsp;</div>
                                    <div>কক্ষপরির স্বাক্ষর</div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="alert alert-info text-center">
                    <i class="fas fa-info-circle fs-1 mb-3"></i>
                    <h5>কোন ছাত্র-ছাত্রী পাওয়া যায়নি</h5>
                    <p class="mb-0">ফিল্টার পরিবর্তন করে আবার চেষ্টা করুন</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Filter Panel -->
    <div class="container-fluid fixed-bottom bg-white shadow no-print p-3 border-top">
        <div class="row g-3 align-items-end">
            <div class="col-md-2">
                <label class="form-label">ক্লাস</label>
                <select class="form-select" id="search_class" name="search_class" onchange="updateFilters()">
                    <option value="">সব ক্লাস</option>
                    <?php foreach ($classes as $class): ?>
                        <option value="<?php echo $class['id']; ?>" <?php echo ($search_class == $class['id']) ? 'selected' : ''; ?>>
                            <?php echo $class['name'] . ' - ' . $class['section']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <label class="form-label">সেশন</label>
                <select class="form-select" id="search_session" name="search_session" onchange="updateFilters()">
                    <option value="">সব সেশন</option>
                    <?php foreach ($sessions as $session): ?>
                        <option value="<?php echo $session['session_name']; ?>" <?php echo ($search_session == $session['session_name']) ? 'selected' : ''; ?>>
                            <?php echo $session['session_name']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <label class="form-label">পরীক্ষা</label>
                <select class="form-select" id="search_exam" name="search_exam" onchange="updateFilters()">
                    <option value="">সব পরীক্ষা</option>
                    <?php foreach ($exams as $exam): ?>
                        <option value="<?php echo $exam['id']; ?>" <?php echo ($search_exam == $exam['id']) ? 'selected' : ''; ?>>
                            <?php echo $exam['name'] . ' (' . date('d/m/Y', strtotime($exam['exam_date'])) . ')'; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <label class="form-label">বিষয়</label>
                <select class="form-select" id="search_subject" name="search_subject" onchange="updateFilters()">
                    <option value="">সব বিষয়</option>
                    <?php foreach ($subjects as $subject): ?>
                        <option value="<?php echo $subject['id']; ?>" <?php echo ($search_subject == $subject['id']) ? 'selected' : ''; ?>>
                            <?php echo $subject['name'] . ' (' . $subject['code'] . ')'; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <label class="form-label">পরীক্ষার তারিখ</label>
                <input type="date" class="form-control" id="exam_date" name="exam_date" value="<?php echo $exam_date; ?>" onchange="updateFilters()">
            </div>
            
            <div class="col-md-2">
                <button class="btn btn-primary w-100" onclick="window.print()">
                    <i class="fas fa-print me-1"></i> প্রিন্ট
                </button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function updateFilters() {
            const classId = document.getElementById('search_class').value;
            const session = document.getElementById('search_session').value;
            const exam = document.getElementById('search_exam').value;
            const subject = document.getElementById('search_subject').value;
            const examDate = document.getElementById('exam_date').value;
            
            let params = new URLSearchParams();
            if (classId) params.append('search_class', classId);
            if (session) params.append('search_session', session);
            if (exam) params.append('search_exam', exam);
            if (subject) params.append('search_subject', subject);
            if (examDate) params.append('exam_date', examDate);
            
            window.location.href = '?' + params.toString();
        }
        
        // Initialize the page with filters
        document.addEventListener('DOMContentLoaded', function() {
            // Set the exam date to today if not set
            const examDateInput = document.getElementById('exam_date');
            if (!examDateInput.value) {
                examDateInput.value = new Date().toISOString().split('T')[0];
            }
        });
    </script>
</body>
</html>