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

// Permissions: admin/teacher can manage, others can view list only
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$can_manage = isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['admin','teacher']);
$success_message = '';
$error_message = '';

// Handle POST actions (add/update/delete/toggle)
if ($can_manage && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    try {
        if ($action === 'add') {
            $group_name = trim($_POST['group_name'] ?? '');
            $group_code = strtoupper(trim($_POST['group_code'] ?? ''));
            $description = trim($_POST['description'] ?? '');
            $status = $_POST['status'] ?? 'active';

            if ($group_name === '' || $group_code === '') {
                throw new Exception('গ্রুপ নাম এবং গ্রুপ কোড প্রয়োজন');
            }

            // Unique group_code
            $chk = $pdo->prepare('SELECT COUNT(*) FROM student_groups WHERE group_code = ?');
            $chk->execute([$group_code]);
            if ($chk->fetchColumn() > 0) {
                throw new Exception('এই কোড দিয়ে ইতিমধ্যে একটি গ্রুপ রয়েছে');
            }

            $stmt = $pdo->prepare('INSERT INTO student_groups (group_name, group_code, description, status) VALUES (?, ?, ?, ?)');
            $stmt->execute([$group_name, $group_code, $description, $status]);
            $success_message = 'গ্রুপ সফলভাবে তৈরি হয়েছে';
        } elseif ($action === 'update') {
            $id = (int)($_POST['id'] ?? 0);
            $group_name = trim($_POST['group_name'] ?? '');
            $group_code = strtoupper(trim($_POST['group_code'] ?? ''));
            $description = trim($_POST['description'] ?? '');
            $status = $_POST['status'] ?? 'active';

            if ($id <= 0 || $group_name === '' || $group_code === '') {
                throw new Exception('অবৈধ ইনপুট');
            }

            $chk = $pdo->prepare('SELECT COUNT(*) FROM student_groups WHERE group_code = ? AND id != ?');
            $chk->execute([$group_code, $id]);
            if ($chk->fetchColumn() > 0) {
                throw new Exception('এই কোড দিয়ে ইতিমধ্যে একটি গ্রুপ রয়েছে');
            }

            $stmt = $pdo->prepare('UPDATE student_groups SET group_name = ?, group_code = ?, description = ?, status = ? WHERE id = ?');
            $stmt->execute([$group_name, $group_code, $description, $status, $id]);
            $success_message = 'গ্রুপ আপডেট হয়েছে';
        } elseif ($action === 'toggle') {
            $id = (int)($_POST['id'] ?? 0);
            $new_status = $_POST['new_status'] === 'active' ? 'active' : 'inactive';
            $stmt = $pdo->prepare('UPDATE student_groups SET status = ? WHERE id = ?');
            $stmt->execute([$new_status, $id]);
            $success_message = $new_status === 'active' ? 'গ্রুপ সক্রিয় হয়েছে' : 'গ্রুপ নিষ্ক্রিয় হয়েছে';
        } elseif ($action === 'delete') {
            $id = (int)($_POST['id'] ?? 0);
            // Prevent delete if referenced by any student
            $ref = $pdo->prepare('SELECT COUNT(*) FROM students WHERE group_name = (SELECT group_name FROM student_groups WHERE id = ? LIMIT 1)');
            $ref->execute([$id]);
            if ($ref->fetchColumn() > 0) {
                throw new Exception('এই গ্রুপটি শিক্ষার্থীদের সাথে যুক্ত, মুছে ফেলা যাবে না');
            }
            $del = $pdo->prepare('DELETE FROM student_groups WHERE id = ?');
            $del->execute([$id]);
            $success_message = 'গ্রুপ মুছে ফেলা হয়েছে';
        }
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

// Filters
$search = trim($_GET['search'] ?? '');
$status_filter = $_GET['status'] ?? '';

$where = [];
$params = [];
if ($search !== '') { $where[] = '(group_name LIKE :q OR group_code LIKE :q OR description LIKE :q)'; $params['q'] = "%$search%"; }
if ($status_filter !== '') { $where[] = 'status = :st'; $params['st'] = $status_filter; }
$where_clause = $where ? implode(' AND ', $where) : '1=1';

$groups = [];
$stmt = $pdo->prepare("SELECT * FROM student_groups WHERE $where_clause ORDER BY group_name");
foreach ($params as $k=>$v) { $stmt->bindValue(":$k", $v); }
$stmt->execute();
$groups = $stmt->fetchAll();
?>
<!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">
</head>
<body>
<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="../students/add.php"><i class="fas fa-user-plus"></i> শিক্ষার্থী যোগ</a>
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></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 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-layer-group"></i> গ্রুপ তালিকা</h5>
                    <?php if ($can_manage): ?>
                        <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#groupModal">
                            <i class="fas fa-plus"></i> নতুন গ্রুপ
                        </button>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <?php if ($success_message): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <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" role="alert">
                            <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; ?>

                    <form class="mb-3" method="GET">
                        <div class="row g-2 align-items-end">
                            <div class="col-md-4">
                                <label class="form-label">খুঁজুন</label>
                                <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search); ?>" placeholder="নাম, কোড বা বিবরণ">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">অবস্থা</label>
                                <select class="form-select" name="status">
                                    <option value="">সব</option>
                                    <option value="active" <?php echo $status_filter==='active'?'selected':''; ?>>সক্রিয়</option>
                                    <option value="inactive" <?php echo $status_filter==='inactive'?'selected':''; ?>>নিষ্ক্রিয়</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button class="btn btn-primary w-100" type="submit"><i class="fas fa-search"></i> খুঁজুন</button>
                            </div>
                            <div class="col-md-2">
                                <a class="btn btn-secondary w-100" href="list.php">রিসেট</a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                            <tr>
                                <th>গ্রুপ নাম</th>
                                <th>কোড</th>
                                <th>বিবরণ</th>
                                <th>অবস্থা</th>
                                <th class="no-print">কার্যক্রম</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (empty($groups)): ?>
                                <tr><td colspan="5" class="text-center text-muted py-4">কোন গ্রুপ পাওয়া যায়নি</td></tr>
                            <?php else: ?>
                                <?php foreach ($groups as $g): ?>
                                    <tr>
                                        <td><strong><?php echo htmlspecialchars($g['group_name']); ?></strong></td>
                                        <td><span class="badge bg-primary"><?php echo htmlspecialchars($g['group_code']); ?></span></td>
                                        <td><?php echo $g['description']?htmlspecialchars($g['description']):'<span class="text-muted">-</span>'; ?></td>
                                        <td>
                                            <span class="badge <?php echo $g['status']==='active'?'bg-success':'bg-secondary'; ?>">
                                                <?php echo $g['status']==='active'?'সক্রিয়':'নিষ্ক্রিয়'; ?>
                                            </span>
                                        </td>
                                        <td class="no-print">
                                            <?php if ($can_manage): ?>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#groupModal" 
                                                            data-id="<?php echo (int)$g['id']; ?>"
                                                            data-name="<?php echo htmlspecialchars($g['group_name']); ?>"
                                                            data-code="<?php echo htmlspecialchars($g['group_code']); ?>"
                                                            data-description="<?php echo htmlspecialchars($g['description']); ?>"
                                                            data-status="<?php echo htmlspecialchars($g['status']); ?>"
                                                            title="সম্পাদনা">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <form method="POST" class="d-inline" onsubmit="return confirm('স্ট্যাটাস পরিবর্তন করবেন?');">
                                                        <input type="hidden" name="action" value="toggle">
                                                        <input type="hidden" name="id" value="<?php echo (int)$g['id']; ?>">
                                                        <input type="hidden" name="new_status" value="<?php echo $g['status']==='active'?'inactive':'active'; ?>">
                                                        <button type="submit" class="btn <?php echo $g['status']==='active'?'btn-secondary':'btn-success'; ?>" title="স্ট্যাটাস টগল">
                                                            <i class="fas <?php echo $g['status']==='active'?'fa-ban':'fa-check'; ?>"></i>
                                                        </button>
                                                    </form>
                                                    <form method="POST" class="d-inline" onsubmit="return confirm('মুছে ফেলতে চান?');">
                                                        <input type="hidden" name="action" value="delete">
                                                        <input type="hidden" name="id" value="<?php echo (int)$g['id']; ?>">
                                                        <button type="submit" class="btn btn-outline-danger" title="ডিলিট">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="groupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-layer-group"></i> <span id="modalTitle">নতুন গ্রুপ</span></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" id="formAction" value="add">
                    <input type="hidden" name="id" id="groupId" value="">
                    <div class="mb-3">
                        <label class="form-label">গ্রুপ নাম <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="group_name" id="groupName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">গ্রুপ কোড <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="group_code" id="groupCode" required>
                        <div class="form-text">উদাহরণ: SCI, COM, ARTS</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">বিবরণ</label>
                        <textarea class="form-control" rows="3" name="description" id="groupDescription"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">অবস্থা</label>
                        <select class="form-select" name="status" id="groupStatus">
                            <option value="active">সক্রিয়</option>
                            <option value="inactive">নিষ্ক্রিয়</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                    <button type="submit" class="btn btn-primary">সংরক্ষণ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const groupModal = document.getElementById('groupModal');
if (groupModal) {
    groupModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const id = button?.getAttribute('data-id');
        const name = button?.getAttribute('data-name') || '';
        const code = button?.getAttribute('data-code') || '';
        const description = button?.getAttribute('data-description') || '';
        const status = button?.getAttribute('data-status') || 'active';

        const modalTitle = document.getElementById('modalTitle');
        const formAction = document.getElementById('formAction');
        const groupId = document.getElementById('groupId');
        const groupName = document.getElementById('groupName');
        const groupCode = document.getElementById('groupCode');
        const groupDescription = document.getElementById('groupDescription');
        const groupStatus = document.getElementById('groupStatus');

        if (id) {
            modalTitle.textContent = 'গ্রুপ সম্পাদনা';
            formAction.value = 'update';
            groupId.value = id;
            groupName.value = name;
            groupCode.value = code;
            groupDescription.value = description;
            groupStatus.value = status;
        } else {
            modalTitle.textContent = 'নতুন গ্রুপ';
            formAction.value = 'add';
            groupId.value = '';
            groupName.value = '';
            groupCode.value = '';
            groupDescription.value = '';
            groupStatus.value = 'active';
        }
    });
}
</script>
</body>
</html>