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

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

echo "<!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'>
</head>
<body class='bg-light'>
    <div class='container mt-5'>
        <div class='row justify-content-center'>
            <div class='col-md-10'>
                <div class='card'>
                    <div class='card-header bg-primary text-white'>
                        <h4><i class='fas fa-clipboard-list'></i> পরীক্ষা সিস্টেম টেস্ট</h4>
                    </div>
                    <div class='card-body'>";

try {
    // Check database tables
    echo "<h5><i class='fas fa-database'></i> ডাটাবেস টেবিল চেক:</h5>";
    
    $required_tables = [
        'exams' => 'পরীক্ষা',
        'exam_subjects' => 'পরীক্ষার বিষয়',
        'exam_attendance' => 'পরীক্ষার হাজিরা',
        'seat_arrangements' => 'সীট বিন্যাস'
    ];
    
    echo "<div class='row'>";
    foreach ($required_tables as $table => $name) {
        try {
            $stmt = $pdo->query("SELECT COUNT(*) FROM $table");
            $count = $stmt->fetchColumn();
            echo "<div class='col-md-3 mb-2'>";
            echo "<div class='alert alert-success py-2'>";
            echo "<i class='fas fa-check'></i> $name ($count)";
            echo "</div>";
            echo "</div>";
        } catch (Exception $e) {
            echo "<div class='col-md-3 mb-2'>";
            echo "<div class='alert alert-danger py-2'>";
            echo "<i class='fas fa-times'></i> $name (Missing)";
            echo "</div>";
            echo "</div>";
        }
    }
    echo "</div>";
    
    // Check required columns
    echo "<hr>";
    echo "<h5><i class='fas fa-columns'></i> নতুন কলাম চেক:</h5>";
    
    $required_columns = [
        'exams' => ['session', 'group_name'],
        'exam_subjects' => ['room_number', 'invigilator']
    ];
    
    echo "<div class='row'>";
    foreach ($required_columns as $table => $columns) {
        foreach ($columns as $column) {
            try {
                $stmt = $pdo->query("SHOW COLUMNS FROM $table LIKE '$column'");
                $exists = $stmt->fetch();
                if ($exists) {
                    echo "<div class='col-md-3 mb-2'>";
                    echo "<div class='alert alert-success py-2'>";
                    echo "<i class='fas fa-check'></i> $table.$column";
                    echo "</div>";
                    echo "</div>";
                } else {
                    echo "<div class='col-md-3 mb-2'>";
                    echo "<div class='alert alert-danger py-2'>";
                    echo "<i class='fas fa-times'></i> $table.$column";
                    echo "</div>";
                    echo "</div>";
                }
            } catch (Exception $e) {
                echo "<div class='col-md-3 mb-2'>";
                echo "<div class='alert alert-danger py-2'>";
                echo "<i class='fas fa-times'></i> $table.$column (Error)";
                echo "</div>";
                echo "</div>";
            }
        }
    }
    echo "</div>";
    
    // Show existing data
    echo "<hr>";
    echo "<h5><i class='fas fa-list'></i> বর্তমান ডাটা:</h5>";
    
    // Exams
    $exams = $pdo->query("
        SELECT e.*, c.name as class_name, c.section
        FROM exams e
        LEFT JOIN classes c ON e.class_id = c.id
        ORDER BY e.created_at DESC
        LIMIT 5
    ")->fetchAll();
    
    echo "<h6>পরীক্ষাসমূহ:</h6>";
    if (empty($exams)) {
        echo "<div class='alert alert-info'>";
        echo "<i class='fas fa-info-circle'></i> কোন পরীক্ষা পাওয়া যায়নি। প্রথমে পরীক্ষার রুটিন তৈরি করুন।";
        echo "</div>";
    } else {
        echo "<div class='table-responsive'>";
        echo "<table class='table table-sm table-striped'>";
        echo "<thead>";
        echo "<tr>";
        echo "<th>নাম</th>";
        echo "<th>ক্লাস</th>";
        echo "<th>সেশন</th>";
        echo "<th>গ্রুপ</th>";
        echo "<th>তারিখ</th>";
        echo "<th>স্ট্যাটাস</th>";
        echo "</tr>";
        echo "</thead>";
        echo "<tbody>";
        
        foreach ($exams as $exam) {
            echo "<tr>";
            echo "<td>" . $exam['name'] . "</td>";
            echo "<td>" . ($exam['class_name'] ? $exam['class_name'] . '-' . $exam['section'] : 'N/A') . "</td>";
            echo "<td>" . ($exam['session'] ?? 'N/A') . "</td>";
            echo "<td>" . ($exam['group_name'] ?? 'সাধারণ') . "</td>";
            echo "<td>" . date('d/m/Y', strtotime($exam['exam_date'])) . "</td>";
            echo "<td>";
            $status_colors = [
                'scheduled' => 'primary',
                'ongoing' => 'warning',
                'completed' => 'success',
                'cancelled' => 'danger'
            ];
            $status_text = [
                'scheduled' => 'নির্ধারিত',
                'ongoing' => 'চলমান',
                'completed' => 'সম্পন্ন',
                'cancelled' => 'বাতিল'
            ];
            $color = $status_colors[$exam['status']] ?? 'secondary';
            $text = $status_text[$exam['status']] ?? $exam['status'];
            echo "<span class='badge bg-$color'>$text</span>";
            echo "</td>";
            echo "</tr>";
        }
        
        echo "</tbody>";
        echo "</table>";
        echo "</div>";
    }
    
    // Sample data creation
    echo "<hr>";
    echo "<h5><i class='fas fa-magic'></i> নমুনা ডাটা তৈরি:</h5>";
    
    if (empty($exams)) {
        echo "<div class='alert alert-warning'>";
        echo "<h6><i class='fas fa-lightbulb'></i> নমুনা পরীক্ষা তৈরি করুন:</h6>";
        echo "<p>টেস্ট করার জন্য একটি নমুনা পরীক্ষা তৈরি করতে নিচের বাটনে ক্লিক করুন।</p>";
        echo "<form method='POST' action='' style='display: inline;'>";
        echo "<input type='hidden' name='create_sample_exam' value='1'>";
        echo "<button type='submit' class='btn btn-warning'>";
        echo "<i class='fas fa-plus'></i> নমুনা পরীক্ষা তৈরি করুন";
        echo "</button>";
        echo "</form>";
        echo "</div>";
    }
    
    // Handle sample exam creation
    if (isset($_POST['create_sample_exam'])) {
        try {
            $pdo->beginTransaction();
            
            // Get first active class
            $class = $pdo->query("SELECT id FROM classes WHERE status = 'active' LIMIT 1")->fetch();
            if (!$class) {
                throw new Exception("কোন সক্রিয় ক্লাস পাওয়া যায়নি");
            }
            
            // Get current session
            $session = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC LIMIT 1")->fetch();
            $session_name = $session ? $session['session_name'] : '2024';
            
            // Create sample exam
            $stmt = $pdo->prepare("
                INSERT INTO exams (name, class_id, session, exam_date, start_time, end_time, description, status) 
                VALUES (?, ?, ?, ?, '09:00:00', '17:00:00', 'Sample exam for testing', 'scheduled')
            ");
            $stmt->execute(['নমুনা পরীক্ষা ২০২৪', $class['id'], $session_name, date('Y-m-d', strtotime('+7 days'))]);
            $exam_id = $pdo->lastInsertId();
            
            // Get some subjects
            $subjects = $pdo->query("SELECT id, name FROM subjects WHERE status = 'active' LIMIT 3")->fetchAll();
            
            if (!empty($subjects)) {
                $date = new DateTime('+7 days');
                foreach ($subjects as $index => $subject) {
                    $stmt = $pdo->prepare("
                        INSERT INTO exam_subjects 
                        (exam_id, subject_id, max_marks, pass_marks, exam_date, start_time, end_time, room_number, invigilator) 
                        VALUES (?, ?, 100, 40, ?, '10:00:00', '13:00:00', ?, 'নমুনা পরীক্ষক')
                    ");
                    $stmt->execute([
                        $exam_id,
                        $subject['id'],
                        $date->format('Y-m-d'),
                        'Room-' . ($index + 1)
                    ]);
                    $date->add(new DateInterval('P1D')); // Add 1 day
                }
            }
            
            $pdo->commit();
            echo "<div class='alert alert-success'>";
            echo "<i class='fas fa-check'></i> নমুনা পরীক্ষা সফলভাবে তৈরি হয়েছে!";
            echo "</div>";
            
            // Refresh page to show new data
            echo "<script>setTimeout(function(){ location.reload(); }, 2000);</script>";
            
        } catch (Exception $e) {
            $pdo->rollBack();
            echo "<div class='alert alert-danger'>";
            echo "<i class='fas fa-exclamation-triangle'></i> ত্রুটি: " . $e->getMessage();
            echo "</div>";
        }
    }
    
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>";
    echo "<h5><i class='fas fa-exclamation-triangle'></i> ত্রুটি!</h5>";
    echo "<p>" . $e->getMessage() . "</p>";
    echo "</div>";
}

echo "                    </div>
                    <div class='card-footer'>
                        <div class='row'>
                            <div class='col-md-4'>
                                <a href='exams/routine.php' class='btn btn-primary w-100'>
                                    <i class='fas fa-calendar'></i> পরীক্ষার রুটিন
                                </a>
                            </div>
                            <div class='col-md-4'>
                                <a href='exams/attendance.php' class='btn btn-success w-100'>
                                    <i class='fas fa-clipboard-check'></i> হাজিরা পত্র
                                </a>
                            </div>
                            <div class='col-md-4'>
                                <a href='exams/seat_card.php' class='btn btn-info w-100'>
                                    <i class='fas fa-id-card'></i> সীট কার্ড
                                </a>
                            </div>
                        </div>
                        <div class='row mt-2'>
                            <div class='col-md-6'>
                                <a href='EXAM_SYSTEM_README.md' target='_blank' class='btn btn-outline-primary w-100'>
                                    <i class='fas fa-book'></i> ডকুমেন্টেশন
                                </a>
                            </div>
                            <div class='col-md-6'>
                                <a href='index.php' class='btn btn-secondary w-100'>
                                    <i class='fas fa-home'></i> হোমে ফিরুন
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";
?>