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

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

// Check if the user has sufficient permissions (assuming admin level 8-9 are super admins)
$admin_level = $_SESSION['admin_level'] ?? 0;
if ($admin_level < 8) {
    header('Location: index.php?error=insufficient_permissions');
    exit();
}

$pageTitle = 'Admin Management';
$currentPage = 'admins';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- Google Font: Source Sans Pro -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
    <link rel="stylesheet" href="plugins/datatables-buttons/css/buttons.bootstrap4.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="plugins/sweetalert2-theme-bootstrap-4/bootstrap-4.min.css">
    <!-- Select2 -->
    <link rel="stylesheet" href="plugins/select2/css/select2.min.css">
    <link rel="stylesheet" href="plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    
    <style>
        .admin-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #f8f9fa;
        }
        
        .permission-group {
            margin-bottom: 20px;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 10px;
        }
        
        .permission-group h5 {
            margin-bottom: 15px;
            font-weight: 600;
        }
        
        .permission-item {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 4px;
            background-color: #f8f9fa;
        }
        
        .online-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }
        
        .online-indicator.online {
            background-color: #28a745;
        }
        
        .online-indicator.offline {
            background-color: #dc3545;
        }
        
        .admin-card {
            transition: all 0.3s ease;
        }
        
        .admin-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        
        .admin-level-badge {
            position: absolute;
            top: 0;
            right: 0;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            background-color: #007bff;
            color: white;
            font-weight: bold;
            border: 2px solid white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-users-cog text-primary"></i> Admin Management
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Admin Management</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Admin Summary -->
                <div class="row">
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-info">
                            <div class="inner">
                                <h3 id="totalAdmins">0</h3>
                                <p>Total Administrators</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-users-cog"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-success">
                            <div class="inner">
                                <h3 id="activeAdmins">0</h3>
                                <p>Active Administrators</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-user-check"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-warning">
                            <div class="inner">
                                <h3 id="onlineAdmins">0</h3>
                                <p>Online Now</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-signal"></i>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-6">
                        <div class="small-box bg-danger">
                            <div class="inner">
                                <h3 id="superAdmins">0</h3>
                                <p>Super Administrators</p>
                            </div>
                            <div class="icon">
                                <i class="fas fa-user-shield"></i>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Admin Management Card -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Administrator Accounts</h3>
                        <div class="card-tools">
                            <?php if ($admin_level >= 9): ?>
                            <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addAdminModal">
                                <i class="fas fa-user-plus"></i> Add New Admin
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-8">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="searchAdmin" placeholder="Search administrators...">
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary" type="button" id="searchButton">
                                            <i class="fas fa-search"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-right">
                                <div class="btn-group">
                                    <button type="button" class="btn btn-default" id="viewGridBtn">
                                        <i class="fas fa-th-large"></i> Grid
                                    </button>
                                    <button type="button" class="btn btn-default active" id="viewListBtn">
                                        <i class="fas fa-list"></i> List
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Admin List View -->
                        <div id="adminListView">
                            <table id="adminsTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th style="width: 50px;">Photo</th>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Role</th>
                                        <th>Level</th>
                                        <th>Status</th>
                                        <th>Last Login</th>
                                        <th style="width: 120px;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="adminsList">
                                    <!-- Admin list will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Admin Grid View -->
                        <div id="adminGridView" class="row" style="display: none;">
                            <!-- Admin grid will be loaded here -->
                        </div>
                        
                        <!-- Pagination -->
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <p id="paginationInfo">Showing 0 to 0 of 0 entries</p>
                            </div>
                            <div class="col-md-6">
                                <nav aria-label="Admin pagination">
                                    <ul class="pagination justify-content-end" id="adminPagination">
                                        <!-- Pagination will be loaded here -->
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
    
    <!-- Add Admin Modal -->
    <div class="modal fade" id="addAdminModal" tabindex="-1" role="dialog" aria-labelledby="addAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary">
                    <h5 class="modal-title" id="addAdminModalLabel">
                        <i class="fas fa-user-plus"></i> Add New Administrator
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addAdminForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="addName">Full Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="addName" name="name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="addEmail">Email <span class="text-danger">*</span></label>
                                    <input type="email" class="form-control" id="addEmail" name="email" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="addPassword">Password <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="addPassword" name="password" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="addConfirmPassword">Confirm Password <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="addConfirmPassword" name="confirm_password" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="addRole">Role <span class="text-danger">*</span></label>
                                    <select class="form-control" id="addRole" name="role" required>
                                        <option value="Administrator">Administrator</option>
                                        <option value="Finance Manager">Finance Manager</option>
                                        <option value="Event Manager">Event Manager</option>
                                        <option value="Member Manager">Member Manager</option>
                                        <option value="Content Manager">Content Manager</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="addAdminLevel">Admin Level <span class="text-danger">*</span></label>
                                    <select class="form-control" id="addAdminLevel" name="admin_level" required>
                                        <option value="4">Level 4 - Basic</option>
                                        <option value="5">Level 5 - Standard</option>
                                        <option value="6">Level 6 - Advanced</option>
                                        <option value="7">Level 7 - Senior</option>
                                        <option value="8">Level 8 - Manager</option>
                                        <option value="9">Level 9 - Super Admin</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="addStatus">Status <span class="text-danger">*</span></label>
                            <select class="form-control" id="addStatus" name="status" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="pending">Pending Activation</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Permissions</label>
                            <div id="permissionsContainer" class="mt-3">
                                <!-- Permissions will be loaded here -->
                                <div class="text-center">
                                    <i class="fas fa-spinner fa-spin"></i> Loading permissions...
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="saveAdminBtn">
                        <i class="fas fa-save"></i> Save Administrator
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Edit Admin Modal -->
    <div class="modal fade" id="editAdminModal" tabindex="-1" role="dialog" aria-labelledby="editAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-info">
                    <h5 class="modal-title" id="editAdminModalLabel">
                        <i class="fas fa-user-edit"></i> Edit Administrator
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editAdminForm">
                        <input type="hidden" id="editAdminId" name="admin_id">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editName">Full Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="editName" name="name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editEmail">Email <span class="text-danger">*</span></label>
                                    <input type="email" class="form-control" id="editEmail" name="email" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editPassword">Password (leave blank to keep current)</label>
                                    <input type="password" class="form-control" id="editPassword" name="password">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editConfirmPassword">Confirm Password</label>
                                    <input type="password" class="form-control" id="editConfirmPassword" name="confirm_password">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editRole">Role <span class="text-danger">*</span></label>
                                    <select class="form-control" id="editRole" name="role" required>
                                        <option value="Administrator">Administrator</option>
                                        <option value="Finance Manager">Finance Manager</option>
                                        <option value="Event Manager">Event Manager</option>
                                        <option value="Member Manager">Member Manager</option>
                                        <option value="Content Manager">Content Manager</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editAdminLevel">Admin Level <span class="text-danger">*</span></label>
                                    <select class="form-control" id="editAdminLevel" name="admin_level" required>
                                        <option value="4">Level 4 - Basic</option>
                                        <option value="5">Level 5 - Standard</option>
                                        <option value="6">Level 6 - Advanced</option>
                                        <option value="7">Level 7 - Senior</option>
                                        <option value="8">Level 8 - Manager</option>
                                        <option value="9">Level 9 - Super Admin</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="editStatus">Status <span class="text-danger">*</span></label>
                            <select class="form-control" id="editStatus" name="status" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="pending">Pending Activation</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Permissions</label>
                            <div id="editPermissionsContainer" class="mt-3">
                                <!-- Permissions will be loaded here -->
                                <div class="text-center">
                                    <i class="fas fa-spinner fa-spin"></i> Loading permissions...
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-info" id="updateAdminBtn">
                        <i class="fas fa-save"></i> Update Administrator
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- View Admin Modal -->
    <div class="modal fade" id="viewAdminModal" tabindex="-1" role="dialog" aria-labelledby="viewAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary">
                    <h5 class="modal-title" id="viewAdminModalLabel">
                        <i class="fas fa-user"></i> Administrator Details
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4 text-center">
                            <img id="viewAdminPhoto" src="dist/img/user-default.jpg" class="img-circle elevation-2" alt="Admin Photo" style="width: 150px; height: 150px; object-fit: cover; margin-bottom: 15px;">
                            <h5 id="viewAdminName" class="mb-0">Admin Name</h5>
                            <p id="viewAdminRole" class="text-muted">Role</p>
                            <span id="viewAdminStatus" class="badge badge-success">Active</span>
                            <div class="mt-3">
                                <span id="viewAdminLevel" class="badge badge-primary">Level 9</span>
                            </div>
                        </div>
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Profile Information</h3>
                                </div>
                                <div class="card-body p-0">
                                    <table class="table">
                                        <tr>
                                            <th style="width: 150px;">Email:</th>
                                            <td id="viewAdminEmail">admin@example.com</td>
                                        </tr>
                                        <tr>
                                            <th>Last Login:</th>
                                            <td id="viewAdminLastLogin">2022-01-01 12:00:00</td>
                                        </tr>
                                        <tr>
                                            <th>Account Created:</th>
                                            <td id="viewAdminCreated">2022-01-01</td>
                                        </tr>
                                        <tr>
                                            <th>Account Age:</th>
                                            <td id="viewAdminAge">1 year, 2 months</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Recent Activity</h3>
                                </div>
                                <div class="card-body p-0">
                                    <ul class="list-group list-group-flush" id="viewAdminActivity">
                                        <!-- Activity will be loaded here -->
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Permissions</h3>
                                </div>
                                <div class="card-body">
                                    <div id="viewPermissionsContainer">
                                        <!-- Permissions will be loaded here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-info" id="editAdminBtn">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Delete Admin Confirmation Modal -->
    <div class="modal fade" id="deleteAdminModal" tabindex="-1" role="dialog" aria-labelledby="deleteAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger">
                    <h5 class="modal-title" id="deleteAdminModalLabel">
                        <i class="fas fa-exclamation-triangle"></i> Confirm Delete
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this administrator?</p>
                    <p>This action cannot be undone.</p>
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle"></i> Note: If this admin has recent activity, they will be soft-deleted (deactivated) instead of permanently deleted.
                    </div>
                    <input type="hidden" id="deleteAdminId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteAdminBtn">
                        <i class="fas fa-trash"></i> Delete Administrator
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="plugins/jquery/jquery.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<script src="plugins/sweetalert2/sweetalert2.min.js"></script>
<script src="plugins/select2/js/select2.full.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize variables
    let currentPage = 1;
    let totalPages = 1;
    let adminsPerPage = 10;
    let currentView = 'list';
    let currentPermissions = {};
    
    // Load administrators on page load
    loadAdmins();
    
    // Load permissions
    loadPermissions();
    
    // View toggle handlers
    $('#viewGridBtn').click(function() {
        $('#viewListBtn').removeClass('active');
        $(this).addClass('active');
        $('#adminListView').hide();
        $('#adminGridView').show();
        currentView = 'grid';
    });
    
    $('#viewListBtn').click(function() {
        $('#viewGridBtn').removeClass('active');
        $(this).addClass('active');
        $('#adminGridView').hide();
        $('#adminListView').show();
        currentView = 'list';
    });
    
    // Search handler
    $('#searchButton').click(function() {
        currentPage = 1;
        loadAdmins();
    });
    
    $('#searchAdmin').keypress(function(e) {
        if (e.which === 13) {
            currentPage = 1;
            loadAdmins();
        }
    });
    
    // Add admin form submission
    $('#saveAdminBtn').click(function() {
        if (validateAddAdminForm()) {
            createAdmin();
        }
    });
    
    // Edit admin form submission
    $('#updateAdminBtn').click(function() {
        if (validateEditAdminForm()) {
            updateAdmin();
        }
    });
    
    // Edit button click handler
    $('#editAdminBtn').click(function() {
        $('#viewAdminModal').modal('hide');
        const adminId = $('#viewAdminModal').data('admin-id');
        openEditModal(adminId);
    });
    
    // Delete confirmation
    $('#confirmDeleteAdminBtn').click(function() {
        const adminId = $('#deleteAdminId').val();
        deleteAdmin(adminId);
    });
    
    // Function to load administrators
    function loadAdmins() {
        const search = $('#searchAdmin').val();
        
        $.ajax({
            url: 'api/admins/list.php',
            method: 'GET',
            data: {
                page: currentPage,
                limit: adminsPerPage,
                search: search
            },
            success: function(response) {
                if (response.success) {
                    renderAdmins(response.admins);
                    renderPagination(response.pagination);
                    updateStats(response);
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Failed to load administrators', 'error');
            }
        });
    }
    
    // Function to render administrators
    function renderAdmins(admins) {
        // Render list view
        const tableBody = $('#adminsList');
        tableBody.empty();
        
        // Render grid view
        const gridContainer = $('#adminGridView');
        gridContainer.empty();
        
        if (admins.length === 0) {
            tableBody.html('<tr><td colspan="8" class="text-center">No administrators found</td></tr>');
            return;
        }
        
        admins.forEach(function(admin) {
            // Format status badge
            let statusBadge = '';
            switch (admin.status) {
                case 'active':
                    statusBadge = '<span class="badge badge-success">Active</span>';
                    break;
                case 'inactive':
                    statusBadge = '<span class="badge badge-danger">Inactive</span>';
                    break;
                case 'pending':
                    statusBadge = '<span class="badge badge-warning">Pending</span>';
                    break;
                default:
                    statusBadge = '<span class="badge badge-secondary">Unknown</span>';
            }
            
            // Format admin level badge
            let levelBadge = '';
            switch (parseInt(admin.admin_level)) {
                case 9:
                    levelBadge = '<span class="badge badge-danger">Level 9</span>';
                    break;
                case 8:
                    levelBadge = '<span class="badge badge-warning">Level 8</span>';
                    break;
                case 7:
                    levelBadge = '<span class="badge badge-primary">Level 7</span>';
                    break;
                case 6:
                    levelBadge = '<span class="badge badge-info">Level 6</span>';
                    break;
                case 5:
                    levelBadge = '<span class="badge badge-success">Level 5</span>';
                    break;
                default:
                    levelBadge = '<span class="badge badge-secondary">Level ' + admin.admin_level + '</span>';
            }
            
            // Format last login
            const lastLogin = admin.last_login ? new Date(admin.last_login).toLocaleString() : 'Never';
            
            // Online indicator
            const onlineIndicator = admin.is_online ? 
                '<span class="online-indicator online" title="Online"></span>' : 
                '<span class="online-indicator offline" title="Offline"></span>';
            
            // Render list row
            const row = `
                <tr>
                    <td>
                        <img src="${admin.photo_url || 'dist/img/user-default.jpg'}" class="admin-avatar" alt="${admin.name}">
                    </td>
                    <td>
                        ${onlineIndicator} ${admin.name}
                    </td>
                    <td>${admin.email}</td>
                    <td>${admin.role}</td>
                    <td>${levelBadge}</td>
                    <td>${statusBadge}</td>
                    <td>${lastLogin}</td>
                    <td>
                        <button type="button" class="btn btn-info btn-sm view-admin" data-id="${admin.id}">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button type="button" class="btn btn-primary btn-sm edit-admin" data-id="${admin.id}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button type="button" class="btn btn-danger btn-sm delete-admin" data-id="${admin.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
            tableBody.append(row);
            
            // Render grid card
            const card = `
                <div class="col-md-4 col-sm-6">
                    <div class="card admin-card mb-4">
                        <div class="card-body text-center position-relative">
                            <div class="admin-level-badge">
                                ${admin.admin_level}
                            </div>
                            <img src="${admin.photo_url || 'dist/img/user-default.jpg'}" class="img-circle elevation-2 mb-3" alt="${admin.name}" style="width: 100px; height: 100px; object-fit: cover;">
                            <h5 class="card-title mb-0">${admin.name}</h5>
                            <p class="text-muted mb-2">${admin.role}</p>
                            <p class="mb-2">${admin.email}</p>
                            <div class="mb-3">
                                ${statusBadge}
                            </div>
                            <div class="btn-group">
                                <button type="button" class="btn btn-info btn-sm view-admin" data-id="${admin.id}">
                                    <i class="fas fa-eye"></i> View
                                </button>
                                <button type="button" class="btn btn-primary btn-sm edit-admin" data-id="${admin.id}">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button type="button" class="btn btn-danger btn-sm delete-admin" data-id="${admin.id}">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            gridContainer.append(card);
        });
        
        // Attach event handlers
        $('.view-admin').click(function() {
            const adminId = $(this).data('id');
            viewAdmin(adminId);
        });
        
        $('.edit-admin').click(function() {
            const adminId = $(this).data('id');
            openEditModal(adminId);
        });
        
        $('.delete-admin').click(function() {
            const adminId = $(this).data('id');
            $('#deleteAdminId').val(adminId);
            $('#deleteAdminModal').modal('show');
        });
    }
    
    // Function to render pagination
    function renderPagination(pagination) {
        const paginationContainer = $('#adminPagination');
        paginationContainer.empty();
        
        // Update pagination info
        $('#paginationInfo').text(
            `Showing ${(pagination.current_page - 1) * pagination.per_page + 1} to ${
                Math.min(pagination.current_page * pagination.per_page, pagination.total)
            } of ${pagination.total} entries`
        );
        
        // Previous button
        paginationContainer.append(`
            <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${pagination.current_page - 1}">Previous</a>
            </li>
        `);
        
        // Page numbers
        const totalPages = pagination.last_page;
        const currentPage = pagination.current_page;
        
        // First page
        paginationContainer.append(`
            <li class="page-item ${currentPage === 1 ? 'active' : ''}">
                <a class="page-link" href="#" data-page="1">1</a>
            </li>
        `);
        
        // Ellipsis if needed
        if (currentPage > 3) {
            paginationContainer.append(`
                <li class="page-item disabled">
                    <a class="page-link" href="#">...</a>
                </li>
            `);
        }
        
        // Pages around current page
        for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
            if (i === 1 || i === totalPages) continue; // Skip first and last page (already added)
            paginationContainer.append(`
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        }
        
        // Ellipsis if needed
        if (currentPage < totalPages - 2) {
            paginationContainer.append(`
                <li class="page-item disabled">
                    <a class="page-link" href="#">...</a>
                </li>
            `);
        }
        
        // Last page (if more than 1 page)
        if (totalPages > 1) {
            paginationContainer.append(`
                <li class="page-item ${currentPage === totalPages ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a>
                </li>
            `);
        }
        
        // Next button
        paginationContainer.append(`
            <li class="page-item ${pagination.current_page === pagination.last_page ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${pagination.current_page + 1}">Next</a>
            </li>
        `);
        
        // Attach click handler to pagination links
        $('.page-link').click(function(e) {
            e.preventDefault();
            const page = $(this).data('page');
            if (page && !$(this).parent().hasClass('disabled')) {
                currentPage = page;
                loadAdmins();
            }
        });
    }
    
    // Function to update stats
    function updateStats(data) {
        const admins = data.admins;
        const total = data.pagination.total;
        let active = 0;
        let online = 0;
        let superAdmins = 0;
        
        admins.forEach(function(admin) {
            if (admin.status === 'active') active++;
            if (admin.is_online) online++;
            if (parseInt(admin.admin_level) >= 9) superAdmins++;
        });
        
        $('#totalAdmins').text(total);
        $('#activeAdmins').text(active);
        $('#onlineAdmins').text(online);
        $('#superAdmins').text(superAdmins);
    }
    
    // Function to load permissions
    function loadPermissions() {
        $.ajax({
            url: 'api/admins/permissions.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    currentPermissions = response.permissions;
                    renderPermissionInputs(response.categories, 'permissionsContainer');
                }
            }
        });
    }
    
    // Function to render permission inputs
    function renderPermissionInputs(categories, containerId) {
        const container = $(`#${containerId}`);
        container.empty();
        
        Object.keys(categories).forEach(function(category) {
            const permissions = categories[category];
            const categoryName = category.charAt(0).toUpperCase() + category.slice(1);
            
            let html = `
                <div class="permission-group">
                    <h5>${categoryName} Permissions</h5>
                    <div class="row">
            `;
            
            Object.keys(permissions).forEach(function(key) {
                const permission = permissions[key];
                html += `
                    <div class="col-lg-6">
                        <div class="permission-item">
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="${containerId}_${key}" name="permissions[${key}]" value="1">
                                <label class="custom-control-label" for="${containerId}_${key}">${permission.description}</label>
                                <small class="form-text text-muted">Required level: ${permission.min_level}</small>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += `
                    </div>
                </div>
            `;
            
            container.append(html);
        });
    }
    
    // Function to set permissions in form
    function setPermissions(permissions, containerId) {
        // Reset all checkboxes
        $(`#${containerId} input[type="checkbox"]`).prop('checked', false);
        
        // Set checked based on permissions
        Object.keys(permissions).forEach(function(key) {
            $(`#${containerId}_${key}`).prop('checked', permissions[key]);
        });
    }
    
    // Function to get permissions from form
    function getPermissions(containerId) {
        const permissions = {};
        $(`#${containerId} input[type="checkbox"]`).each(function() {
            const key = $(this).attr('name').match(/\[(.*?)\]/)[1];
            permissions[key] = $(this).is(':checked');
        });
        return permissions;
    }
    
    // Function to validate add admin form
    function validateAddAdminForm() {
        const name = $('#addName').val();
        const email = $('#addEmail').val();
        const password = $('#addPassword').val();
        const confirmPassword = $('#addConfirmPassword').val();
        
        if (!name || !email || !password) {
            Swal.fire('Error', 'Please fill in all required fields', 'error');
            return false;
        }
        
        if (password !== confirmPassword) {
            Swal.fire('Error', 'Passwords do not match', 'error');
            return false;
        }
        
        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            Swal.fire('Error', 'Please enter a valid email address', 'error');
            return false;
        }
        
        return true;
    }
    
    // Function to validate edit admin form
    function validateEditAdminForm() {
        const name = $('#editName').val();
        const email = $('#editEmail').val();
        const password = $('#editPassword').val();
        const confirmPassword = $('#editConfirmPassword').val();
        
        if (!name || !email) {
            Swal.fire('Error', 'Please fill in all required fields', 'error');
            return false;
        }
        
        // Only validate passwords if being changed
        if (password && password !== confirmPassword) {
            Swal.fire('Error', 'Passwords do not match', 'error');
            return false;
        }
        
        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            Swal.fire('Error', 'Please enter a valid email address', 'error');
            return false;
        }
        
        return true;
    }
    
    // Function to create a new admin
    function createAdmin() {
        const formData = new FormData(document.getElementById('addAdminForm'));
        
        // Add permissions to form data
        const permissions = getPermissions('permissionsContainer');
        formData.append('permissions', JSON.stringify(permissions));
        
        // Show loading indicator
        Swal.fire({
            title: 'Creating administrator...',
            html: 'Please wait while we create the account and send the welcome email.',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: 'api/admins/create.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    let message = 'Administrator created successfully.';
                    
                    if (response.email_sent) {
                        message += ' A welcome email has been sent to the administrator with their login credentials.';
                    } else {
                        message += ' However, the welcome email could not be sent. Please notify the administrator manually.';
                    }
                    
                    Swal.fire({
                        title: 'Success',
                        icon: 'success',
                        html: message,
                        confirmButtonText: 'OK'
                    });
                    
                    $('#addAdminModal').modal('hide');
                    $('#addAdminForm')[0].reset();
                    loadAdmins();
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Failed to create administrator', 'error');
            }
        });
    }
    
    // Function to open edit modal
    function openEditModal(adminId) {
        $.ajax({
            url: 'api/admins/details.php',
            method: 'GET',
            data: { id: adminId },
            success: function(response) {
                if (response.success) {
                    const admin = response.admin;
                    
                    // Populate form fields
                    $('#editAdminId').val(admin.id);
                    $('#editName').val(admin.name);
                    $('#editEmail').val(admin.email);
                    $('#editRole').val(admin.role);
                    $('#editAdminLevel').val(admin.admin_level);
                    $('#editStatus').val(admin.status);
                    
                    // Clear password fields
                    $('#editPassword').val('');
                    $('#editConfirmPassword').val('');
                    
                    // Set permissions
                    setPermissions(admin.permissions, 'editPermissionsContainer');
                    
                    $('#editAdminModal').modal('show');
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Failed to load administrator details', 'error');
            }
        });
    }
    
    // Function to update an admin
    function updateAdmin() {
        const formData = new FormData(document.getElementById('editAdminForm'));
        
        // Add permissions to form data
        const permissions = getPermissions('editPermissionsContainer');
        formData.append('permissions', JSON.stringify(permissions));
        
        $.ajax({
            url: 'api/admins/update.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    Swal.fire('Success', 'Administrator updated successfully', 'success');
                    $('#editAdminModal').modal('hide');
                    loadAdmins();
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Failed to update administrator', 'error');
            }
        });
    }
    
    // Function to view admin details
    function viewAdmin(adminId) {
        $.ajax({
            url: 'api/admins/details.php',
            method: 'GET',
            data: { id: adminId },
            success: function(response) {
                if (response.success) {
                    const admin = response.admin;
                    
                    // Set admin ID for edit button
                    $('#viewAdminModal').data('admin-id', admin.id);
                    
                    // Populate profile information
                    $('#viewAdminPhoto').attr('src', admin.photo_url || 'dist/img/user-default.jpg');
                    $('#viewAdminName').text(admin.name);
                    $('#viewAdminRole').text(admin.role);
                    $('#viewAdminEmail').text(admin.email);
                    $('#viewAdminLastLogin').text(admin.last_login || 'Never');
                    $('#viewAdminCreated').text(admin.created_at);
                    
                    // Format account age
                    let ageText = '';
                    if (admin.account_age.years > 0) {
                        ageText += admin.account_age.years + ' year' + (admin.account_age.years !== 1 ? 's' : '');
                    }
                    if (admin.account_age.months > 0) {
                        ageText += (ageText ? ', ' : '') + admin.account_age.months + ' month' + (admin.account_age.months !== 1 ? 's' : '');
                    }
                    if (admin.account_age.days > 0 || ageText === '') {
                        ageText += (ageText ? ', ' : '') + admin.account_age.days + ' day' + (admin.account_age.days !== 1 ? 's' : '');
                    }
                    $('#viewAdminAge').text(ageText);
                    
                    // Set status badge
                    let statusBadge = '';
                    switch (admin.status) {
                        case 'active':
                            statusBadge = '<span class="badge badge-success">Active</span>';
                            break;
                        case 'inactive':
                            statusBadge = '<span class="badge badge-danger">Inactive</span>';
                            break;
                        case 'pending':
                            statusBadge = '<span class="badge badge-warning">Pending</span>';
                            break;
                        default:
                            statusBadge = '<span class="badge badge-secondary">Unknown</span>';
                    }
                    $('#viewAdminStatus').html(statusBadge);
                    
                    // Set admin level badge
                    $('#viewAdminLevel').text('Level ' + admin.admin_level);
                    
                    // Populate recent activity
                    const activityContainer = $('#viewAdminActivity');
                    activityContainer.empty();
                    
                    if (admin.recent_activity && admin.recent_activity.length > 0) {
                        admin.recent_activity.forEach(function(activity) {
                            activityContainer.append(`
                                <li class="list-group-item">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <strong>${activity.action}</strong>
                                            <p class="mb-0">${activity.details}</p>
                                        </div>
                                        <small class="text-muted">${new Date(activity.created_at).toLocaleString()}</small>
                                    </div>
                                </li>
                            `);
                        });
                    } else {
                        activityContainer.append('<li class="list-group-item text-center">No recent activity</li>');
                    }
                    
                    // Populate permissions
                    const permissionsContainer = $('#viewPermissionsContainer');
                    permissionsContainer.empty();
                    
                    if (admin.permissions) {
                        let permHtml = '<div class="row">';
                        Object.keys(admin.permissions).forEach(function(key) {
                            const granted = admin.permissions[key];
                            const permDesc = currentPermissions[key] ? currentPermissions[key].description : key;
                            
                            permHtml += `
                                <div class="col-lg-6 col-md-12 mb-2">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-${granted ? 'check text-success' : 'times text-danger'} mr-2"></i>
                                        <span>${permDesc}</span>
                                    </div>
                                </div>
                            `;
                        });
                        permHtml += '</div>';
                        permissionsContainer.html(permHtml);
                    } else {
                        permissionsContainer.html('<p class="text-center">No permissions data available</p>');
                    }
                    
                    $('#viewAdminModal').modal('show');
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Failed to load administrator details', 'error');
            }
        });
    }
    
    // Function to delete an admin
    function deleteAdmin(adminId) {
        $.ajax({
            url: 'api/admins/delete.php',
            method: 'POST',
            data: { admin_id: adminId },
            success: function(response) {
                if (response.success) {
                    Swal.fire('Success', 'Administrator ' + (response.delete_type === 'soft' ? 'deactivated' : 'deleted') + ' successfully', 'success');
                    $('#deleteAdminModal').modal('hide');
                    loadAdmins();
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Failed to delete administrator', 'error');
            }
        });
    }
});
</script>

</body>
</html>
