<?php
include '../config.php';

if (!isAdmin()) {
    redirect('../login.php');
}

// Handle actions (delete, toggle status, reset password)
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $action = $_GET['action'];
    
    if ($action == 'delete') {
        // Check if user has lms_courses or lms_enrollments before deleting
        $check_lms_courses = $conn->query("SELECT COUNT(*) as total FROM lms_courses WHERE id_guru = $id");
        $check_lms_enrollments = $conn->query("SELECT COUNT(*) as total FROM lms_enrollments WHERE id_siswa = $id");
        
        $has_lms_courses = $check_lms_courses->fetch_assoc()['total'] > 0;
        $has_lms_enrollments = $check_lms_enrollments->fetch_assoc()['total'] > 0;
        
        if ($has_lms_courses || $has_lms_enrollments) {
            $_SESSION['error'] = "Tidak dapat menghapus user yang memiliki kursus atau enrollment!";
        } else {
            $conn->query("DELETE FROM lms_users WHERE id = $id");
            $_SESSION['success'] = "User berhasil dihapus!";
        }
    } elseif ($action == 'toggle_status') {
        $current_status = $conn->query("SELECT status FROM lms_users WHERE id = $id")->fetch_assoc()['status'];
        $new_status = $current_status == 'active' ? 'inactive' : 'active';
        $conn->query("UPDATE lms_users SET status = '$new_status' WHERE id = $id");
        $_SESSION['success'] = "Status user berhasil diubah!";
    } elseif ($action == 'reset_password') {
        // Reset password to default: 123
        $default_password = password_hash('123', PASSWORD_DEFAULT);
        $conn->query("UPDATE lms_users SET password = '$default_password' WHERE id = $id");
        $_SESSION['success'] = "Password user berhasil direset ke '123'!";
    }
    
    header("Location: manage_users.php");
    exit();
}

// Get all lms_users with pagination
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Search functionality
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$role_filter = isset($_GET['role']) ? $conn->real_escape_string($_GET['role']) : '';

$where_conditions = [];
if (!empty($search)) {
    $where_conditions[] = "(nama_lengkap LIKE '%$search%' OR username LIKE '%$search%' OR email LIKE '%$search%')";
}
if (!empty($role_filter)) {
    $where_conditions[] = "role = '$role_filter'";
}

$where_sql = '';
if (!empty($where_conditions)) {
    $where_sql = "WHERE " . implode(" AND ", $where_conditions);
}

// Get total count for pagination
$count_result = $conn->query("SELECT COUNT(*) as total FROM lms_users $where_sql");
$total_lms_users = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_lms_users / $limit);

// Get lms_users data
$sql_lms_users = "SELECT * FROM lms_users $where_sql ORDER BY tanggal_daftar DESC LIMIT $limit OFFSET $offset";
$result_lms_users = $conn->query($sql_lms_users);

