File "index.php"

Full path: /home/itsevak/public_html/prepaiddev.itsevak.com/admin/index.php
File size: 60.17 B (60.17 KB bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Edit   Advanced Editor   Back

<?php
require_once '../includes/functions.php';

// Require backend access
requireBackendAccess();

$user = getCurrentUser();
$userType = $_SESSION['user_type'];

// Redirect operators away from admin panel - they don't need it
if ($userType === 'operator') {
    redirect('/operator/');
}

// Set userTablesExist to true since operators can now see user lists
$userTablesExist = true;

$pageTitle = 'Admin Dashboard';
require_once '../includes/header.php';
?>

<div class="container-fluid py-4">
            <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1 class="h3 mb-0">Admin Dashboard</h1>
                    <div class="d-flex align-items-center">
                        <span class="badge bg-primary me-2"><?php echo ucfirst(str_replace('_', ' ', $userType)); ?></span>
                        <span class="text-muted">Welcome, <?php echo htmlspecialchars($user['name']); ?></span>
                    </div>
                </div>
            </div>
        </div>
        


    <?php if (in_array($userType, ['super_admin', 'admin'])): ?>
        <!-- Admin Dashboard -->
        <div class="row">
            <div class="col-md-3 mb-4">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Operators</h5>
                                <h2 class="mb-0"><?php echo count(getBackendUsers('operators')); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-users fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 mb-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Validators</h5>
                                <h2 class="mb-0"><?php echo count(getBackendUsers('validators')); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-check-circle fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php if ($userType === 'super_admin'): ?>
            <div class="col-md-3 mb-4">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Admins</h5>
                                <h2 class="mb-0"><?php echo count(getBackendUsers('admins')); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-shield-alt fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="col-md-3 mb-4">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title"><?php echo $userType === 'super_admin' ? 'Total Users' : 'Operators & Validators'; ?></h5>
                                <h2 class="mb-0"><?php echo count(getBackendUsers()); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-chart-line fa-2x opacity-75"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- System Statistics Row -->
        <div class="row">
            <div class="col-md-3 mb-4">
                <div class="card bg-secondary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">From Locations</h5>
                                <h2 class="mb-0"><?php echo count(getFromLocations()); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-map-marker-alt fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="manage_from_locations.php" class="btn btn-sm btn-light">Manage</a>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php if (in_array($userType, ['admin', 'super_admin'])): ?>
            <div class="col-md-3 mb-4">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">To Locations</h5>
                                <h2 class="mb-0"><?php echo count(getToLocations()); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-flag-checkered fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="manage_to_locations.php" class="btn btn-sm btn-light">Manage</a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (in_array($userType, ['admin', 'super_admin', 'validator'])): ?>
            <div class="col-md-3 mb-4">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Auto Rickshaws</h5>
                                <h2 class="mb-0">
                                    <?php 
                                    try {
                                        $rickshawCount = count(getAutoRickshaws());
                                        echo $rickshawCount;
                                    } catch (Exception $e) {
                                        echo '0';
                                    }
                                    ?>
                                </h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-truck fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="validate_rickshaws.php" class="btn btn-sm btn-light">Validate</a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (in_array($userType, ['admin', 'super_admin'])): ?>
            <div class="col-md-3 mb-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Fare Routes</h5>
                                <h2 class="mb-0"><?php echo count(getFareDetails()); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-route fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="manage_fares.php" class="btn btn-sm btn-light">Manage</a>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>



        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Quick Navigation</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php if ($userType === 'super_admin'): ?>
                            <div class="col-md-3 mb-3">
                                <a href="manage_from_locations.php" class="btn btn-outline-primary w-100">
                                    <i class="fas fa-map-marker-alt me-2"></i>
                                    Manage From Locations
                                </a>
                            </div>
                            <?php endif; ?>
                            <?php if (in_array($userType, ['admin', 'super_admin'])): ?>
                            <div class="col-md-3 mb-3">
                                <a href="manage_to_locations.php" class="btn btn-outline-info w-100">
                                    <i class="fas fa-flag-checkered me-2"></i>
                                    Manage To Locations
                                </a>
                            </div>
                            <?php endif; ?>
                            <?php if (in_array($userType, ['admin', 'super_admin', 'validator'])): ?>
                            <div class="col-md-3 mb-3">
                                <a href="validate_rickshaws.php" class="btn btn-outline-warning w-100">
                                    <i class="fas fa-truck me-2"></i>
                                    Validate Auto Rickshaws
                                </a>
                            </div>
                            <?php endif; ?>
                            <?php if (in_array($userType, ['admin', 'super_admin'])): ?>
                            <div class="col-md-3 mb-3">
                                <a href="manage_fares.php" class="btn btn-outline-success w-100">
                                    <i class="fas fa-route me-2"></i>
                                    Manage Fares
                                </a>
                            </div>
                            <?php endif; ?>
                            <?php if ($userType === 'super_admin'): ?>
                            <div class="col-md-3 mb-3">
                                <a href="add_user.php" class="btn btn-outline-success w-100">
                                    <i class="fas fa-user-plus me-2"></i>
                                    Add New User
                                </a>
                            </div>
                            <div class="col-md-3 mb-3">
                                <a href="manage_commission.php" class="btn btn-outline-warning w-100">
                                    <i class="fas fa-percentage me-2"></i>
                                    Manage Commission
                                </a>
                            </div>
                            <?php endif; ?>


                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if (in_array($userType, ['super_admin', 'admin'])): ?>
        <!-- User Management Section - Admin Only -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><?php echo $userType === 'super_admin' ? 'Backend User Management' : 'Operator & Validator Management'; ?></h5>
                        <?php if ($userTablesExist): ?>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                            <i class="fas fa-plus"></i> Add New User
                        </button>
                        <?php else: ?>
                        <button type="button" class="btn btn-secondary" disabled title="Database tables not set up yet">
                            <i class="fas fa-plus"></i> Add New User
                        </button>
                        <?php endif; ?>
                    </div>
                    <div class="card-body">
                        <!-- Search and Filter Section -->
                        <?php if ($userTablesExist): ?>
                        <div class="row mb-3 search-filter-section">
                        <?php else: ?>
                        <div class="row mb-3 search-filter-section" style="display: none;">
                        <?php endif; ?>
                            <div class="col-md-8">
                                <label for="searchAll" class="form-label">Search Users</label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <i class="fas fa-search"></i>
                                    </span>
                                    <input type="text" class="form-control" id="searchAll" placeholder="Search by name, email, or phone number...">
                                    <button type="button" class="btn btn-outline-secondary" id="clearSearchBtn">
                                        <i class="fas fa-times"></i> Clear
                                    </button>
                                </div>
                                <small class="form-text text-muted">Search across all user fields simultaneously</small>
                            </div>
                            <div class="col-md-4">
                                <label for="filterUserType" class="form-label">Filter by User Type</label>
                                <select class="form-select" id="filterUserType">
                                    <option value="">All User Types</option>
                                    <option value="operators">Operators</option>
                                    <option value="validators">Validators</option>
                                    <?php if ($userType === 'super_admin'): ?>
                                    <option value="admins">Admins</option>
                                    <option value="super_admins">Super Admins</option>
                                    <?php endif; ?>
                                </select>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-12">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="text-muted" id="searchResultsInfo"></span>
                                    </div>
                                    <div>
                                        <span class="badge bg-info" id="totalUsersCount">0</span>
                                        <small class="text-muted ms-1">Total Users</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($userTablesExist): ?>
                        <div class="table-responsive">
                            <table class="table table-striped" id="usersTable">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Email</th>
                                        <th>Type</th>
                                        <th>Phone</th>
                                        <th>Status</th>
                                        <th>Created</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="usersTableBody">
                                    <?php if ($userTablesExist): ?>
                                        <?php if (empty(getBackendUsers())): ?>
                                            <tr>
                                                <td colspan="7" class="text-center text-muted py-4">
                                                    <i class="fas fa-users fa-2x mb-3"></i>
                                                    <p class="mb-0">No backend users found.</p>
                                                    <small>Use the "Add New User" button above to create your first user.</small>
                                                </td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach (getBackendUsers() as $backendUser): ?>
                                                <?php 
                                                // For admin users, skip admin and super_admin users
                                                if ($userType === 'admin' && in_array($backendUser['user_table'], ['admins', 'super_admins'])) {
                                                    continue;
                                                }
                                                ?>
                                                <tr class="user-row" 
                                                    data-name="<?php echo htmlspecialchars(strtolower($backendUser['name'])); ?>"
                                                    data-email="<?php echo htmlspecialchars(strtolower($backendUser['email'])); ?>"
                                                    data-phone="<?php echo htmlspecialchars(strtolower($backendUser['phone'] ?? '')); ?>"
                                                    data-type="<?php echo htmlspecialchars($backendUser['user_table']); ?>">
                                                    <td><?php echo htmlspecialchars($backendUser['name']); ?></td>
                                                    <td><?php echo htmlspecialchars($backendUser['email']); ?></td>
                                                    <td>
                                                        <span class="badge bg-secondary">
                                                            <?php echo ucfirst(str_replace('s', '', $backendUser['user_table'])); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($backendUser['phone'] ?? '-'); ?></td>
                                                    <td><?php echo getStatusBadge($backendUser['status']); ?></td>
                                                    <td><?php echo formatDate($backendUser['created_at']); ?></td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="btn btn-sm btn-outline-info" onclick="viewUser(<?php echo $backendUser['id']; ?>, '<?php echo $backendUser['user_table']; ?>')" title="View User Details">
                                                                <i class="fas fa-eye"></i>
                                                                <i class="bi bi-eye" style="display: none;"></i>
                                                            </button>
                                                            <button class="btn btn-sm btn-outline-primary" onclick="editUser(<?php echo $backendUser['id']; ?>, '<?php echo $backendUser['user_table']; ?>')" title="Edit User">
                                                                <i class="fas fa-edit"></i>
                                                                <i class="bi bi-pencil-square" style="display: none;"></i>
                                                            </button>
                                                            <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(<?php echo $backendUser['id']; ?>, '<?php echo $backendUser['user_table']; ?>')" title="Delete User">
                                                                <i class="fas fa-trash"></i>
                                                                <i class="bi bi-trash" style="display: none;"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="7" class="text-center text-muted py-4">
                                                <i class="fas fa-database fa-2x mb-3"></i>
                                                <p class="mb-0">Database tables not set up yet.</p>
                                                <small>Please run the database initialization script first.</small>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

    <?php endif; ?>

    <?php if ($userType === 'validator'): ?>
        <!-- Validator Dashboard -->
        <div class="row">
            <div class="col-md-4 mb-4">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Pending Approvals</h5>
                                <h2 class="mb-0">
                                    <?php 
                                    try {
                                        $pendingCount = count(getAutoRickshaws('pending_approval'));
                                        echo $pendingCount;
                                    } catch (Exception $e) {
                                        echo '0';
                                    }
                                    ?>
                                </h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-clock fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="validate_rickshaws.php" class="btn btn-sm btn-light">Review Now</a>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Active Rickshaws</h5>
                                <h2 class="mb-0">
                                    <?php 
                                    try {
                                        $activeCount = count(getAutoRickshaws('active'));
                                        echo $activeCount;
                                    } catch (Exception $e) {
                                        echo '0';
                                    }
                                    ?>
                                </h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-check-circle fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="validate_rickshaws.php" class="btn btn-sm btn-light">View All</a>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-4">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Total Rickshaws</h5>
                                <h2 class="mb-0">
                                    <?php 
                                    try {
                                        $totalCount = count(getAutoRickshaws());
                                        echo $totalCount;
                                    } catch (Exception $e) {
                                        echo '0';
                                    }
                                    ?>
                                </h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-truck fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="validate_rickshaws.php" class="btn btn-sm btn-light">Manage</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <?php endif; ?>

    <?php if ($userType === 'operator'): ?>
        <!-- Operator Dashboard -->
        <div class="row">
            <div class="col-md-4 mb-4">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">To Locations</h5>
                                <h2 class="mb-0"><?php echo count(getToLocations()); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-flag-checkered fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="manage_to_locations.php" class="btn btn-sm btn-light">View</a>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Active Rickshaws</h5>
                                <h2 class="mb-0">
                                    <?php 
                                    try {
                                        $activeCount = count(getAutoRickshaws('active'));
                                        echo $activeCount;
                                    } catch (Exception $e) {
                                        echo '0';
                                    }
                                    ?>
                                </h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-truck fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="validate_rickshaws.php" class="btn btn-sm btn-light">View</a>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-4 mb-4">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h5 class="card-title">Fare Routes</h5>
                                <h2 class="mb-0"><?php echo count(getFareDetails()); ?></h2>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-route fa-2x opacity-75"></i>
                            </div>
                        </div>
                        <div class="mt-2">
                            <a href="manage_fares.php" class="btn btn-sm btn-light">View</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions for Operator -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Quick Actions</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <a href="validate_rickshaws.php" class="btn btn-outline-info w-100">
                                    <i class="fas fa-truck me-2"></i>
                                    View Auto Rickshaws
                                </a>
                            </div>
                            <div class="col-md-4 mb-3">
                                <a href="manage_fares.php" class="btn btn-outline-success w-100">
                                    <i class="fas fa-route me-2"></i>
                                    View Fares
                                </a>
                            </div>
                            <div class="col-md-4 mb-3">
                                <a href="manage_to_locations.php" class="btn btn-outline-primary w-100">
                                    <i class="fas fa-flag-checkered me-2"></i>
                                    View Locations
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <?php endif; ?>
</div>

<style>
/* Icon fallback handling */
.btn i.fas {
    display: inline-block;
}

.btn i.bi {
    display: none;
}

/* Fallback: if Font Awesome fails, show Bootstrap Icons */
.btn i.fas:not([class*="fa-"]) {
    display: none;
}

.btn i.fas:not([class*="fa-"]) + .btn i.bi {
    display: inline-block;
}

/* Button spacing and sizing */
.btn-sm {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
}

.btn + .btn {
    margin-left: 0.25rem;
}

/* Responsive text labels */
@media (max-width: 576px) {
    .btn span {
        display: none !important;
    }
    
    .btn {
        padding: 0.375rem 0.5rem;
    }
}

/* Ensure dropdowns work properly in modals */
.modal .form-select {
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;
}

.modal .form-select option {
    display: block !important;
    visibility: visible !important;
}

/* Search and Filter Styling */
.search-filter-section {
    background-color: #f8f9fa;
    border-radius: 0.375rem;
    padding: 1rem;
    margin-bottom: 1rem;
}

.search-filter-section .form-label {
    font-weight: 500;
    color: #495057;
    margin-bottom: 0.5rem;
}

.search-filter-section .form-control,
.search-filter-section .form-select {
    border: 1px solid #ced4da;
    border-radius: 0.375rem;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.search-filter-section .form-control:focus,
.search-filter-section .form-select:focus {
    border-color: #86b7fe;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

#clearSearchBtn {
    transition: all 0.15s ease-in-out;
}

#clearSearchBtn:hover {
    background-color: #6c757d;
    border-color: #6c757d;
    color: white;
}

#searchResultsInfo {
    font-size: 0.875rem;
    color: #6c757d;
}

