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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$exam_id = $_GET['id'] ?? '';

if (!$exam_id) {
    header('Location: routine.php');
    exit();
}

// Get exam details
$stmt = $pdo->prepare("
    SELECT e.*, c.name as class_name, c.section
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    WHERE e.id = ?
");
$stmt->execute([$exam_id]);
$exam_details = $stmt->fetch();

if (!$exam_details) {
    header('Location: routine.php');
    exit();
}

// Get exam subjects
$stmt = $pdo->prepare("
    SELECT es.*, s.name as subject_name, s.code as subject_code
    FROM exam_subjects es
    JOIN subjects s ON es.subject_id = s.id
    WHERE es.exam_id = ?
    ORDER BY es.exam_date, es.start_time
");
$stmt->execute([$exam_id]);
$exam_subjects = $stmt->fetchAll();

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'প্রতিষ্ঠানের নাম';
$site_address = $settings['site_address'] ?? 'ঠিকানা, ফোন: ০১৭xxxxxxxx';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;
$logo_opacity = isset($settings['logo_opacity']) ? floatval($settings['logo_opacity']) : 0.9;

// Use custom institution fields if they exist, otherwise use site settings
$institution_name = !empty($exam_details['custom_institution_name']) ? $exam_details['custom_institution_name'] : $site_name;
$institution_address = !empty($exam_details['custom_institution_address']) ? $exam_details['custom_institution_address'] : $site_address;
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $exam_details['name']; ?> - পরীক্ষার রুটিন</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/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">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* Use Hind Siliguri for Bengali text */
        html, body { font-family: 'Hind Siliguri', system-ui, -apple-system, 'Segoe UI', Roboto, Arial, sans-serif; }
        @media print {
            body { font-size: 12px; margin: 0; }
            .no-print { display: none !important; }
            .card { border: none; box-shadow: none; }
            .table { font-size: 11px; }
            .routine-table th, .routine-table td {
                border: 1px solid #000 !important;
                padding: 8px !important;
                text-align: center;
            }
        }
        .routine-table th, .routine-table td {
            border: 1px solid #000 !important;
            padding: 8px !important;
            text-align: center;
        }
        .header-section {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #000;
            padding-bottom: 20px;
        }
        .header-section img {
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
    </style>
</head>
<body class="bengali-text">
    <div class="container-fluid">
        <!-- Print Button -->
        <div class="no-print text-center mb-3">
            <button class="btn btn-primary" onclick="window.print()">
                <i class="fas fa-print"></i> প্রিন্ট করুন
            </button>
            <a href="admit_card.php?id=<?php echo $exam_id; ?>" class="btn btn-info">
                <i class="fas fa-address-card"></i> এডমিট কার্ড
            </a>
            <a href="routine.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> ফিরে যান
            </a>
        </div>

        <!-- Header Section -->
        <div class="header-section">
            <?php if ($logo_image): ?>
            <div class="text-center mb-3">
                <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" class="img-fluid" style="max-height: <?php echo $logo_size; ?>px; opacity: <?php echo $logo_opacity; ?>; max-width: 200px; object-fit: contain;">
            </div>
            <?php endif; ?>
            <h2><?php echo htmlspecialchars($institution_name); ?></h2>
            <p><?php echo htmlspecialchars($institution_address); ?></p>
            <h3 style="color: #007bff; margin-top: 20px;"><?php echo $exam_details['name']; ?></h3>
            <h4>পরীক্ষার রুটিন</h4>
            <p>
                <strong>ক্লাস:</strong> <?php echo $exam_details['class_name'] . ' - ' . $exam_details['section']; ?> |
                <strong>সেশন:</strong> <?php echo $exam_details['session']; ?>
                <?php if ($exam_details['group_name']): ?>
                    | <strong>গ্রুপ:</strong> <?php echo $exam_details['group_name']; ?>
                <?php endif; ?>
            </p>
            <?php if (!empty($exam_details['custom_institution_name']) || !empty($exam_details['custom_institution_address'])): ?>
            <div class="alert alert-info small mt-2">
                <i class="fas fa-info-circle"></i> 
                এই রুটিনে কাস্টম প্রতিষ্ঠানের নাম ও ঠিকানা ব্যবহার করা হয়েছে
            </div>
            <?php endif; ?>
        </div>

        <!-- Routine Table -->
        <?php if (!empty($exam_subjects)): ?>
            <?php
                // Group subjects by date
                $grouped_by_date = [];
                foreach ($exam_subjects as $row) {
                    $d = date('Y-m-d', strtotime($row['exam_date']));
                    if (!isset($grouped_by_date[$d])) { $grouped_by_date[$d] = []; }
                    $grouped_by_date[$d][] = $row;
                }
                // Preserve order as fetched (already ordered by exam_date, start_time)
                $ordered_dates = array_keys($grouped_by_date);
            ?>
            <div class="table-responsive">
                <table class="table table-bordered routine-table">
                    <thead style="background-color: #007bff; color: white;">
                        <tr>
                            <th style="width: 5%;">ক্রমিক</th>
                            <th style="width: 15%;">তারিখ</th>
                            <th style="width: 15%;">দিন</th>
                            <th style="width: 35%;">বিষয়</th>
                            <th style="width: 30%;">সময়</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $serial = 1; ?>
                        <?php foreach ($ordered_dates as $dateKey): ?>
                            <?php
                                $rows = $grouped_by_date[$dateKey];
                                // Build subjects string with slash
                                $subject_parts = [];
                                $time_parts = [];
                                foreach ($rows as $r) {
                                    $label = $r['subject_name'] . ($r['subject_code'] ? ' ('.$r['subject_code'].')' : '');
                                    $subject_parts[] = $label;
                                    $time_parts[] = date('h:i A', strtotime($r['start_time'])) . ' - ' . date('h:i A', strtotime($r['end_time']));
                                }
                                // Unique values
                                $time_parts = array_values(array_unique($time_parts));
                                $date_display = date('d/m/Y', strtotime($dateKey));
                                $days = [
                                    'Sunday' => 'রবিবার',
                                    'Monday' => 'সোমবার',
                                    'Tuesday' => 'মঙ্গলবার',
                                    'Wednesday' => 'বুধবার',
                                    'Thursday' => 'বৃহস্পতিবার',
                                    'Friday' => 'শুক্রবার',
                                    'Saturday' => 'শনিবার'
                                ];
                                $day_display = $days[date('l', strtotime($dateKey))];
                            ?>
                            <tr>
                                <td><?php echo $serial++; ?></td>
                                <td><?php echo $date_display; ?></td>
                                <td><?php echo $day_display; ?></td>
                                <td style="text-align: left; padding-left: 10px;">
                                    <strong><?php echo implode(' / ', $subject_parts); ?></strong>
                                </td>
                                <td><?php echo !empty($time_parts) ? implode(' / ', $time_parts) : '-'; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Instructions -->
            <div style="margin-top: 30px; border-top: 1px solid #000; padding-top: 20px;">
                <h5><i class="fas fa-exclamation-triangle"></i> পরীক্ষার নির্দেশনা:</h5>
                <div class="row">
                    <div class="col-md-6">
                        <ul>
                            <li>পরীক্ষার ১৫ মিনিট আগে হলে প্রবেশ করতে হবে</li>
                            <li>পরীক্ষা শুরুর ৩০ মিনিট পর হল ত্যাগ করা যাবে</li>
                            <li>প্রয়োজনীয় স্টেশনারি সাথে আনতে হবে</li>
                            <li>মোবাইল ফোন ব্যবহার সম্পূর্ণ নিষিদ্ধ</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <ul>
                            <li>পরীক্ষার হলে শান্তি বজায় রাখতে হবে</li>
                            <li>অসদুপায় অবলম্বন করা যাবে না</li>
                            <li>প্রবেশপত্র সাথে রাখতে হবে</li>
                            <li>পরীক্ষকের নির্দেশ মেনে চলতে হবে</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div style="margin-top: 40px; border-top: 1px solid #000; padding-top: 20px;">
                <div class="row">
                    <div class="col-md-4 text-center">
                        <div style="border-top: 1px solid #000; margin-top: 50px; padding-top: 5px;">
                            <strong>পরীক্ষা নিয়ন্ত্রক</strong>
                        </div>
                    </div>
                    <div class="col-md-4 text-center">
                        <div style="border-top: 1px solid #000; margin-top: 50px; padding-top: 5px;">
                            <strong>উপাধ্যক্ষ</strong>
                        </div>
                    </div>
                    <div class="col-md-4 text-center">
                        <div style="border-top: 1px solid #000; margin-top: 50px; padding-top: 5px;">
                            <strong>প্রধান শিক্ষক</strong>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-4">
                    <small>
                        প্রকাশের তারিখ: <?php echo date('d/m/Y'); ?> | 
                        মোট বিষয়: <?php echo count($exam_subjects); ?>টি |
                        পরীক্ষার মেয়াদ: <?php echo date('d/m/Y', strtotime(min(array_column($exam_subjects, 'exam_date')))); ?> থেকে 
                        <?php echo date('d/m/Y', strtotime(max(array_column($exam_subjects, 'exam_date')))); ?>
                    </small>
                </div>
            </div>
        <?php else: ?>
            <div class="alert alert-warning text-center">
                <i class="fas fa-exclamation-triangle"></i> এই পরীক্ষার জন্য কোন বিষয় যোগ করা হয়নি
            </div>
        <?php endif; ?>
    </div>

    <script>
        // Auto print when page loads (optional)
        // window.onload = function() { window.print(); }
    </script>
</body>
</html>