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

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

// Get exam ID from URL parameter
$exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;

if ($exam_id <= 0) {
    header('Location: view_seat_plans.php');
    exit();
}

// Get site settings
require_once '../includes/site_settings.php';
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'প্রতিষ্ঠানের নাম';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Fetch exam details
$stmt = $pdo->prepare("
    SELECT 
        e.id as exam_id,
        e.name as exam_name,
        e.session,
        c.name as class_name,
        c.section,
        e.group_name,
        e.created_at
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    WHERE e.id = ?
");

$stmt->execute([$exam_id]);
$exam = $stmt->fetch();

if (!$exam) {
    header('Location: view_seat_plans.php');
    exit();
}

// Fetch subjects for this exam
$stmt = $pdo->prepare("
    SELECT 
        es.subject_id,
        s.name as subject_name,
        s.code as subject_code,
        es.exam_date,
        es.start_time,
        es.end_time
    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]);
$subjects = $stmt->fetchAll();

// Fetch distinct rooms for this exam
$stmt = $pdo->prepare("
    SELECT DISTINCT room_number
    FROM seat_arrangements
    WHERE exam_id = ?
    ORDER BY room_number
");

$stmt->execute([$exam_id]);
$rooms = $stmt->fetchAll();

// Fetch seat arrangements grouped by subject and room
$seat_arrangements = [];

foreach ($subjects as $subject) {
    foreach ($rooms as $room) {
        $stmt = $pdo->prepare("
            SELECT 
                sa.*,
                s.first_name,
                s.last_name,
                s.roll_number,
                s.student_id
            FROM seat_arrangements sa
            JOIN students s ON sa.student_id = s.id
            WHERE sa.exam_id = ? 
            AND sa.subject_id = ? 
            AND sa.room_number = ?
            ORDER BY sa.row_number, sa.column_number, sa.seat_number
        ");
        
        $stmt->execute([$exam_id, $subject['subject_id'], $room['room_number']]);
        $arrangements = $stmt->fetchAll();
        
        if (!empty($arrangements)) {
            $seat_arrangements[$subject['subject_id']][$room['room_number']] = $arrangements;
        }
    }
}

function h($s) {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

// Calculate statistics
$total_students = 0;
$total_seats = 0;

foreach ($seat_arrangements as $subject_arrangements) {
    foreach ($subject_arrangements as $room_arrangements) {
        $total_students += count($room_arrangements);
        foreach ($room_arrangements as $arrangement) {
            if ($arrangement['student_id']) {
                $total_seats++;
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo h($exam['exam_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>
        body { 
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        
        .header-section {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            border-radius: 10px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .header-section img {
            max-height: 80px;
            width: auto;
            margin-bottom: 15px;
        }
        
        .stat-card {
            border-radius: 10px;
            transition: transform 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-3px);
        }
        
        .subject-card {
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }
        
        .room-card {
            border-radius: 8px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.03);
            margin-bottom: 1.5rem;
        }
        
        .seat-box {
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 10px;
            margin: 5px;
            background-color: #f8f9fa;
            min-height: 80px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
        }
        
        .seat-box.occupied {
            background-color: #d1ecf1;
            border-color: #bee5eb;
        }
        
        .seat-box.empty {
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }
        
        .seat-number {
            font-weight: bold;
            font-size: 0.9rem;
        }
        
        .student-info {
            font-size: 0.8rem;
        }
        
        .room-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 10px;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .card {
                box-shadow: none;
                border: 1px solid #ddd;
            }
        }
    </style>
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="view_seat_plans.php">
                    <i class="fas fa-arrow-left"></i> সীট প্ল্যান তালিকা
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <!-- Header Section -->
        <div class="header-section text-center">
            <?php if ($logo_image): ?>
                <img src="../<?php echo h($logo_image); ?>" alt="Logo" style="max-height: <?php echo $logo_size; ?>px;">
            <?php endif; ?>
            <h1><i class="fas fa-chair"></i> <?php echo h($exam['exam_name']); ?></h1>
            <p class="lead"><?php echo h($site_name); ?></p>
            <p class="mb-0">
                ক্লাস: <?php echo h($exam['class_name'] . ' (' . $exam['section'] . ')'); ?> | 
                সেশন: <?php echo h($exam['session']); ?>
                <?php if ($exam['group_name']): ?> | গ্রুপ: <?php echo h($exam['group_name']); ?><?php endif; ?>
            </p>
        </div>
        
        <!-- Stats Cards -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="card stat-card bg-primary text-white h-100">
                    <div class="card-body text-center">
                        <h3><?php echo count($subjects); ?></h3>
                        <p class="mb-0">মোট বিষয়</p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card stat-card bg-success text-white h-100">
                    <div class="card-body text-center">
                        <h3><?php echo count($rooms); ?></h3>
                        <p class="mb-0">মোট রুম</p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card stat-card bg-info text-white h-100">
                    <div class="card-body text-center">
                        <h3><?php echo $total_seats; ?></h3>
                        <p class="mb-0">মোট সিট</p>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="card stat-card bg-warning text-white h-100">
                    <div class="card-body text-center">
                        <h3><?php echo $total_students; ?></h3>
                        <p class="mb-0">মোট ছাত্র/ছাত্রী</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Action Buttons -->
        <div class="row mb-4 no-print">
            <div class="col-12">
                <div class="d-flex justify-content-between">
                    <a href="view_seat_plans.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> ফিরে যান
                    </a>
                    <button class="btn btn-primary" onclick="window.print()">
                        <i class="fas fa-print"></i> প্রিন্ট করুন
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Subject Wise Seat Plans -->
        <?php if (empty($seat_arrangements)): ?>
            <div class="alert alert-info text-center">
                <i class="fas fa-info-circle"></i> এই পরীক্ষার জন্য কোন সীট প্ল্যান তৈরি করা হয়নি।
            </div>
        <?php else: ?>
            <?php foreach ($subjects as $subject): ?>
                <?php if (isset($seat_arrangements[$subject['subject_id']])): ?>
                    <div class="card subject-card">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0">
                                <i class="fas fa-book"></i> 
                                <?php echo h($subject['subject_name']); ?> (<?php echo h($subject['subject_code']); ?>)
                            </h5>
                            <small>
                                পরীক্ষার তারিখ: <?php echo h($subject['exam_date']); ?> | 
                                সময়: <?php echo h($subject['start_time']); ?> - <?php echo h($subject['end_time']); ?>
                            </small>
                        </div>
                        <div class="card-body">
                            <?php foreach ($rooms as $room): ?>
                                <?php if (isset($seat_arrangements[$subject['subject_id']][$room['room_number']])): ?>
                                    <?php $arrangements = $seat_arrangements[$subject['subject_id']][$room['room_number']]; ?>
                                    <div class="card room-card">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0">
                                                <i class="fas fa-door-open"></i> 
                                                <?php echo h($room['room_number']); ?>
                                                <span class="badge bg-secondary float-end">
                                                    <?php echo count($arrangements); ?> টি সিট
                                                </span>
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="room-grid">
                                                <?php foreach ($arrangements as $arrangement): ?>
                                                    <div class="seat-box <?php echo $arrangement['student_id'] ? 'occupied' : 'empty'; ?>">
                                                        <div class="seat-number">
                                                            <?php echo h($arrangement['seat_number']); ?>
                                                        </div>
                                                        <?php if ($arrangement['student_id']): ?>
                                                            <div class="student-info">
                                                                <div>রোল: <?php echo h($arrangement['roll_number']); ?></div>
                                                                <div>আইডি: <?php echo h($arrangement['student_id']); ?></div>
                                                            </div>
                                                        <?php else: ?>
                                                            <div class="student-info text-muted">
                                                                খালি
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <!-- Footer Note -->
        <div class="card no-print mt-4">
            <div class="card-body text-center">
                <p class="mb-0">
                    <i class="fas fa-info-circle"></i> 
                    প্রতিটি সিটে ছাত্র/ছাত্রীর রোল নাম্বার এবং আইডি দেখানো হয়েছে। খালি সিটগুলো লাল রঙে চিহ্নিত করা হয়েছে।
                </p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>