<?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="../groups/list.php">
                    <i class="fas fa-layer-group"></i> গ্রুপ
                </a>
                <?php if ($user_role == 'admin'): ?>
                <a class="nav-link" href="add.php">
                    <i class="fas fa-plus"></i> নতুন ক্লাস
                </a>
                <a class="nav-link" href="manage.php">
                    <i class="fas fa-cog"></i> ক্লাস ব্যবস্থাপনা
                </a>
                <?php endif; ?>
            </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 !empty($class['section']) ? ' - ' . $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">
                                <!-- Class Teacher -->
                                <div class="mb-3">
                                    <small class="text-muted">ক্লাস শিক্ষক:</small><br>
                                    <?php if ($class['teacher_first_name']): ?>
                                        <strong><?php echo $class['teacher_first_name'] . ' ' . $class['teacher_last_name']; ?></strong>
                                    <?php else: ?>
                                        <span class="text-muted">নির্ধারিত নয়</span>
                                    <?php endif; ?>
                                </div>

                                <!-- Student Count -->
                                <div class="mb-3">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <small class="text-muted">শিক্ষার্থী:</small>
                                        <small>
                                            <strong><?php echo $class['student_count']; ?></strong> / <?php echo $class['capacity']; ?>
                                        </small>
                                    </div>
                                    <?php 
                                    $percentage = $class['capacity'] > 0 ? ($class['student_count'] / $class['capacity']) * 100 : 0;
                                    $bar_color = $percentage > 90 ? 'danger' : ($percentage > 75 ? 'warning' : 'success');
                                    ?>
                                    <div class="progress capacity-bar">
                                        <div class="progress-bar bg-<?php echo $bar_color; ?>" 
                                             style="width: <?php echo min($percentage, 100); ?>%"></div>
                                    </div>
                                </div>

                                <!-- Subject Count -->
                                <div class="mb-3">
                                    <small class="text-muted">বিষয়:</small>
                                    <strong><?php echo $class['subject_count']; ?>টি</strong>
                                </div>

                                <!-- Description -->
                                <?php if ($class['description']): ?>
                                <div class="mb-3">
                                    <small class="text-muted">বিবরণ:</small><br>
                                    <small><?php echo htmlspecialchars($class['description']); ?></small>
                                </div>
                                <?php endif; ?>

                                <!-- Created Date -->
                                <div class="mb-3">
                                    <small class="text-muted">তৈরি:</small>
                                    <small><?php echo date('d/m/Y', strtotime($class['created_at'])); ?></small>
                                </div>
                            </div>
                            <div class="card-footer">
                                <div class="d-flex gap-2">
                                    <a href="../students/list.php?class_id=<?php echo $class['id']; ?>" 
                                       class="btn btn-sm btn-outline-primary flex-fill">
                                        <i class="fas fa-users"></i> শিক্ষার্থী
                                    </a>
                                    
                                    <?php if ($user_role == 'admin'): ?>
                                    <a href="manage.php?class_id=<?php echo $class['id']; ?>" 
                                       class="btn btn-sm btn-outline-success flex-fill">
                                        <i class="fas fa-cog"></i> ব্যবস্থাপনা
                                    </a>
                                    
                                    <!-- Status Toggle -->
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="update_status" value="1">
                                        <input type="hidden" name="class_id" value="<?php echo $class['id']; ?>">
                                        <input type="hidden" name="status" value="<?php echo ($class['status'] == 'active') ? 'inactive' : 'active'; ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-<?php echo ($class['status'] == 'active') ? 'warning' : 'success'; ?>"
                                                onclick="return confirm('আপনি কি নিশ্চিত?')">
                                            <i class="fas fa-<?php echo ($class['status'] == 'active') ? 'pause' : 'play'; ?>"></i>
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- Additional Information -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h6><i class="fas fa-info-circle"></i> তথ্য ও নির্দেশনা</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>ক্লাস কার্ডের তথ্য:</h6>
                                <ul class="list-unstyled">
                                    <li><i class="fas fa-circle text-success"></i> <strong>সবুজ ব্যাজ:</strong> সক্রিয় ক্লাস</li>
                                    <li><i class="fas fa-circle text-secondary"></i> <strong>ধূসর ব্যাজ:</strong> নিষ্ক্রিয় ক্লাস</li>
                                    <li><i class="fas fa-chart-bar text-success"></i> <strong>সবুজ বার:</strong> ধারণক্ষমতার ৭৫% এর কম</li>
                                    <li><i class="fas fa-chart-bar text-warning"></i> <strong>হলুদ বার:</strong> ধারণক্ষমতার ৭৫-৯০%</li>
                                    <li><i class="fas fa-chart-bar text-danger"></i> <strong>লাল বার:</strong> ধারণক্ষমতার ৯০% এর বেশি</li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <h6>দ্রুত অ্যাকশন:</h6>
                                <ul class="list-unstyled">
                                    <li><i class="fas fa-users text-primary"></i> <strong>শিক্ষার্থী বাটন:</strong> ক্লাসের শিক্ষার্থী তালিকা</li>
                                    <?php if ($user_role == 'admin'): ?>
                                    <li><i class="fas fa-cog text-success"></i> <strong>ব্যবস্থাপনা বাটন:</strong> ক্লাস সেটিংস ও বিষয় যোগ</li>
                                    <li><i class="fas fa-pause text-warning"></i> <strong>পজ বাটন:</strong> ক্লাস নিষ্ক্রিয় করুন</li>
                                    <li><i class="fas fa-play text-success"></i> <strong>প্লে বাটন:</strong> ক্লাস সক্রিয় করুন</li>
                                    <?php endif; ?>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);

        // Add loading state to status toggle buttons
        document.querySelectorAll('form').forEach(function(form) {
            form.addEventListener('submit', function() {
                const button = form.querySelector('button[type="submit"]');
                button.disabled = true;
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
            });
        });
    </script>
</body>
</html>