<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content">
    <div class="row my-2">
      <div class="col-md-6">
        <h4>Edit Admin User</h4>
      </div>
      <div class="col-md-6 text-end">
        <a href="<?= base_url('admin/admins'); ?>" class="btn btn-secondary">
          <i class="bi bi-arrow-left"></i> Back to Admin List
        </a>
      </div>
    </div>

    <?php
    $success = $this->session->flashdata('success');
    $error = $this->session->flashdata('error');
    
    if(!empty($success)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?= $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif;
    
    if(!empty($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?= $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; 
    
    // Load role helper
    $this->load->helper('role');
    $departments = get_department_structure();
    
    // Get current values
    $currentDepartment = isset($adminInfo['department']) ? $adminInfo['department'] : '';
    $currentRoleKey = isset($adminInfo['roleKey']) ? $adminInfo['roleKey'] : (isset($adminInfo['role']) ? $adminInfo['role'] : '');
    $currentRoleInfo = get_role_info($currentRoleKey);
    ?>

    <div class="card">
      <div class="card-body">
        <form action="<?= base_url('admin/updateAdmin'); ?>" method="post" id="editAdminForm">
          <input type="hidden" name="adminId" value="<?= isset($adminId) ? $adminId : ''; ?>">
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label for="fullName" class="form-label">Full Name <span class="text-danger">*</span></label>
              <input type="text" class="form-control" id="fullName" name="fullName" required 
                     value="<?= isset($adminInfo['fullName']) ? htmlspecialchars($adminInfo['fullName']) : ''; ?>">
              <?php if(function_exists('form_error') && form_error('fullName')): ?>
                <span class="text-danger"><?= form_error('fullName'); ?></span>
              <?php endif; ?>
            </div>

            <div class="col-md-6 mb-3">
              <label for="email" class="form-label">Email Address</label>
              <input type="email" class="form-control" id="email" 
                     value="<?= isset($adminInfo['email']) ? htmlspecialchars($adminInfo['email']) : ''; ?>" disabled>
              <small class="text-muted">Email cannot be changed</small>
            </div>

            <div class="col-md-6 mb-3">
              <label for="phone" class="form-label">Phone Number</label>
              <input type="text" class="form-control" id="phone" name="phone" 
                     value="<?= isset($adminInfo['phone']) ? htmlspecialchars($adminInfo['phone']) : ''; ?>">
            </div>

            <div class="col-md-6 mb-3">
              <label for="isActive" class="form-label">Status <span class="text-danger">*</span></label>
              <select class="form-select" id="isActive" name="isActive" required>
                <option value="true" <?= (isset($adminInfo['isActive']) && $adminInfo['isActive'] === true) ? 'selected' : ''; ?>>Active</option>
                <option value="false" <?= (isset($adminInfo['isActive']) && $adminInfo['isActive'] === false) ? 'selected' : ''; ?>>Inactive</option>
              </select>
            </div>

            <div class="col-md-12 mb-3">
              <label for="role" class="form-label">Role <span class="text-danger">*</span></label>
              <select class="form-select" id="role" name="role" required>
                <option value="">Select Role</option>
                <option value="admin" <?= (isset($adminInfo['role']) && $adminInfo['role'] === 'admin') ? 'selected' : ''; ?>>👑 Admin Panel Department</option>
                <option value="content" <?= (isset($adminInfo['role']) && $adminInfo['role'] === 'content') ? 'selected' : ''; ?>>📝 Media Panel Department</option>
                <option value="userdepartment" <?= (isset($adminInfo['role']) && $adminInfo['role'] === 'userdepartment') ? 'selected' : ''; ?>>📱 User Panel Department</option>
                <option value="accountant" <?= (isset($adminInfo['role']) && $adminInfo['role'] === 'accountant') ? 'selected' : ''; ?>>💰 Finance Panel Department</option>
              </select>
              <?php if(function_exists('form_error') && form_error('role')): ?>
                <span class="text-danger"><?= form_error('role'); ?></span>
              <?php endif; ?>
            </div>
          </div>

          <!-- Current Role Information -->
         
          <!-- Password Change Section -->
          <div class="card mt-3">
            <div class="card-header bg-warning text-dark">
              <h6 class="mb-0"><i class="bi bi-lock"></i> Change Password</h6>
            </div>
            <div class="card-body">
              <button type="button" class="btn btn-warning" id="changePasswordBtn" data-adminid="<?= isset($adminId) ? $adminId : ''; ?>">
                <i class="bi bi-key"></i> Change Password
              </button>
              <p class="mt-2 mb-0 text-muted">
                <small>Click to set a new password for this admin user</small>
              </p>
            </div>
          </div>

          <div class="row mt-3">
            <div class="col-md-12">
              <button type="submit" class="btn btn-primary">
                <i class="bi bi-save"></i> Update Admin
              </button>
              <a href="<?= base_url('admin/admins'); ?>" class="btn btn-secondary">
                <i class="bi bi-x-circle"></i> Cancel
              </a>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script>
$(document).ready(function() {
    // Department and role data
    const departmentRoles = <?= json_encode($departments); ?>;
    const currentDepartment = '<?= $currentDepartment ?>';
    const currentRoleKey = '<?= $currentRoleKey ?>';

    // Initialize role dropdown based on current department
    function loadRoles(deptKey, selectedRole) {
        const roleSelect = $('#roleKey');
        roleSelect.html('<option value="">Select Role</option>');
        
        if (deptKey && departmentRoles[deptKey]) {
            const dept = departmentRoles[deptKey];
            const roles = dept.roles;
            
            for (let roleKey in roles) {
                const role = roles[roleKey];
                const selected = roleKey === selectedRole ? 'selected' : '';
                roleSelect.append(`<option value="${roleKey}" ${selected}>${role.title}</option>`);
            }
            
            roleSelect.prop('disabled', false);
            
            // Show current role permissions
            if (selectedRole && roles[selectedRole]) {
                displayPermissions(selectedRole, deptKey);
            }
        } else {
            roleSelect.prop('disabled', true);
        }
    }

    // Display permissions for selected role
    function displayPermissions(roleKey, deptKey) {
        if (departmentRoles[deptKey] && departmentRoles[deptKey].roles[roleKey]) {
            const role = departmentRoles[deptKey].roles[roleKey];
            let html = '<p class="mb-2"><strong>Permissions:</strong></p>';
            
            if (role.permissions && role.permissions.length > 0) {
                role.permissions.forEach(function(perm) {
                    html += `<div class="col-md-4 mb-2">
                        <i class="bi bi-check-circle-fill text-success"></i> ${perm}
                    </div>`;
                });
            } else {
                html += '<p class="text-muted">No specific permissions defined</p>';
            }
            
            $('#permissionsList').html(html);
        }
    }

    // Initialize on page load
    if (currentDepartment) {
        loadRoles(currentDepartment, currentRoleKey);
    }

    // Handle department change
    $('#department').change(function() {
        const deptKey = $(this).val();
        loadRoles(deptKey, '');
        $('#permissionsList').empty();
    });

    // Handle role change
    $('#roleKey').change(function() {
        const roleKey = $(this).val();
        const deptKey = $('#department').val();
        
        if (roleKey && deptKey) {
            displayPermissions(roleKey, deptKey);
            
            if (departmentRoles[deptKey] && departmentRoles[deptKey].roles[roleKey]) {
                const role = departmentRoles[deptKey].roles[roleKey];
                $('#currentRoleDisplay').text('Selected Role: ' + role.title);
            }
        }
    });

    // Change password functionality
    $('#changePasswordBtn').click(function() {
        var adminId = $(this).data('adminid');
        
        Swal.fire({
            title: 'Change Password',
            html: '<input id="swal-input-password" type="password" class="swal2-input" placeholder="New Password" minlength="6"><br>' +
                  '<input id="swal-input-confirm" type="password" class="swal2-input" placeholder="Confirm Password" minlength="6">',
            showCancelButton: true,
            confirmButtonText: '<i class="bi bi-key"></i> Update Password',
            confirmButtonColor: '#ffc107',
            cancelButtonColor: '#6c757d',
            preConfirm: () => {
                const password = document.getElementById('swal-input-password').value;
                const confirm = document.getElementById('swal-input-confirm').value;
                
                if (!password || !confirm) {
                    Swal.showValidationMessage('Please enter both fields');
                    return false;
                }
                
                if (password.length < 6) {
                    Swal.showValidationMessage('Password must be at least 6 characters');
                    return false;
                }
                
                if (password !== confirm) {
                    Swal.showValidationMessage('Passwords do not match');
                    return false;
                }
                
                return password;
            }
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Updating...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?= base_url('admin/updatePassword'); ?>',
                    type: 'POST',
                    data: { 
                        adminId: adminId,
                        newPassword: result.value
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Success!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message,
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    }
                });
            }
        });
    });
});
</script>