#totalUsersCount {
    font-size: 1rem;
    font-weight: 600;
}

/* Responsive adjustments for search filters */
@media (max-width: 768px) {
    .search-filter-section .col-md-3 {
        margin-bottom: 1rem;
    }
    
    .search-filter-section .d-flex {
        flex-direction: column;
        align-items: stretch !important;
    }
    
    .search-filter-section .d-flex > div {
        margin-bottom: 0.5rem;
    }
}
</style>

<!-- Add User Modal -->
<?php if (in_array($userType, ['super_admin', 'admin'])): ?>
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addUserModalLabel"><?php echo $userType === 'super_admin' ? 'Add New Backend User' : 'Add New Operator/Validator'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="addUserForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <div class="mb-3">
                        <label for="userType" class="form-label">User Type</label>
                        <select class="form-select" id="userType" name="userType" required>
                            <option value="">Select User Type</option>
                            <option value="operator">Operator</option>
                            <option value="validator">Validator</option>
                            <?php if ($userType === 'super_admin'): ?>
                            <option value="admin">Admin</option>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="name" class="form-label">Full Name</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="phone" class="form-label">Phone</label>
                        <input type="tel" class="form-control" id="phone" name="phone">
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="password" name="password" required>
                    </div>
                    <div class="mb-3">
                        <label for="confirmPassword" class="form-label">Confirm Password</label>
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add User</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Edit User Modal -->
<?php if (in_array($userType, ['super_admin', 'admin'])): ?>
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel"><?php echo $userType === 'super_admin' ? 'Edit Backend User' : 'Edit Operator/Validator'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editUserForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <input type="hidden" name="user_id" id="editUserId">
                    <input type="hidden" name="user_table" id="editUserTable">
                    
                    <div class="mb-3">
                        <label for="editUserType" class="form-label">User Type</label>
                        <select class="form-select" id="editUserType" name="userType" required>
                            <option value="">Select User Type</option>
                            <option value="operator">Operator</option>
                            <option value="validator">Validator</option>
                            <?php if ($userType === 'super_admin'): ?>
                            <option value="admin">Admin</option>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="editName" class="form-label">Full Name</label>
                        <input type="text" class="form-control" id="editName" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="editEmail" class="form-label">Email</label>
                        <input type="email" class="form-control" id="editEmail" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="editPhone" class="form-label">Phone</label>
                        <input type="tel" class="form-control" id="editPhone" name="phone">
                    </div>
                    <div class="mb-3">
                        <label for="editStatus" class="form-label">Status</label>
                        <select class="form-select" id="editStatus" name="status" required>
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                            <option value="pending">Pending</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="editPassword" class="form-label">New Password (leave blank to keep current)</label>
                        <input type="password" class="form-control" id="editPassword" name="password">
                    </div>
                    <div class="mb-3">
                        <label for="editConfirmPassword" class="form-label">Confirm New Password</label>
                        <input type="password" class="form-control" id="editConfirmPassword" name="confirmPassword">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update User</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- View User Modal -->
