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

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

// Get system name for branding
$system_name = get_system_name($pdo);

$success_message = '';
$error_message = '';

// Handle user creation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_user'])) {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $role = trim($_POST['role']);

    if (empty($username) || empty($email) || empty($password) || empty($role)) {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
        // Don't clear POST data on validation error - preserve form data
    } elseif (strlen($username) < 3) {
        $error_message = 'ইউজারনেম কমপক্ষে ৩ অক্ষরের হতে হবে';
    } elseif (strlen($password) < 6) {
        $error_message = 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'সঠিক ইমেইল ঠিকানা দিন';
    } else {
        try {
            // Check if username or email already exists
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);

            if ($stmt->fetchColumn() > 0) {
                $error_message = 'এই ইউজারনেম বা ইমেইল ইতিমধ্যে ব্যবহৃত হয়েছে';
                // Don't clear POST data on duplicate error - preserve form data
            } else {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO users (username, email, password, role)
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([$username, $email, $hashed_password, $role]);

                $success_message = 'নতুন ইউজার সফলভাবে তৈরি হয়েছে';
                $_POST = array(); // Clear form data only on successful creation
            }
        } catch (Exception $e) {
            $error_message = 'ইউজার তৈরিতে সমস্যা: ' . $e->getMessage();
            // Don't clear POST data on database error - preserve form data
        }
    }
}

// Handle user status update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_status'])) {
    $user_id = (int)$_POST['user_id'];
    $status = $_POST['status'];
    
    try {
        $stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt->execute([$status, $user_id]);
        
    } catch (Exception $e) {
        $error_message = 'স্ট্যাণাস আপডেটে সমস্যা: ' . $e->getMessage();
    }
}

// Pagination and search parameters
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = isset($_GET['per_page']) ? max(5, min(100, (int)$_GET['per_page'])) : 10;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$role_filter = isset($_GET['role_filter']) ? $_GET['role_filter'] : '';
$status_filter = isset($_GET['status_filter']) ? $_GET['status_filter'] : '';
$session_filter = isset($_GET['session_filter']) ? $_GET['session_filter'] : '';
$class_filter = isset($_GET['class_filter']) ? $_GET['class_filter'] : '';
$group_filter = isset($_GET['group_filter']) ? $_GET['group_filter'] : '';

// Build search conditions
$where_conditions = [];
$params = [];

if (!empty($search)) {
    $where_conditions[] = "(
        u.username LIKE ? OR 
        u.email LIKE ? OR 
        CONCAT(s.first_name, ' ', s.last_name) LIKE ? OR 
        CONCAT(t.first_name, ' ', t.last_name) LIKE ?
    )";
    $search_param = '%' . $search . '%';
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
}

if (!empty($role_filter)) {
    $where_conditions[] = "u.role = ?";
    $params[] = $role_filter;
}

if (!empty($status_filter)) {
    $where_conditions[] = "u.status = ?";
    $params[] = $status_filter;
}

