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

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

$success_message = '';
$error_message = '';
$exam_id = $_GET['exam_id'] ?? '';

// Get all exams for dropdown
$all_exams = $pdo->query("
    SELECT e.id, e.name, c.name as class_name, c.section, e.session, e.group_name
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    ORDER BY e.created_at DESC
")->fetchAll();

// Get exam details if selected
$exam_details = null;
$students = [];

if ($exam_id) {
    $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) {
        // Get students for this exam - ordered by roll number
        $stmt = $pdo->prepare("
            SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.guardian_name, s.group_name
            FROM students s
            WHERE s.class_id = ? AND s.session = ?
            ORDER BY s.roll_number
        ");
        $stmt->execute([$exam_details['class_id'], $exam_details['session']]);
        $students = $stmt->fetchAll();
    }
}

// Handle seat arrangement generation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['generate_seats'])) {
    $exam_id = $_POST['exam_id'];
    $room_config = $_POST['room_config'] ?? [];
    
    try {
        $pdo->beginTransaction();
        
        // Clear existing seat arrangements for this exam
        $stmt = $pdo->prepare("DELETE FROM seat_arrangements WHERE exam_id = ?");
        $stmt->execute([$exam_id]);
        
        // Get all exam subjects for this exam
        $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();
        
        // Apply the same seating arrangement for all subjects
        $room_data = $room_config['general'] ?? [];
        $room_number = $room_data['room'] ?? 'Room-1';
        $benches_per_row = intval($room_data['benches_per_row'] ?? 5);
        $seating_pattern = $room_data['pattern'] ?? 'rows';
        $students_per_bench = $room_data['students_per_bench'] ?? 'single'; // 'single' or 'double'
        
        $total_students = count($students);
        $benches_needed = $students_per_bench === 'double' ? ceil($total_students / 2) : $total_students;
        
        // Create seating based on pattern
        $student_index = 0;
        $bench_count = 0;
        
        switch ($seating_pattern) {
            case 'columns':
                // Arrange in columns
                $cols = $benches_per_row;
                $rows = ceil($benches_needed / $cols);
                
                for ($col = 1; $col <= $cols; $col++) {
                    for ($row = 1; $row <= $rows; $row++) {
                        if ($student_index >= $total_students) break;
                        
                        $bench_count++;
                        $seat_number = $room_number . '-B' . str_pad($bench_count, 3, '0', STR_PAD_LEFT);
                        
                        // Insert seating for all subjects for this student
                        foreach ($exam_subjects as $subject) {
                            $stmt = $pdo->prepare("
                                INSERT INTO seat_arrangements 
                                (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                            ");
                            $stmt->execute([
                                $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                $room_number, $seat_number . '-A', $row, $col,
                                $subject['exam_date']
                            ]);
                        }
                        
                        $student_index++;
                        
                        // If double seating and there's another student
                        if ($students_per_bench === 'double' && $student_index < $total_students) {
                            // Second student on the same bench
                            foreach ($exam_subjects as $subject) {
                                $stmt = $pdo->prepare("
                                    INSERT INTO seat_arrangements 
                                    (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->execute([
                                    $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                    $room_number, $seat_number . '-B', $row, $col,
                                    $subject['exam_date']
                                ]);
                            }
                            
                            $student_index++;
                        }
                    }
                    if ($student_index >= $total_students) break;
                }
                break;
                
            case 'zigzag':
                // Arrange in zigzag pattern
                $cols = $benches_per_row;
                $rows = ceil($benches_needed / $cols);
                $reverse = false;
                
                for ($row = 1; $row <= $rows; $row++) {
                    if (!$reverse) {
                        // Left to right
                        for ($col = 1; $col <= $cols; $col++) {
                            if ($student_index >= $total_students) break;
                            
                            $bench_count++;
                            $seat_number = $room_number . '-B' . str_pad($bench_count, 3, '0', STR_PAD_LEFT);
                            
                            // Insert seating for all subjects for this student
                            foreach ($exam_subjects as $subject) {
                                $stmt = $pdo->prepare("
                                    INSERT INTO seat_arrangements 
                                    (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->execute([
                                    $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                    $room_number, $seat_number . '-A', $row, $col,
                                    $subject['exam_date']
                                ]);
                            }
                            
                            $student_index++;
                            
                            // If double seating and there's another student
                            if ($students_per_bench === 'double' && $student_index < $total_students) {
                                // Second student on the same bench
                                foreach ($exam_subjects as $subject) {
                                    $stmt = $pdo->prepare("
                                        INSERT INTO seat_arrangements 
                                        (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                                    ");
                                    $stmt->execute([
                                        $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                        $room_number, $seat_number . '-B', $row, $col,
                                        $subject['exam_date']
                                    ]);
                                }
                                
                                $student_index++;
                            }
                        }
                    } else {
                        // Right to left
                        for ($col = $cols; $col >= 1; $col--) {
                            if ($student_index >= $total_students) break;
                            
                            $bench_count++;
                            $seat_number = $room_number . '-B' . str_pad($bench_count, 3, '0', STR_PAD_LEFT);
                            
                            // Insert seating for all subjects for this student
                            foreach ($exam_subjects as $subject) {
                                $stmt = $pdo->prepare("
                                    INSERT INTO seat_arrangements 
                                    (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->execute([
                                    $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                    $room_number, $seat_number . '-A', $row, $col,
                                    $subject['exam_date']
                                ]);
                            }
                            
                            $student_index++;
                            
                            // If double seating and there's another student
                            if ($students_per_bench === 'double' && $student_index < $total_students) {
                                // Second student on the same bench
                                foreach ($exam_subjects as $subject) {
                                    $stmt = $pdo->prepare("
                                        INSERT INTO seat_arrangements 
                                        (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                                    ");
                                    $stmt->execute([
                                        $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                        $room_number, $seat_number . '-B', $row, $col,
                                        $subject['exam_date']
                                    ]);
                                }
                                
                                $student_index++;
                            }
                        }
                    }
                    $reverse = !$reverse;
                    if ($student_index >= $total_students) break;
                }
                break;
                
            case 'diagonal':
                // Arrange in diagonal pattern
                $cols = $benches_per_row;
                $rows = ceil($benches_needed / $cols);
                $diag_row = 1;
                $diag_col = 1;
                
                for ($i = 0; $i < $benches_needed; $i++) {
                    if ($student_index >= $total_students) break;
                    
                    $bench_count++;
                    $seat_number = $room_number . '-B' . str_pad($bench_count, 3, '0', STR_PAD_LEFT);
                    
                    // Insert seating for all subjects for this student
                    foreach ($exam_subjects as $subject) {
                        $stmt = $pdo->prepare("
                            INSERT INTO seat_arrangements 
                            (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([
                            $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                            $room_number, $seat_number . '-A', $diag_row, $diag_col,
                            $subject['exam_date']
                        ]);
                    }
                    
                    $student_index++;
                    
                    // If double seating and there's another student
                    if ($students_per_bench === 'double' && $student_index < $total_students) {
                        // Second student on the same bench
                        foreach ($exam_subjects as $subject) {
                            $stmt = $pdo->prepare("
                                INSERT INTO seat_arrangements 
                                (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                            ");
                            $stmt->execute([
                                $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                $room_number, $seat_number . '-B', $diag_row, $diag_col,
                                $subject['exam_date']
                            ]);
                        }
                        
                        $student_index++;
                    }
                    
                    // Move diagonally
                    $diag_col++;
                    if ($diag_col > $cols) {
                        $diag_col = 1;
                        $diag_row++;
                    }
                    
                    if ($diag_row > $rows) {
                        $diag_row = 1;
                    }
                    
                    if ($student_index >= $total_students) break;
                }
                break;
                
            case 'rows':
            default:
                // Default: arrange in rows
                $cols = $benches_per_row;
                $rows = ceil($benches_needed / $cols);
                
                for ($row = 1; $row <= $rows; $row++) {
                    for ($col = 1; $col <= $cols; $col++) {
                        if ($student_index >= $total_students) break;
                        
                        $bench_count++;
                        $seat_number = $room_number . '-B' . str_pad($bench_count, 3, '0', STR_PAD_LEFT);
                        
                        // Insert seating for all subjects for this student
                        foreach ($exam_subjects as $subject) {
                            $stmt = $pdo->prepare("
                                INSERT INTO seat_arrangements 
                                (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                            ");
                            $stmt->execute([
                                $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                $room_number, $seat_number . '-A', $row, $col,
                                $subject['exam_date']
                            ]);
                        }
                        
                        $student_index++;
                        
                        // If double seating and there's another student
                        if ($students_per_bench === 'double' && $student_index < $total_students) {
                            // Second student on the same bench
                            foreach ($exam_subjects as $subject) {
                                $stmt = $pdo->prepare("
                                    INSERT INTO seat_arrangements 
                                    (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->execute([
                                    $exam_id, $subject['subject_id'], $students[$student_index]['id'],
                                    $room_number, $seat_number . '-B', $row, $col,
                                    $subject['exam_date']
                                ]);
                            }
                            
                            $student_index++;
                        }
                    }
                    if ($student_index >= $total_students) break;
                }
                break;
        }
        
        $pdo->commit();
        $success_message = "সীট বিন্যাস সফলভাবে তৈরি করা হয়েছে!";
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_message = "ত্রুটি: " . $e->getMessage();
    }
}
?>

<!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.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">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background-color: #f8f9fa;
        }
        .bengali-text {
            font-family: 'Hind Siliguri', sans-serif;
        }
        .room-config-card {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 15px;
            padding: 15px;
            background-color: #f8f9fa;
        }
    </style>
</head>
<body class="bengali-text">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <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="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="routine.php">
                    <i class="fas fa-calendar"></i> পরীক্ষার রুটিন
                </a>
                <a class="nav-link" href="seat_card.php">
                    <i class="fas fa-chair"></i> সীট কার্ড
                </a>
                <a class="nav-link" href="seat_arrangements.php">
                    <i class="fas fa-chair"></i> সীট ব্যবস্থাপনা
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-cogs"></i> সীট বিন্যাস জেনারেটর</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <!-- Exam Selection -->
                        <form method="GET" action="">
                            <div class="row mb-4">
                                <div class="col-md-8">
                                    <div class="mb-3">
                                        <label for="exam_id" class="form-label">পরীক্ষা নির্বাচন করুন</label>
                                        <select class="form-select" id="exam_id" name="exam_id" required onchange="this.form.submit()">
                                            <option value="">পরীক্ষা নির্বাচন করুন</option>
                                            <?php foreach ($all_exams as $exam): ?>
                                                <option value="<?php echo $exam['id']; ?>" 
                                                        <?php echo ($exam_id == $exam['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $exam['name'] . ' - ' . $exam['class_name'] . ' (' . $exam['section'] . ')'; ?>
                                                    <?php if ($exam['group_name']): ?>
                                                        - <?php echo $exam['group_name']; ?>
                                                    <?php endif; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <!-- Room Configuration Form -->
                        <?php if ($exam_details && !empty($students)): 
                            // Get exam subjects for display purposes
                            $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();
                        ?>
                            <form method="POST" action="">
                                <input type="hidden" name="generate_seats" value="1">
                                <input type="hidden" name="exam_id" value="<?php echo $exam_id; ?>">
                                
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle"></i> 
                                    মোট ছাত্র/ছাত্রী: <?php echo count($students); ?> জন | 
                                    বিষয়: <?php echo count($exam_subjects); ?> টি
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-12 mb-4">
                                        <div class="room-config-card">
                                            <h6 class="mb-3">
                                                <i class="fas fa-university"></i> 
                                                সাধারণ সীটিং কনফিগারেশন
                                            </h6>
                                            
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <label class="form-label">রুম নম্বর</label>
                                                    <input type="text" class="form-control" 
                                                        name="room_config[general][room]" 
                                                        value="Main-Room" required>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <label class="form-label">বেঞ্চ প্রতি সারি</label>
                                                    <input type="number" class="form-control" 
                                                        name="room_config[general][benches_per_row]" 
                                                        value="5" min="1" max="20" required>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <label class="form-label">বেঞ্চে ছাত্র/ছাত্রী</label>
                                                    <select class="form-select" 
                                                        name="room_config[general][students_per_bench]">
                                                        <option value="single">১ জন (একক)</option>
                                                        <option value="double" selected>২ জন (দ্বৈত)</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <label class="form-label">সীটিং প্যাটার্ন</label>
                                                    <select class="form-select" 
                                                        name="room_config[general][pattern]">
                                                        <option value="rows">সারি অনুযায়ী</option>
                                                        <option value="columns">কলাম অনুযা়ী</option>
                                                        <option value="zigzag">জিগজ্যাগ</option>
                                                        <option value="diagonal">তির্যক</option>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <div class="mt-3">
                                                <small class="text-muted">
                                                    <i class="fas fa-lightbulb"></i> 
                                                    সকল বিষয়ের জন্য একই সীটিং প্ল্যান প্রয়োগ করা হবে। 
                                                    ছাত্র/ছাত্রীদের রোল নম্বর অনুযায়ী সীট বরাদ্দ করা হবে।
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mt-4">
                                    <button type="submit" class="btn btn-success btn-lg">
                                        <i class="fas fa-magic"></i> সীট বিন্যাস তৈরি করুন
                                    </button>
                                    
                                    <a href="seat_card.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">
                                        <i class="fas fa-eye"></i> সীট কার্ড দেখুন
                                    </a>
                                </div>
                            </form>
                        <?php elseif ($exam_id): ?>
                            <div class="alert alert-warning text-center">
                                <i class="fas fa-exclamation-triangle"></i> 
                                এই পরীক্ষার জন্য কোন ছাত্র/ছাত্রী বা বিষয় পাওয়া যায়নি।
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info text-center">
                                <i class="fas fa-info-circle"></i> 
                                শুরু করতে একটি পরীক্ষা নির্বাচন করুন।
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

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