<?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-success text-white'>
                        <h4><i class='fas fa-school'></i> ক্লাস সিস্টেম টেস্ট</h4>
                    </div>
                    <div class='card-body'>";

try {
    // Check classes table
    echo "<h5><i class='fas fa-database'></i> ডাটাবেস টেবিল চেক:</h5>";
    
    try {
        $classes_count = $pdo->query("SELECT COUNT(*) FROM classes")->fetchColumn();
        echo "<div class='alert alert-success'>";
        echo "<i class='fas fa-check'></i> Classes টেবিল পাওয়া গেছে ($classes_count টি ক্লাস)";
        echo "</div>";
    } catch (Exception $e) {
        echo "<div class='alert alert-danger'>";
        echo "<i class='fas fa-times'></i> Classes টেবিল পাওয়া যায়নি";
        echo "</div>";
    }
    
    // Check required columns
    echo "<hr>";
    echo "<h5><i class='fas fa-columns'></i> টেবিল স্ট্রাকচার চেক:</h5>";
    
    $required_columns = ['id', 'name', 'section', 'capacity', 'status', 'created_at'];
    $columns = $pdo->query("DESCRIBE classes")->fetchAll();
    $existing_columns = array_column($columns, 'Field');
    
    echo "<div class='row'>";
    foreach ($required_columns as $col) {
        if (in_array($col, $existing_columns)) {
            echo "<div class='col-md-2 mb-2'>";
            echo "<div class='alert alert-success py-2'>";
            echo "<i class='fas fa-check'></i> $col";
            echo "</div>";
            echo "</div>";
        } else {
            echo "<div class='col-md-2 mb-2'>";
            echo "<div class='alert alert-danger py-2'>";
            echo "<i class='fas fa-times'></i> $col";
            echo "</div>";
            echo "</div>";
        }
    }
    echo "</div>";
    
    // Show existing classes
    echo "<hr>";
    echo "<h5><i class='fas fa-list'></i> বর্তমান ক্লাসসমূহ:</h5>";
    
    $classes = $pdo->query("
        SELECT c.*, 
               (SELECT COUNT(*) FROM students WHERE class_id = c.id AND status = 'active') as student_count,
               t.first_name as teacher_first_name, t.last_name as teacher_last_name
        FROM classes c
        LEFT JOIN teachers t ON c.class_teacher_id = t.id
        ORDER BY c.name, c.section
        LIMIT 10
    ")->fetchAll();
    
    if (empty($classes)) {
        echo "<div class='alert alert-info'>";
        echo "<i class='fas fa-info-circle'></i> কোন ক্লাস পাওয়া যায়নি। প্রথমে কিছু ক্লাস তৈরি করুন।";
        echo "</div>";
        
        // Sample classes creation
        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_classes' value='1'>";
        echo "<button type='submit' class='btn btn-warning'>";
        echo "<i class='fas fa-plus'></i> নমুনা ক্লাস তৈরি করুন";
        echo "</button>";
        echo "</form>";
        echo "</div>";
    } else {
        echo "<div class='table-responsive'>";
        echo "<table class='table 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 "<th>তৈরি</th>";
        echo "</tr>";
        echo "</thead>";
        echo "<tbody>";
        
        foreach ($classes as $class) {
            echo "<tr>";
            echo "<td><strong>" . $class['name'] . "</strong></td>";
            echo "<td>" . $class['section'] . "</td>";
            echo "<td>" . $class['capacity'] . "</td>";
            echo "<td>";
            $percentage = $class['capacity'] > 0 ? ($class['student_count'] / $class['capacity']) * 100 : 0;
            $badge_color = $percentage > 90 ? 'danger' : ($percentage > 75 ? 'warning' : 'success');
            echo "<span class='badge bg-$badge_color'>" . $class['student_count'] . "</span>";
            echo "</td>";
            echo "<td>";
            if ($class['teacher_first_name']) {
                echo $class['teacher_first_name'] . ' ' . $class['teacher_last_name'];
            } else {
                echo "<span class='text-muted'>নির্ধারিত নয়</span>";
            }
            echo "</td>";
            echo "<td>";
            if ($class['status'] == 'active') {
                echo "<span class='badge bg-success'>সক্রিয়</span>";
            } else {
                echo "<span class='badge bg-secondary'>নিষ্ক্রিয়</span>";
            }
            echo "</td>";
            echo "<td>" . date('d/m/Y', strtotime($class['created_at'])) . "</td>";
            echo "</tr>";
        }
        
        echo "</tbody>";
        echo "</table>";
        echo "</div>";
    }
    
    // Handle sample classes creation
    if (isset($_POST['create_sample_classes'])) {
        try {
            $pdo->beginTransaction();
            
            $sample_classes = [
                ['ষষ্ঠ', 'ক', 50],
                ['ষষ্ঠ', 'খ', 45],
                ['সপ্তম', 'ক', 48],
                ['সপ্তম', 'খ', 42],
                ['অষ্টম', 'ক', 50],
                ['নবম', 'ক', 40],
                ['দশম', 'ক', 35]
            ];
            
            foreach ($sample_classes as $class_data) {
                // Check if class already exists
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM classes WHERE name = ? AND section = ?");
                $stmt->execute([$class_data[0], $class_data[1]]);
                
                if ($stmt->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("
                        INSERT INTO classes (name, section, capacity, status, description) 
                        VALUES (?, ?, ?, 'active', 'নমুনা ক্লাস - টেস্টের জন্য তৈরি')
                    ");
                    $stmt->execute($class_data);
                }
            }
            
            $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>";
        }
    }
    
    // Statistics
    echo "<hr>";
    echo "<h5><i class='fas fa-chart-bar'></i> পরিসংখ্যান:</h5>";
    
    $stats = $pdo->query("
        SELECT 
            COUNT(*) as total_classes,
            SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_classes,
            SUM(capacity) as total_capacity,
            (SELECT COUNT(*) FROM students WHERE status = 'active') as total_students
        FROM classes
    ")->fetch();
    
    echo "<div class='row'>";
    echo "<div class='col-md-3'>";
    echo "<div class='card bg-primary text-white text-center'>";
    echo "<div class='card-body'>";
    echo "<h3>" . $stats['total_classes'] . "</h3>";
    echo "<p>মোট ক্লাস</p>";
    echo "</div>";
    echo "</div>";
    echo "</div>";
    
    echo "<div class='col-md-3'>";
    echo "<div class='card bg-success text-white text-center'>";
    echo "<div class='card-body'>";
    echo "<h3>" . $stats['active_classes'] . "</h3>";
    echo "<p>সক্রিয় ক্লাস</p>";
    echo "</div>";
    echo "</div>";
    echo "</div>";
    
    echo "<div class='col-md-3'>";
    echo "<div class='card bg-info text-white text-center'>";
    echo "<div class='card-body'>";
    echo "<h3>" . $stats['total_capacity'] . "</h3>";
    echo "<p>মোট ধারণক্ষমতা</p>";
    echo "</div>";
    echo "</div>";
    echo "</div>";
    
    echo "<div class='col-md-3'>";
    echo "<div class='card bg-warning text-white text-center'>";
    echo "<div class='card-body'>";
    echo "<h3>" . $stats['total_students'] . "</h3>";
    echo "<p>মোট শিক্ষার্থী</p>";
    echo "</div>";
    echo "</div>";
    echo "</div>";
    echo "</div>";
    
    // Capacity utilization
    if ($stats['total_capacity'] > 0) {
        $utilization = ($stats['total_students'] / $stats['total_capacity']) * 100;
        echo "<div class='mt-3'>";
        echo "<h6>ধারণক্ষমতার ব্যবহার:</h6>";
        echo "<div class='progress' style='height: 25px;'>";
        $progress_color = $utilization > 90 ? 'danger' : ($utilization > 75 ? 'warning' : 'success');
        echo "<div class='progress-bar bg-$progress_color' style='width: " . min($utilization, 100) . "%'>";
        echo round($utilization, 1) . "%";
        echo "</div>";
        echo "</div>";
        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='classes/add.php' class='btn btn-primary w-100'>
                                    <i class='fas fa-plus'></i> নতুন ক্লাস যোগ
                                </a>
                            </div>
                            <div class='col-md-4'>
                                <a href='classes/list.php' class='btn btn-success w-100'>
                                    <i class='fas fa-list'></i> ক্লাস তালিকা
                                </a>
                            </div>
                            <div class='col-md-4'>
                                <a href='classes/manage.php' class='btn btn-info w-100'>
                                    <i class='fas fa-cog'></i> ক্লাস ব্যবস্থাপনা
                                </a>
                            </div>
                        </div>
                        <div class='row mt-2'>
                            <div class='col-md-6'>
                                <a href='CLASSES_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>";
?>