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

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

$user_role = $_SESSION['user_role'];
$success_message = '';
$error_message = '';

// Handle status update (admin only)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_status']) && $user_role == 'admin') {
    $class_id = intval($_POST['class_id']);
    $new_status = $_POST['status'];
    
    try {
        $stmt = $pdo->prepare("UPDATE classes SET status = ? WHERE id = ?");
        if ($stmt->execute([$new_status, $class_id])) {
            $success_message = "ক্লাসের স্ট্যাটাস আপডেট করা হয়েছে";
        }
    } catch (Exception $e) {
        $error_message = "স্ট্যাটাস আপডেট করতে সমস্যা হয়েছে: " . $e->getMessage();
    }
}

// Get all classes with related information
$classes = $pdo->query("
    SELECT c.*, 
           t.first_name as teacher_first_name, 
           t.last_name as teacher_last_name,
           (SELECT COUNT(*) FROM students WHERE class_id = c.id AND status = 'active') as student_count,
           (SELECT COUNT(DISTINCT subject_id) FROM class_subjects WHERE class_id = c.id) as subject_count
    FROM classes c
    LEFT JOIN teachers t ON c.class_teacher_id = t.id
    ORDER BY c.name, c.section
")->fetchAll();

// Get statistics
$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();
?>

<!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">
    <link href="../../assets/css/style.css" rel="stylesheet">
    <style>
        .class-card {
            transition: transform 0.2s;
        }
        .class-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .capacity-bar {
            height: 8px;
            border-radius: 4px;
        }
    </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="add.php">
                    <i class="fas fa-plus"></i> নতুন ক্লাস
                </a>
                <a class="nav-link" href="../../students/index.php">
                    <i class="fas fa-user-graduate"></i> ছাত্র-ছাত্রী
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <!-- Header and Stats -->
        <div class="row mb-4">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center">
                    <h2><i class="fas fa-school"></i> ক্লাস তালিকা</h2>
                    <?php if ($user_role == 'admin'): ?>
                    <a href="add.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i> নতুন ক্লাস যোগ করুন
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Success/Error Messages -->
        <?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; ?>

        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-school fa-2x mb-2"></i>
                        <h4><?php echo $stats['total_classes']; ?></h4>
                        <p class="mb-0">মোট ক্লাস</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-check-circle fa-2x mb-2"></i>
                        <h4><?php echo $stats['active_classes']; ?></h4>
                        <p class="mb-0">সক্রিয় ক্লাস</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-users fa-2x mb-2"></i>
                        <h4><?php echo $stats['total_capacity']; ?></h4>
                        <p class="mb-0">মোট ধারণক্ষমতা</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <i class="fas fa-user-graduate fa-2x mb-2"></i>
                        <h4><?php echo $stats['total_students']; ?></h4>
                        <p class="mb-0">মোট শিক্ষার্থী</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Classes Grid -->
        <?php if (empty($classes)): ?>
            <div class="row">
                <div class="col-md-12">
                    <div class="alert alert-info text-center">
                        <i class="fas fa-info-circle fa-3x mb-3"></i>
                        <h4>কোন ক্লাস পাওয়া যায়নি</h4>
                        <p>এখনও কোন ক্লাস তৈরি করা হয়নি।</p>
                        <?php if ($user_role == 'admin'): ?>
                        <a href="add.php" class="btn btn-primary">
                            <i class="fas fa-plus"></i> প্রথম ক্লাস তৈরি করুন
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="row">
                <?php foreach ($classes as $class): ?>
                    <div class="col-md-4 mb-4">
                        <div class="card class-card h-100">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">
                                    <i class="fas fa-school text-primary"></i>
                                    <?php echo $class['name']; ?> - <?php echo $class['section']; ?>
                                </h5>
                                <span class="badge bg-<?php echo ($class['status'] == 'active') ? 'success' : 'secondary'; ?>">
                                    <?php echo ($class['status'] == 'active') ? 'সক্রিয়' : 'নিষ্ক্রিয়'; ?>
                                </span>
                            </div>
                            <div class="card-body">
                                <p class="card-text">
                                    <?php if (!empty($class['description'])): ?>
                                        <?php echo htmlspecialchars($class['description']); ?>
                                    <?php else: ?>
                                        <span class="text-muted">কোন বিবরণ নেই</span>
                                    <?php endif; ?>
                                </p>
                                
                                <div class="row">
                                    <div class="col-6">
                                        <small class="text-muted">শিক্ষার্থী</small>
                                        <div class="fw-bold"><?php echo $class['student_count']; ?> জন</div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">বিষয়</small>
                                        <div class="fw-bold"><?php echo $class['subject_count']; ?>টি</div>
                                    </div>
                                </div>
                                
                                <div class="mt-3">
                                    <small class="text-muted">ধারণক্ষমতা: <?php echo $class['capacity']; ?> জন</small>
                                    <div class="progress capacity-bar mt-1">
                                        <?php 
                                        $percentage = ($class['capacity'] > 0) ? ($class['student_count'] / $class['capacity']) * 100 : 0;
                                        $percentage = min($percentage, 100);
                                        ?>
                                        <div class="progress-bar bg-<?php echo ($percentage > 80) ? 'warning' : 'success'; ?>" 
                                             role="progressbar" 
                                             style="width: <?php echo $percentage; ?>%"></div>
                                    </div>
                                </div>
                                
                                <?php if ($class['teacher_first_name']): ?>
                                    <div class="mt-2">
                                        <small class="text-muted">ক্লাস শিক্ষক: 
                                            <?php echo htmlspecialchars($class['teacher_first_name'] . ' ' . $class['teacher_last_name']); ?>
                                        </small>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <?php if ($user_role == 'admin'): ?>
                            <div class="card-footer">
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="class_id" value="<?php echo $class['id']; ?>">
                                    <select name="status" class="form-select form-select-sm d-inline-block w-auto" 
                                            onchange="this.form.submit()">
                                        <option value="active" <?php echo ($class['status'] == 'active') ? 'selected' : ''; ?>>সক্রিয়</option>
                                        <option value="inactive" <?php echo ($class['status'] == 'inactive') ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                                    </select>
                                    <input type="hidden" name="update_status" value="1">
                                </form>
                                <small class="text-muted">স্ট্যাটাস পরিবর্তন</small>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

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