<?php if (in_array($userType, ['super_admin', 'admin'])): ?>
<div class="modal fade" id="viewUserModal" tabindex="-1" aria-labelledby="viewUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewUserModalLabel">User Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Name:</strong> <span id="viewUserName"></span></p>
                        <p><strong>Email:</strong> <span id="viewUserEmail"></span></p>
                        <p><strong>Phone:</strong> <span id="viewUserPhone"></span></p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>Type:</strong> <span id="viewUserType"></span></p>
                        <p><strong>Status:</strong> <span id="viewUserStatus"></span></p>
                        <p><strong>Created:</strong> <span id="viewUserCreated"></span></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="editFromViewBtn">
                    <i class="fas fa-edit"></i> Edit User
                </button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Delete User Confirmation Modal -->
<?php if (in_array($userType, ['super_admin', 'admin'])): ?>
<div class="modal fade" id="deleteUserModal" tabindex="-1" aria-labelledby="deleteUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteUserModalLabel"><?php echo $userType === 'super_admin' ? 'Confirm User Deletion' : 'Confirm Operator/Validator Deletion'; ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this <?php echo $userType === 'super_admin' ? 'user' : 'operator/validator'; ?>?</p>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Warning:</strong> This action cannot be undone. The <?php echo $userType === 'super_admin' ? 'user' : 'operator/validator'; ?> will be permanently removed from the system.
                </div>
                <div id="deleteUserInfo">
                    <p><strong>User:</strong> <span id="deleteUserName"></span></p>
                    <p><strong>Email:</strong> <span id="deleteUserEmail"></span></p>
                    <p><strong>Type:</strong> <span id="deleteUserType"></span></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                    <i class="fas fa-trash"></i> Delete <?php echo $userType === 'super_admin' ? 'User' : 'Operator/Validator'; ?>
                </button>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {

    
    // Initialize search and filter functionality after a short delay to ensure DOM is ready
    setTimeout(() => {
        // Check if search elements are visible (only shown when userTablesExist is true)
        const searchSection = document.querySelector('.search-filter-section');
        if (searchSection && searchSection.style.display !== 'none') {
            initializeSearchAndFilter();
        }
    }, 500);
    
    <?php if (in_array($userType, ['super_admin', 'admin'])): ?>
    const addUserForm = document.getElementById('addUserForm');
    if (addUserForm) {
        addUserForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const password = formData.get('password');
            const confirmPassword = formData.get('confirmPassword');
            
            if (password !== confirmPassword) {
                alert('Passwords do not match!');
                return;
            }
            
            // Submit form via AJAX
            fetch('add_user.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                alert('An error occurred while adding the user. Check console for details.');
            });
        });
    }
    <?php endif; ?>
    
    // Handle edit user form submission
    const editUserForm = document.getElementById('editUserForm');
    if (editUserForm) {
        editUserForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const password = formData.get('password');
            const confirmPassword = formData.get('confirmPassword');
            
            // Check if passwords match if password is provided
            if (password && password !== confirmPassword) {
                alert('Passwords do not match!');
                return;
            }
            
            // Submit form via AJAX
            fetch('edit_user.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                alert('An error occurred while updating the user. Check console for details.');
            });
        });
    }
});