// Add session, class, and group filters when role is student
if ($role_filter === 'student') {
    if (!empty($session_filter)) {
        $where_conditions[] = "s.session = ?";
        $params[] = $session_filter;
    }
    
    if (!empty($class_filter)) {
        $where_conditions[] = "s.class_id = ?";
        $params[] = $class_filter;
    }
    
    if (!empty($group_filter)) {
        $where_conditions[] = "s.group_name = ?";
        $params[] = $group_filter;
    }
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count for pagination
$count_sql = "
    SELECT COUNT(*) as total
    FROM users u
    LEFT JOIN students s ON u.id = s.user_id
    LEFT JOIN teachers t ON u.id = t.user_id
    $where_clause
";

// Get academic sessions for dropdown
$session_sql = "SELECT DISTINCT session FROM students WHERE session IS NOT NULL ORDER BY session DESC";
$session_stmt = $pdo->query($session_sql);
$sessions = $session_stmt->fetchAll();

// Get classes for dropdown
$class_sql = "SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section";
$class_stmt = $pdo->query($class_sql);
$classes = $class_stmt->fetchAll();

// Get student groups for dropdown
$group_sql = "SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name";
$group_stmt = $pdo->query($group_sql);
$groups = $group_stmt->fetchAll();
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($params);
$total_users = $count_stmt->fetch()['total'];
$total_pages = ceil($total_users / $per_page);

// Get users with pagination
$offset = ($page - 1) * $per_page;
$sql = "
    SELECT u.*, 
           CASE 
               WHEN u.role = 'student' THEN CONCAT(s.first_name, ' ', s.last_name)
               WHEN u.role = 'teacher' THEN CONCAT(t.first_name, ' ', t.last_name)
               ELSE u.username
           END as full_name
    FROM users u
    LEFT JOIN students s ON u.id = s.user_id
    LEFT JOIN teachers t ON u.id = t.user_id
    $where_clause
    ORDER BY u.created_at DESC
    LIMIT $per_page OFFSET $offset
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

// Get user statistics (filtered)
$stats_sql = "
    SELECT 
        COUNT(*) as total_users,
        SUM(CASE WHEN u.role = 'admin' THEN 1 ELSE 0 END) as admin_users,
        SUM(CASE WHEN u.role = 'teacher' THEN 1 ELSE 0 END) as teacher_users,
        SUM(CASE WHEN u.role = 'student' THEN 1 ELSE 0 END) as student_users,
        SUM(CASE WHEN u.status = 'active' THEN 1 ELSE 0 END) as active_users,
        SUM(CASE WHEN u.status = 'inactive' THEN 1 ELSE 0 END) as inactive_users
    FROM users u
    LEFT JOIN students s ON u.id = s.user_id
    LEFT JOIN teachers t ON u.id = t.user_id
    $where_clause
";
$stats_stmt = $pdo->prepare($stats_sql);
$stats_stmt->execute($params);
$user_stats = $stats_stmt->fetch();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ইউজার ব্যবস্থাপনা - <?php echo htmlspecialchars($system_name); ?></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>
        .form-select-container {
            position: relative;
            display: block;
        }
        .dropdown-icon {
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
            pointer-events: none;
            z-index: 1;
        }
        .form-select {
            padding-right: 30px;
        }
    </style>
</head>
<body>
    <header class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <span class="navbar-brand">ইউজার ব্যবস্থাপনা</span>
            <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="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </header>

    <div class="container-fluid mt-4">
        <!-- User Statistics -->
        <div class="row mb-4">
            <div class="col-md-2">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $user_stats['total_users'] ?: 0; ?></h4>
                        <p class="mb-0">মোট ইউজার</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-danger text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $user_stats['admin_users'] ?: 0; ?></h4>
                        <p class="mb-0">অ্যাডমিন</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $user_stats['teacher_users'] ?: 0; ?></h4>
                        <p class="mb-0">শিক্ষক</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $user_stats['student_users'] ?: 0; ?></h4>
                        <p class="mb-0">ছাত্র-ছাত্রী</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-warning text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $user_stats['active_users'] ?: 0; ?></h4>
                        <p class="mb-0">সক্রিয়</p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card bg-secondary text-white">
                    <div class="card-body text-center">
                        <h4><?php echo $user_stats['inactive_users'] ?: 0; ?></h4>
                        <p class="mb-0">নিষ্ক্রিয়</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <h2><i class="fas fa-users-cog"></i> ইউজার ব্যবস্থাপনা</h2>
            </div>
        </div>

        <?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; ?>

                        <div class="alert alert-info alert-dismissible fade show" role="alert">
                            <i class="fas fa-info-circle"></i> <strong>ফর্ম সুরক্ষা:</strong> আপনার ফর্মের তথ্য স্বয়ংক্রিয়ভাবে সংরক্ষিত হয়।
                            ত্রুটি দেখা দিলে তথ্য সংশোধন করে "পেজ রিফ্রেশ করুন" বাটনে ক্লিক করুন।
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>

        <div class="row">
            <!-- Create User Form -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-user-plus"></i> নতুন ইউজার তৈরি</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" id="userForm">
                            <div class="mb-3">
                                <label for="username" class="form-label">ইউজারনেম <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="username" name="username" 
                                       value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="email" class="form-label">ইমেইল <span class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">পাসওয়ার্ড <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="password" class="form-control" id="password" name="password"
                                           minlength="6" required>
                                    <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                        <i class="fas fa-eye" id="passwordIcon"></i>
                                    </button>
                                </div>
                                <div class="form-text">কমপক্ষে ৬ অক্ষরের হতে হবে</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="role" class="form-label">ভূমিকা <span class="text-danger">*</span></label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="">নির্বাচন করুন</option>
                                    <option value="admin" <?php echo (isset($_POST['role']) && $_POST['role'] == 'admin') ? 'selected' : ''; ?>>অ্যাডমিন</option>
                                    <option value="teacher" <?php echo (isset($_POST['role']) && $_POST['role'] == 'teacher') ? 'selected' : ''; ?>>শিক্ষক</option>
                                    <option value="student" <?php echo (isset($_POST['role']) && $_POST['role'] == 'student') ? 'selected' : ''; ?>>ছাত্র-ছাত্রী</option>
                                </select>
                            </div>
                            
                            <button type="submit" name="create_user" class="btn btn-success">
                                <i class="fas fa-save"></i> ইউজার তৈরি করুন
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Users List -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-list"></i> ইউজার তালিকা</h5>
                    </div>
                    <div class="card-body">
                        <!-- Search and Filter Form -->
                        <form method="GET" class="mb-4">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label for="search" class="form-label">অনুসন্ধান</label>
                                    <input type="text" class="form-control" id="search" name="search" 
                                           placeholder="নাম, ইউজারনেম বা ইমেইল লিখুন" 
                                           value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                <div class="col-md-2">
                                    <label for="role_filter" class="form-label">ভূমিকা</label>
                                    <div class="form-select-container">
                                        <select class="form-select" id="role_filter" name="role_filter">
                                            <option value="">সকল ভূমিকা</option>
                                            <option value="admin" <?php echo $role_filter == 'admin' ? 'selected' : ''; ?>>অ্যাডমিন</option>
                                            <option value="teacher" <?php echo $role_filter == 'teacher' ? 'selected' : ''; ?>>শিক্ষক</option>
                                            <option value="student" <?php echo $role_filter == 'student' ? 'selected' : ''; ?>>ছাত্র-ছাত্রী</option>
                                        </select>
                                        <div class="dropdown-icon">
                                            <i class="fas fa-chevron-down"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2" id="session_filter_container" style="display: <?php echo $role_filter == 'student' ? 'block' : 'none'; ?>;">
                                    <label for="session_filter" class="form-label">সেশন</label>
                                    <div class="form-select-container">
                                        <select class="form-select" id="session_filter" name="session_filter">
                                            <option value="">সকল সেশন</option>
                                            <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo htmlspecialchars($session['session']); ?>" <?php echo $session_filter == $session['session'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($session['session']); ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="dropdown-icon">
                                            <i class="fas fa-chevron-down"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2" id="class_filter_container" style="display: <?php echo $role_filter == 'student' ? 'block' : 'none'; ?>;">
                                    <label for="class_filter" class="form-label">ক্লাস</label>
                                    <div class="form-select-container">
                                        <select class="form-select" id="class_filter" name="class_filter">
                                            <option value="">সকল ক্লাস</option>
                                            <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>" <?php echo $class_filter == $class['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="dropdown-icon">
                                            <i class="fas fa-chevron-down"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2" id="group_filter_container" style="display: <?php echo $role_filter == 'student' ? 'block' : 'none'; ?>;">
                                    <label for="group_filter" class="form-label">গ্রুপ</label>
                                    <div class="form-select-container">
                                        <select class="form-select" id="group_filter" name="group_filter">
                                            <option value="">সকল গ্রুপ</option>
                                            <?php foreach ($groups as $group): ?>
                                            <option value="<?php echo htmlspecialchars($group['group_name']); ?>" <?php echo $group_filter == $group['group_name'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($group['group_name']); ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="dropdown-icon">
                                            <i class="fas fa-chevron-down"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label for="status_filter" class="form-label">অবস্থা</label>
                                    <div class="form-select-container">
                                        <select class="form-select" id="status_filter" name="status_filter">
                                            <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 class="dropdown-icon">
                                            <i class="fas fa-chevron-down"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label for="per_page" class="form-label">প্রতি পাতায়</label>
                                    <div class="form-select-container">
                                        <select class="form-select" id="per_page" name="per_page">
                                            <option value="5" <?php echo $per_page == 5 ? 'selected' : ''; ?>>৫টি</option>
                                            <option value="10" <?php echo $per_page == 10 ? 'selected' : ''; ?>>১০টি</option>
                                            <option value="25" <?php echo $per_page == 25 ? 'selected' : ''; ?>>২৫টি</option>
                                            <option value="50" <?php echo $per_page == 50 ? 'selected' : ''; ?>>৫০টি</option>
                                        </select>
                                        <div class="dropdown-icon">
                                            <i class="fas fa-chevron-down"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <div class="d-grid">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-search"></i> খুঁজুন
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <?php if (!empty($search) || !empty($role_filter) || !empty($status_filter) || !empty($session_filter) || !empty($class_filter) || !empty($group_filter)): ?>
                                <div class="mt-2">
                                    <a href="?role_filter=student" class="btn btn-outline-info btn-sm me-1">
                                        <i class="fas fa-user-graduate"></i> শুধুমাত্র ছাত্র
                                    </a>
                                    <a href="users.php" class="btn btn-outline-secondary btn-sm">
                                        <i class="fas fa-times"></i> ফিল্টার মুছুন
                                    </a>
                                </div>
                            <?php endif; ?>
                        </form>
                        
                        <!-- Results Info -->
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <small class="text-muted">
                                    মোট <?php echo $total_users; ?>টি ইউজারের মধ্যে 
                                    <?php echo ($offset + 1); ?>-<?php echo min($offset + $per_page, $total_users); ?>টি দেখানো হচ্ছে
                                </small>
                            </div>
                            <?php if ($total_pages > 1): ?>
                                <div>
                                    <small class="text-muted">পাতা <?php echo $page; ?> of <?php echo $total_pages; ?></small>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>নাম</th>
                                        <th>ইউজারনেম</th>
                                        <th>ইমেইল</th>
                                        <th>ভূমিকা</th>
                                        <th>অবস্থা</th>
                                        <th>তৈরির তারিখ</th>
                                        <th>কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users as $user): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars($user['full_name']); ?></strong>
                                            </td>
                                            <td><?php echo htmlspecialchars($user['username']); ?></td>
                                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                                            <td>
                                                <?php
                                                $role_class = '';
                                                $role_text = '';
                                                switch ($user['role']) {
                                                    case 'admin':
                                                        $role_class = 'bg-danger';
                                                        $role_text = 'অ্যাডমিন';
                                                        break;
                                                    case 'teacher':
                                                        $role_class = 'bg-success';
                                                        $role_text = 'শিক্ষক';
                                                        break;
                                                    case 'student':
                                                        $role_class = 'bg-info';
                                                        $role_text = 'ছাত্র-ছাত্রী';
                                                        break;
                                                }
                                                ?>
                                                <span class="badge <?php echo $role_class; ?>"><?php echo $role_text; ?></span>
                                            </td>
                                            <td>
                                                <?php
                                                $status_class = $user['status'] == 'active' ? 'bg-success' : 'bg-danger';
                                                $status_text = $user['status'] == 'active' ? 'সক্রিয়' : 'নিষ্ক্রিয়';
                                                ?>
                                                <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                            </td>
                                            <td><?php echo date('d/m/Y', strtotime($user['created_at'])); ?></td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                        <form method="POST" style="display: inline;">
                                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                            <input type="hidden" name="status" value="<?php echo $user['status'] == 'active' ? 'inactive' : 'active'; ?>">
                                                            <button type="submit" name="update_status" 
                                                                    class="btn <?php echo $user['status'] == 'active' ? 'btn-warning' : 'btn-success'; ?>" 
                                                                    title="<?php echo $user['status'] == 'active' ? 'নিষ্ক্রিয় করুন' : 'সক্রিয় করুন'; ?>"
                                                                    onclick="return confirm('আপনি কি নিশ্চিত?')">
                                                                <i class="fas <?php echo $user['status'] == 'active' ? 'fa-ban' : 'fa-check'; ?>"></i>
                                                            </button>
                                                        </form>
                                                        <button class="btn btn-danger btn-sm" 
                                                                onclick="resetPassword(<?php echo $user['id']; ?>)" 
                                                                title="পাসওয়ার্ড রিসেট">
                                                            <i class="fas fa-key"></i>
                                                        </button>
                                                    <?php else: ?>
                                                        <span class="badge bg-primary">বর্তমান ইউজার</span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($users)): ?>
                                        <tr>
                                            <td colspan="7" class="text-center py-4">
                                                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                                <p class="text-muted">কোন ইউজার পাওয়া যায়নি</p>
                                                <?php if (!empty($search) || !empty($role_filter) || !empty($status_filter)): ?>
                                                    <a href="users.php" class="btn btn-outline-primary btn-sm">
                                                        সকল ইউজার দেখুন
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- User Management Tips -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h5><i class="fas fa-lightbulb"></i> ইউজার ব্যবস্থাপনা টিপস</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <h6><i class="fas fa-shield-alt text-danger"></i> অ্যাডমিন ইউজার</h6>
                                <ul>
                                    <li>সিস্টেমের সম্পূর্ণ নিয়ন্ত্রণ</li>
                                    <li>সকল মডিউলে অ্যাক্সেস</li>
                                    <li>ইউজার ব্যবস্থাপনা</li>
                                    <li>সেটিংস পরিবর্তন</li>
                                </ul>
                            </div>
                            <div class="col-md-4">
                                <h6><i class="fas fa-chalkboard-teacher text-success"></i> শিক্ষক ইউজার</h6>
                                <ul>
                                    <li>ছাত্র তথ্য দেখা</li>
                                    <li>উপস্থিতি নেওয়া</li>
                                    <li>নম্বর এন্ট্রি</li>
                                    <li>নোটিশ প্রকাশ</li>
                                </ul>
                            </div>
                            <div class="col-md-4">
                                <h6><i class="fas fa-user-graduate text-info"></i> ছাত্র-ছাত্রী ইউজার</h6>
                                <ul>
                                    <li>নিজের প্রোফাইল দেখা</li>
                                    <li>ফলাফল দেখা</li>
                                    <li>উপস্থিতি দেখা</li>
                                    <li>নোটিশ দেখা</li>
                                </ul>
                            </div>
                        </div>
                        
                        <div class="alert alert-warning mt-3" role="alert">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong>সতর্কতা:</strong> অ্যাডমিন ইউজার তৈরি করার সময় সতর্ক থাকুন। শুধুমাত্র বিশ্বস্ত ব্যক্তিদের অ্যাডমিন অ্যাক্সেস দিন।
                        </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 src="../assets/js/script.js"></script>
    <script>
        function resetPassword(userId) {
            if (confirm('আপনি কি নিশ্চিত যে এই ইউজারের পাসওয়ার্ড রিসেট করতে চান?')) {
                const newPassword = prompt('নতুন পাসওয়ার্ড লিখুন (কমপক্ষে ৬ অক্ষর):');
                
                if (newPassword && newPassword.length >= 6) {
                    // AJAX call to reset password
                    fetch('reset_password.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'user_id=' + userId + '&new_password=' + encodeURIComponent(newPassword)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('পাসওয়ার্ড সফলভাবে রিসেট হয়েছে');
                        } else {
                            alert('পাসওয়ার্ড রিসেটে সমস্যা হয়েছে');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('একটি সমস্যা হয়েছে');
                    });
                } else if (newPassword !== null) {
                    alert('পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে');
                }
            }
        }
        
        // Show/hide session, class, and group filters based on role selection
        document.addEventListener('DOMContentLoaded', function() {
            const roleFilter = document.getElementById('role_filter');
            const sessionContainer = document.getElementById('session_filter_container');
            const classContainer = document.getElementById('class_filter_container');
            const groupContainer = document.getElementById('group_filter_container');
            
            function toggleStudentFilters() {
                const selectedRole = roleFilter.value;
                
                if (selectedRole === 'student') {
                    sessionContainer.style.display = 'block';
                    classContainer.style.display = 'block';
                    groupContainer.style.display = 'block';
                } else {
                    sessionContainer.style.display = 'none';
                    classContainer.style.display = 'none';
                    groupContainer.style.display = 'none';
                }
            }
            
            // Initialize on page load
            toggleStudentFilters();
            
            // Add event listener for role filter changes
            roleFilter.addEventListener('change', toggleStudentFilters);
        });

        // Password toggle functionality
        document.addEventListener('DOMContentLoaded', function() {
            const togglePassword = document.getElementById('togglePassword');
            const passwordInput = document.getElementById('password');
            const passwordIcon = document.getElementById('passwordIcon');

            togglePassword.addEventListener('click', function() {
                // Toggle the type attribute
                const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                passwordInput.setAttribute('type', type);

                // Toggle the eye icon
                if (type === 'password') {
                    passwordIcon.classList.remove('fa-eye-slash');
                    passwordIcon.classList.add('fa-eye');
                } else {
                    passwordIcon.classList.remove('fa-eye');
                    passwordIcon.classList.add('fa-eye-slash');
                }
            });
        });

        // Form data persistence and auto-refresh functionality
        document.addEventListener('DOMContentLoaded', function() {
            const userForm = document.getElementById('userForm');
            const usernameInput = document.getElementById('username');
            const emailInput = document.getElementById('email');
            const roleSelect = document.getElementById('role');

            // Load saved form data on page load
            loadFormData();

            // Save form data on input change
            [usernameInput, emailInput, roleSelect].forEach(input => {
                input.addEventListener('input', saveFormData);
                input.addEventListener('change', saveFormData);
            });

            // Form validation and submission handling
            if (userForm) {
                userForm.addEventListener('submit', function(e) {
                    const username = usernameInput.value.trim();
                    const email = emailInput.value.trim();
                    const password = document.getElementById('password').value.trim();
                    const role = roleSelect.value.trim();

                    // Validate required fields
                    if (!username || !email || !password || !role) {
                        e.preventDefault();
                        alert('সকল প্রয়োজনীয় তথ্য পূরণ করুন');
                        return false;
                    }

                    // Validate username length
                    if (username.length < 3) {
                        e.preventDefault();
                        alert('ইউজারনেম কমপক্ষে ৩ অক্ষরের হতে হবে');
                        return false;
                    }

                    // Validate password length
                    if (password.length < 6) {
                        e.preventDefault();
                        alert('পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে');
                        return false;
                    }

                    // Validate email format
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(email)) {
                        e.preventDefault();
                        alert('সঠিক ইমেইল ঠিকানা দিন');
                        return false;
                    }

                    // Clear form data after successful submit
                    setTimeout(() => {
                        const successAlert = document.querySelector('.alert-success');
                        if (successAlert && successAlert.textContent.includes('সফলভাবে তৈরি')) {
                            clearFormData();
                        }
                    }, 1000);
                });
            }

            // Manual refresh functionality for error states
            const errorAlert = document.querySelector('.alert-danger');
            if (errorAlert) {
                // Add a manual refresh button instead of auto-refresh
                const refreshButton = document.createElement('button');
                refreshButton.type = 'button';
                refreshButton.className = 'btn btn-info btn-sm mt-2';
                refreshButton.innerHTML = '<i class="fas fa-sync-alt"></i> পেজ রিফ্রেশ করুন';
                refreshButton.onclick = function() {
                    if (confirm('আপনি কি নিশ্চিত যে পেজ রিফ্রেশ করতে চান? অসংরক্ষিত তথ্য হারিয়ে যাবে।')) {
                        clearFormData();
                        location.reload();
                    }
                };
                errorAlert.parentNode.insertBefore(refreshButton, errorAlert.nextSibling);
            }
        });

        function saveFormData() {
            const formData = getFormData();
            localStorage.setItem('userFormData', JSON.stringify(formData));
        }

        function loadFormData() {
            const savedData = getSavedFormData();
            if (savedData) {
                const usernameInput = document.getElementById('username');
                const emailInput = document.getElementById('email');
                const roleSelect = document.getElementById('role');

                if (usernameInput && savedData.username) usernameInput.value = savedData.username;
                if (emailInput && savedData.email) emailInput.value = savedData.email;
                if (roleSelect && savedData.role) roleSelect.value = savedData.role;
            }
        }

        function clearFormData() {
            localStorage.removeItem('userFormData');
            const usernameInput = document.getElementById('username');
            const emailInput = document.getElementById('email');
            const roleSelect = document.getElementById('role');

            if (usernameInput) usernameInput.value = '';
            if (emailInput) emailInput.value = '';
            if (roleSelect) roleSelect.value = '';
        }

        function getFormData() {
            const usernameInput = document.getElementById('username');
            const emailInput = document.getElementById('email');
            const roleSelect = document.getElementById('role');

            return {
                username: usernameInput ? usernameInput.value : '',
                email: emailInput ? emailInput.value : '',
                role: roleSelect ? roleSelect.value : ''
            };
        }

        function getSavedFormData() {
            const saved = localStorage.getItem('userFormData');
            return saved ? JSON.parse(saved) : null;
        }
    </script>

</body>
</html>