<?php
/**
 * ============================================================================
 * admin/admins.php - Admin Users & Roles Management
 * Manage admin users and assign roles
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Check permission
if (!hasAdminPermission('manage_users') && !hasAdminPermission('manage_roles')) {
    setFlashMessage('You do not have permission to manage admin users.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [
    ['title' => 'Admin Users', 'url' => '']
];

// Fetch admin users
try {
    $sql = "SELECT 
                u.id,
                u.full_name,
                u.phone_number,
                u.email,
                u.user_type,
                u.is_active,
                u.last_login,
                u.created_at,
                ar.id as role_id,
                ar.role_name,
                ar.role_level
            FROM users u
            LEFT JOIN admin_roles ar ON u.admin_role_id = ar.id
            WHERE u.user_type IN ('admin', 'super_admin')
            ORDER BY ar.role_level DESC, u.full_name";
    
    $stmt = $db->query($sql);
    $adminUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get all roles
    $sql = "SELECT * FROM admin_roles WHERE is_active = 1 ORDER BY role_level DESC";
    $stmt = $db->query($sql);
    $roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    logError('Admin users fetch error: ' . $e->getMessage());
    $adminUsers = [];
    $roles = [];
}

renderAdminHeader('Admin Users Management', $breadcrumbs);
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Admin Users</h2>
        <p class="text-muted mb-0">Manage administrative users and assign roles</p>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addAdminModal">
        <i class="bi bi-person-plus me-2"></i>Add New Admin
    </button>
</div>

<!-- Statistics -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Total Admins</p>
                        <h3 class="mb-0 fw-bold"><?php echo count($adminUsers); ?></h3>
                    </div>
                    <div class="text-primary" style="font-size: 2rem;">
                        <i class="bi bi-shield-check"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Active Roles</p>
                        <h3 class="mb-0 fw-bold"><?php echo count($roles); ?></h3>
                    </div>
                    <div class="text-success" style="font-size: 2rem;">
                        <i class="bi bi-key"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Online Today</p>
                        <h3 class="mb-0 fw-bold">
                            <?php 
                            $onlineToday = array_filter($adminUsers, function($admin) {
                                return $admin['last_login'] && 
                                       strtotime($admin['last_login']) >= strtotime('today');
                            });
                            echo count($onlineToday);
                            ?>
                        </h3>
                    </div>
                    <div class="text-info" style="font-size: 2rem;">
                        <i class="bi bi-activity"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <a href="<?php echo APP_URL; ?>/admin/roles.php" class="text-decoration-none text-dark">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Manage Roles</p>
                            <p class="mb-0 fw-semibold">View & Edit <i class="bi bi-arrow-right"></i></p>
                        </div>
                        <div class="text-warning" style="font-size: 2rem;">
                            <i class="bi bi-gear"></i>
                        </div>
                    </div>
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Admin Users Table -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-people me-2"></i>All Admin Users
        </h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0" id="adminsTable">
                <thead class="table-light">
                    <tr>
                        <th>Admin</th>
                        <th>Role</th>
                        <th>Contact</th>
                        <th>Status</th>
                        <th>Last Login</th>
                        <th>Joined</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($adminUsers as $admin): ?>
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <img src="<?php echo getAvatarUrl($admin['id']); ?>" 
                                     class="rounded-circle me-3" width="40" height="40">
                                <div>
                                    <div class="fw-semibold"><?php echo htmlspecialchars($admin['full_name']); ?></div>
                                    <small class="text-muted">ID: <?php echo $admin['id']; ?></small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <?php if ($admin['role_name']): ?>
                                <span class="badge" style="background: <?php 
                                    echo $admin['role_level'] >= 10 ? '#dc2626' : 
                                         ($admin['role_level'] >= 8 ? '#f59e0b' : 
                                         ($admin['role_level'] >= 5 ? '#3b82f6' : '#6b7280'));
                                ?>">
                                    <?php echo htmlspecialchars($admin['role_name']); ?>
                                    <small>(Level <?php echo $admin['role_level']; ?>)</small>
                                </span>
                            <?php else: ?>
                                <span class="badge bg-secondary">No Role</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="small">
                                <i class="bi bi-phone me-1"></i><?php echo htmlspecialchars($admin['phone_number']); ?><br>
                                <?php if ($admin['email']): ?>
                                    <i class="bi bi-envelope me-1"></i><?php echo htmlspecialchars($admin['email']); ?>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <?php if ($admin['is_active']): ?>
                                <span class="badge bg-success">Active</span>
                            <?php else: ?>
                                <span class="badge bg-danger">Inactive</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($admin['last_login']): ?>
                                <small class="text-muted"><?php echo timeAgo($admin['last_login']); ?></small>
                            <?php else: ?>
                                <small class="text-muted">Never</small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <small class="text-muted"><?php echo formatDate($admin['created_at']); ?></small>
                        </td>
                        <td class="text-end">
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-primary" 
                                        onclick="editAdmin(<?php echo $admin['id']; ?>)" 
                                        title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-outline-info" 
                                        onclick="viewPermissions(<?php echo $admin['id']; ?>)" 
                                        title="View Permissions">
                                    <i class="bi bi-key"></i>
                                </button>
                                <?php if ($admin['id'] != $currentUserId): ?>
                                <button class="btn btn-outline-danger" 
                                        onclick="toggleStatus(<?php echo $admin['id']; ?>, <?php echo $admin['is_active']; ?>)" 
                                        title="<?php echo $admin['is_active'] ? 'Deactivate' : 'Activate'; ?>">
                                    <i class="bi bi-<?php echo $admin['is_active'] ? 'x-circle' : 'check-circle'; ?>"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Admin Modal -->
<div class="modal fade" id="addAdminModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-person-plus me-2"></i>Add New Admin User
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addAdminForm">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle me-2"></i>
                        <strong>Note:</strong> Admin users will have access to the admin panel based on their assigned role.
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Full Name *</label>
                            <input type="text" class="form-control" name="full_name" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Phone Number *</label>
                            <input type="tel" class="form-control" name="phone_number" required 
                                   placeholder="0700000000">
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Email (Optional)</label>
                        <input type="email" class="form-control" name="email">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Assign Role *</label>
                        <select class="form-select" name="admin_role_id" required>
                            <option value="">Choose a role...</option>
                            <?php foreach ($roles as $role): ?>
                                <option value="<?php echo $role['id']; ?>">
                                    <?php echo htmlspecialchars($role['role_name']); ?> 
                                    (Level <?php echo $role['role_level']; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted">Role determines what permissions this admin will have</small>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Password *</label>
                            <input type="password" class="form-control" name="password" required minlength="6">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Confirm Password *</label>
                            <input type="password" class="form-control" name="confirm_password" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Location (Optional)</label>
                        <div class="row">
                            <div class="col-md-6 mb-2">
                                <select class="form-select" name="region_id" id="region">
                                    <option value="">Select Region...</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-2">
                                <select class="form-select" name="district_id" id="district" disabled>
                                    <option value="">Select District...</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-2"></i>Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check-circle me-2"></i>Create Admin User
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Admin Modal -->
<div class="modal fade" id="editAdminModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-pencil me-2"></i>Edit Admin User
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editAdminForm">
                <input type="hidden" name="admin_id" id="edit_admin_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Full Name</label>
                        <input type="text" class="form-control" name="full_name" id="edit_full_name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email" id="edit_email">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Role</label>
                        <select class="form-select" name="admin_role_id" id="edit_role_id" required>
                            <?php foreach ($roles as $role): ?>
                                <option value="<?php echo $role['id']; ?>">
                                    <?php echo htmlspecialchars($role['role_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </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">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Permissions Modal -->
<div class="modal fade" id="permissionsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-key me-2"></i>Admin Permissions
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="permissionsContent">
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize DataTable
    $('#adminsTable').DataTable({
        pageLength: 25,
        order: [[5, 'desc']],
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search admins..."
        }
    });
    
    // Load regions for location select
    loadRegions();
    
    // Region change handler
    $('#region').change(function() {
        const regionId = $(this).val();
        $('#district').prop('disabled', !regionId).html('<option value="">Select District...</option>');
        
        if (regionId) {
            $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + regionId, function(response) {
                if (response.success) {
                    response.data.forEach(district => {
                        $('#district').append(`<option value="${district.id}">${district.district_name}</option>`);
                    });
                }
            });
        }
    });
});

function loadRegions() {
    $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            response.data.forEach(region => {
                $('#region').append(`<option value="${region.id}">${region.region_name}</option>`);
            });
        }
    });
}

// Add admin form submission
$('#addAdminForm').submit(function(e) {
    e.preventDefault();
    
    const password = $('input[name="password"]').val();
    const confirmPassword = $('input[name="confirm_password"]').val();
    
    if (password !== confirmPassword) {
        showToast('Passwords do not match', 'error');
        return;
    }
    
    const btn = $(this).find('button[type="submit"]');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Creating...');
    
    $.ajax({
        url: APP_URL + '/api/admin.php',
        method: 'POST',
        data: $(this).serialize() + '&action=add_admin_user',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                showToast(response.message, 'success');
                $('#addAdminModal').modal('hide');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(response.message, 'error');
                btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Create Admin User');
            }
        },
        error: function() {
            showToast('Connection error', 'error');
            btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Create Admin User');
        }
    });
});

function editAdmin(adminId) {
    // Fetch admin details and show edit modal
    $.get(APP_URL + '/api/admin.php?action=get_admin_details&admin_id=' + adminId, function(response) {
        if (response.success) {
            const admin = response.data;
            $('#edit_admin_id').val(admin.id);
            $('#edit_full_name').val(admin.full_name);
            $('#edit_email').val(admin.email);
            $('#edit_role_id').val(admin.admin_role_id);
            $('#editAdminModal').modal('show');
        }
    });
}

// Edit admin form submission
$('#editAdminForm').submit(function(e) {
    e.preventDefault();
    
    const btn = $(this).find('button[type="submit"]');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Saving...');
    
    $.ajax({
        url: APP_URL + '/api/admin.php',
        method: 'POST',
        data: $(this).serialize() + '&action=update_admin_user',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                showToast(response.message, 'success');
                $('#editAdminModal').modal('hide');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(response.message, 'error');
                btn.prop('disabled', false).html('Save Changes');
            }
        },
        error: function() {
            showToast('Connection error', 'error');
            btn.prop('disabled', false).html('Save Changes');
        }
    });
});

function viewPermissions(adminId) {
    $('#permissionsModal').modal('show');
    
    $.get(APP_URL + '/api/admin.php?action=get_admin_permissions&admin_id=' + adminId, function(response) {
        if (response.success) {
            let html = '<div class="list-group">';
            
            // Group by category
            const grouped = {};
            response.data.forEach(perm => {
                if (!grouped[perm.permission_category]) {
                    grouped[perm.permission_category] = [];
                }
                grouped[perm.permission_category].push(perm);
            });
            
            for (const category in grouped) {
                html += `<div class="list-group-item">
                    <h6 class="mb-2 text-uppercase text-muted">${category}</h6>`;
                grouped[category].forEach(perm => {
                    html += `<div class="form-check">
                        <input class="form-check-input" type="checkbox" checked disabled>
                        <label class="form-check-label">
                            <strong>${perm.permission_name}</strong><br>
                            <small class="text-muted">${perm.permission_description}</small>
                        </label>
                    </div>`;
                });
                html += '</div>';
            }
            
            html += '</div>';
            $('#permissionsContent').html(html);
        } else {
            $('#permissionsContent').html('<div class="alert alert-danger">Failed to load permissions</div>');
        }
    });
}

function toggleStatus(adminId, currentStatus) {
    const action = currentStatus ? 'deactivate' : 'activate';
    const newStatus = currentStatus ? 0 : 1;
    
    Swal.fire({
        title: `${action.charAt(0).toUpperCase() + action.slice(1)} Admin?`,
        text: `This will ${action} the admin user's access to the system.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: currentStatus ? '#dc2626' : '#059669',
        cancelButtonColor: '#6b7280',
        confirmButtonText: `Yes, ${action}!`
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.ajax({
                url: APP_URL + '/api/admin.php',
                method: 'POST',
                data: {
                    action: 'toggle_admin_status',
                    admin_id: adminId,
                    is_active: newStatus
                },
                dataType: 'json',
                success: function(response) {
                    hideLoading();
                    if (response.success) {
                        showToast(response.message, 'success');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('Connection error', 'error');
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>