function editUser(userId, userTable) {
    // Reset the form first
    document.getElementById('editUserForm').reset();
    
    // Fetch user data and populate the edit modal
    fetch(`get_user.php?id=${userId}&table=${userTable}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const user = data.user;
                
                // Map table names to user types
                const tableToUserTypeMap = {
                    'operators': 'operator',
                    'validators': 'validator',
                    'admins': 'admin',
                    'super_admins': 'super_admin'
                };
                
                const userType = tableToUserTypeMap[userTable] || userTable.replace('s', '');
                
                // For admin users, disable admin user type selection
                const currentUserType = '<?php echo $userType; ?>';
                if (currentUserType === 'admin' && userTable === 'admins') {
                    alert('Admin users can only edit operators and validators.');
                    return;
                }
                
                // Show the modal first
                const editModal = new bootstrap.Modal(document.getElementById('editUserModal'));
                editModal.show();
                
                // Wait for modal to be fully shown, then populate the form
                document.getElementById('editUserModal').addEventListener('shown.bs.modal', function populateForm() {
                    // Populate the edit modal
                    document.getElementById('editUserId').value = user.id;
                    document.getElementById('editUserTable').value = userTable;
                    
                    // Set the user type dropdown
                    const userTypeSelect = document.getElementById('editUserType');
                    userTypeSelect.value = userType;
                    
                    document.getElementById('editName').value = user.name;
                    document.getElementById('editEmail').value = user.email;
                    document.getElementById('editPhone').value = user.phone || '';
                    document.getElementById('editStatus').value = user.status;
                    document.getElementById('editPassword').value = '';
                    document.getElementById('editConfirmPassword').value = '';
                    
                    // Remove the event listener to prevent multiple executions
                    document.getElementById('editUserModal').removeEventListener('shown.bs.modal', populateForm);
                }, { once: true });
                
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error fetching user data:', error);
            alert('An error occurred while fetching user data.');
        });
}

function viewUser(userId, userTable) {
    // For admin users, prevent viewing admin users
    const currentUserType = '<?php echo $userType; ?>';
    if (currentUserType === 'admin' && userTable === 'admins') {
        alert('Admin users can only view operators and validators.');
        return;
    }
    
    // Fetch user data and populate the view modal
    fetch(`get_user.php?id=${userId}&table=${userTable}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const user = data.user;
                
                // Populate the view modal
                document.getElementById('viewUserName').textContent = user.name;
                document.getElementById('viewUserEmail').textContent = user.email;
                document.getElementById('viewUserPhone').textContent = user.phone || '-';
                document.getElementById('viewUserType').textContent = userTable.replace('s', '').charAt(0).toUpperCase() + userTable.replace('s', '').slice(1);
                document.getElementById('viewUserStatus').innerHTML = getStatusBadgeHTML(user.status);
                document.getElementById('viewUserCreated').textContent = new Date(user.created_at).toLocaleString();
                
                // Store user data for edit from view
                document.getElementById('editFromViewBtn').setAttribute('data-user-id', userId);
                document.getElementById('editFromViewBtn').setAttribute('data-user-table', userTable);
                
                // Show the modal
                const viewModal = new bootstrap.Modal(document.getElementById('viewUserModal'));
                viewModal.show();
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error fetching user data:', error);
            alert('An error occurred while fetching user data.');
        });
}