// Get current admin ID
$current_admin_id = $_SESSION['user_id'];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola User - SMANSAB LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .table-actions {
            white-space: nowrap;
        }
        .status-active {
            color: #198754;
        }
        .status-inactive {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <!-- Navbar Admin -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand fw-bold" href="dashboard.php">SMANSAB LMS - Admin</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="manage_users.php">Kelola User</a>
                <a class="nav-link" href="manage_courses.php">Kelola Kursus</a>
                <a class="nav-link" href="../logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>Kelola User</h2>
            <a href="add_user.php" class="btn btn-primary">
                <i class="bi bi-plus-circle"></i> Tambah User
            </a>
        </div>

        <!-- Alert Messages -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Search and Filter Form -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" action="">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <input type="text" name="search" class="form-control" placeholder="Cari user..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-md-3">
                            <select name="role" class="form-select">
                                <option value="">Semua Role</option>
                                <option value="admin" <?php echo $role_filter == 'admin' ? 'selected' : ''; ?>>Admin</option>
                                <option value="guru" <?php echo $role_filter == 'guru' ? 'selected' : ''; ?>>Guru</option>
                                <option value="siswa" <?php echo $role_filter == 'siswa' ? 'selected' : ''; ?>>Siswa</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button type="submit" class="btn btn-primary w-100">Filter</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- lms_users Table -->
        <div class="card">
            <div class="card-body">
                <?php if ($result_lms_users->num_rows > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Username</th>
                                    <th>Nama Lengkap</th>
                                    <th>Email</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                    <th>Tanggal Daftar</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($user = $result_lms_users->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo $user['id']; ?></td>
                                    <td><?php echo htmlspecialchars($user['username']); ?></td>
                                    <td><?php echo htmlspecialchars($user['nama_lengkap']); ?></td>
                                    <td><?php echo htmlspecialchars($user['email']); ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo $user['role'] == 'admin' ? 'danger' : 
                                                 ($user['role'] == 'guru' ? 'warning' : 'success'); 
                                        ?>">
                                            <?php echo ucfirst($user['role']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo $user['status'] == 'active' ? 'success' : 'secondary'; ?>">
                                            <?php echo ucfirst($user['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($user['tanggal_daftar'])); ?></td>
                                    <td class="table-actions">
                                        <a href="edit_user.php?id=<?php echo $user['id']; ?>" 
                                           class="btn btn-sm btn-outline-primary" title="Edit">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <a href="?action=toggle_status&id=<?php echo $user['id']; ?>" 
                                           class="btn btn-sm btn-outline-<?php echo $user['status'] == 'active' ? 'warning' : 'success'; ?>" 
                                           title="<?php echo $user['status'] == 'active' ? 'Nonaktifkan' : 'Aktifkan'; ?>"
                                           onclick="return confirm('Yakin ingin mengubah status user?')">
                                            <i class="bi bi-<?php echo $user['status'] == 'active' ? 'pause' : 'play'; ?>"></i>
                                        </a>
                                        <a href="?action=reset_password&id=<?php echo $user['id']; ?>" 
                                           class="btn btn-sm btn-outline-info" title="Reset Password"
                                           onclick="return confirm('Yakin ingin mereset password user ini menjadi \\'123\\'?')">
                                            <i class="bi bi-key"></i>
                                        </a>
                                        <?php if ($user['id'] != $current_admin_id): ?>
                                            <a href="?action=delete&id=<?php echo $user['id']; ?>" 
                                               class="btn btn-sm btn-outline-danger" title="Hapus"
                                               onclick="return confirm('Yakin ingin menghapus user ini?')">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        <?php else: ?>
                                            <button class="btn btn-sm btn-outline-secondary" title="Tidak dapat menghapus akun sendiri" disabled>
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&role=<?php echo urlencode($role_filter); ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="text-center py-4">
                        <i class="bi bi-people display-1 text-muted"></i>
                        <h4 class="text-muted mt-3">Tidak ada user ditemukan</h4>
                        <p class="text-muted">Silakan ubah kriteria pencarian atau tambah user baru.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Summary -->
        <div class="row mt-4">
            <div class="col-md-4">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <h5>Total User</h5>
                        <h3><?php echo $total_lms_users; ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h5>User Aktif</h5>
                        <h3>
                            <?php 
                            $active_count = $conn->query("SELECT COUNT(*) as total FROM lms_users WHERE status = 'active'")->fetch_assoc()['total'];
                            echo $active_count;
                            ?>
                        </h3>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h5>User Baru (Bulan Ini)</h5>
                        <h3>
                            <?php 
                            $new_count = $conn->query("SELECT COUNT(*) as total FROM lms_users WHERE MONTH(tanggal_daftar) = MONTH(CURRENT_DATE()) AND YEAR(tanggal_daftar) = YEAR(CURRENT_DATE())")->fetch_assoc()['total'];
                            echo $new_count;
                            ?>
                        </h3>
                    </div>
                </div>
            </div>
        </div>
    </div>

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