// Helper function to create status badge HTML
function getStatusBadgeHTML(status) {
    const badges = {
        'active': 'success',
        'inactive': 'danger',
        'pending': 'warning',
        'pending_approval': 'warning'
    };
    
    const badgeClass = badges[status] || 'secondary';
    const displayStatus = status.charAt(0).toUpperCase() + status.slice(1).replace('_', ' ');
    
    return `<span class="badge bg-${badgeClass}">${displayStatus}</span>`;
}

function deleteUser(userId, userTable) {
    // Get user info from the table row
    const row = event.target.closest('tr');
    const userName = row.cells[0].textContent;
    const userEmail = row.cells[1].textContent;
    const userType = row.cells[2].querySelector('.badge').textContent;
    
    // For admin users, prevent deletion of admin users
    const currentUserType = '<?php echo $userType; ?>';
    if (currentUserType === 'admin' && userTable === 'admins') {
        alert('Admin users can only delete operators and validators.');
        return;
    }
    
    // Populate delete confirmation modal
    document.getElementById('deleteUserName').textContent = userName;
    document.getElementById('deleteUserEmail').textContent = userEmail;
    document.getElementById('deleteUserType').textContent = userType;
    
    // Store user data for deletion
    document.getElementById('confirmDeleteBtn').setAttribute('data-user-id', userId);
    document.getElementById('confirmDeleteBtn').setAttribute('data-user-table', userTable);
    
    // Show the modal
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteUserModal'));
    deleteModal.show();
}

// Handle delete confirmation
document.addEventListener('DOMContentLoaded', function() {
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    if (confirmDeleteBtn) {
        confirmDeleteBtn.addEventListener('click', function() {
            const userId = this.getAttribute('data-user-id');
            const userTable = this.getAttribute('data-user-table');
            
            // Create form data for deletion
            const formData = new FormData();
            formData.append('csrf_token', document.querySelector('input[name="csrf_token"]').value);
            formData.append('user_id', userId);
            formData.append('user_table', userTable);
            
            // Send delete request
            fetch('delete_user.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Delete error:', error);
                alert('An error occurred while deleting the user.');
            });
            
            // Close the modal
            const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteUserModal'));
            deleteModal.hide();
        });
    }
    
    // Handle edit from view button
    const editFromViewBtn = document.getElementById('editFromViewBtn');
    if (editFromViewBtn) {
        editFromViewBtn.addEventListener('click', function() {
            const userId = this.getAttribute('data-user-id');
            const userTable = this.getAttribute('data-user-table');
            
            // Close view modal
            const viewModal = bootstrap.Modal.getInstance(document.getElementById('viewUserModal'));
            viewModal.hide();
            
            // Open edit modal
            editUser(userId, userTable);
        });
    }
    
    // Search and Filter Functions
    function initializeSearchAndFilter() {
        const searchAll = document.getElementById('searchAll');
        const filterUserType = document.getElementById('filterUserType');
        const clearSearchBtn = document.getElementById('clearSearchBtn');
        const searchResultsInfo = document.getElementById('searchResultsInfo');
        const totalUsersCount = document.getElementById('totalUsersCount');
        
        if (!searchAll || !filterUserType) {
            return; // Elements not found, skip initialization
        }
        
        // Update total users count on page load
        updateTotalUsersCount();
        
        // Add event listeners for search inputs
        searchAll.addEventListener('input', performSearch);
        filterUserType.addEventListener('change', performSearch);
        
        // Clear search button
        clearSearchBtn.addEventListener('click', clearSearch);
        
        // Debounce search to improve performance
        let searchTimeout;
        function debouncedSearch() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(performSearch, 300);
        }
        
        // Add debounced search to main search input
        searchAll.addEventListener('input', debouncedSearch);
    }
    
    function performSearch() {
        const searchAll = document.getElementById('searchAll').value.toLowerCase();
        const filterUserType = document.getElementById('filterUserType').value;
        
        const userRows = document.querySelectorAll('.user-row');
        let visibleCount = 0;
        let totalCount = userRows.length;
        
        userRows.forEach(row => {
            const name = row.getAttribute('data-name') || '';
            const email = row.getAttribute('data-email') || '';
            const phone = row.getAttribute('data-phone') || '';
            const type = row.getAttribute('data-type') || '';
            
            // Check if row matches search criteria
            const searchMatch = !searchAll || 
                               name.includes(searchAll) || 
                               email.includes(searchAll) || 
                               phone.includes(searchAll);
            const typeMatch = !filterUserType || type === filterUserType;
            
            // Show/hide row based on all criteria
            if (searchMatch && typeMatch) {
                row.style.display = '';
                visibleCount++;
            } else {
                row.style.display = 'none';
            }
        });
        
        // Update search results info
        updateSearchResultsInfo(visibleCount, totalCount);
        
        // Show/hide "no results" message
        const noResultsRow = document.querySelector('.no-results-row');
        if (noResultsRow) {
            noResultsRow.remove();
        }
        
        if (visibleCount === 0 && (searchAll || filterUserType)) {
            showNoResultsMessage();
        }
    }
    
    function clearSearch() {
        document.getElementById('searchAll').value = '';
        document.getElementById('filterUserType').value = '';
        
        // Show all rows
        const userRows = document.querySelectorAll('.user-row');
        userRows.forEach(row => {
            row.style.display = '';
        });
        
        // Remove no results message
        const noResultsRow = document.querySelector('.no-results-row');
        if (noResultsRow) {
            noResultsRow.remove();
        }
        
        // Update display
        updateSearchResultsInfo(userRows.length, userRows.length);
    }
    
    function updateSearchResultsInfo(visibleCount, totalCount) {
        const searchResultsInfo = document.getElementById('searchResultsInfo');
        const totalUsersCount = document.getElementById('totalUsersCount');
        
        if (searchResultsInfo) {
            if (visibleCount === totalCount) {
                searchResultsInfo.textContent = '';
            } else {
                searchResultsInfo.textContent = `Showing ${visibleCount} of ${totalCount} users`;
            }
        }
        
        if (totalUsersCount) {
            totalUsersCount.textContent = visibleCount;
        }
    }
    
    function showNoResultsMessage() {
        const tbody = document.getElementById('usersTableBody');
        if (!tbody) return;
        
        const noResultsRow = document.createElement('tr');
        noResultsRow.className = 'no-results-row';
        noResultsRow.innerHTML = `
            <td colspan="7" class="text-center text-muted py-4">
                <i class="fas fa-search fa-2x mb-3"></i>
                <p class="mb-0">No users found matching your search criteria.</p>
                <small>Try adjusting your search terms or filters.</small>
            </td>
        `;
        
        tbody.appendChild(noResultsRow);
    }
    
    function updateTotalUsersCount() {
        const userRows = document.querySelectorAll('.user-row');
        const totalUsersCount = document.getElementById('totalUsersCount');
        
        if (totalUsersCount) {
            totalUsersCount.textContent = userRows.length;
        }
    }
    
    // Initialize search and filter functionality
    initializeSearchAndFilter();
});
</script>

<?php require_once '../includes/footer.php'; ?>