<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content">
    <div class="row my-2">
      <div class="col-md-6">
        <h4>Admin Management</h4>
      </div>
      <div class="col-md-6 text-end">
        <a href="<?php echo base_url(); ?>admin/addAdmin" class="btn btn-primary">
          <i class="bi bi-plus-circle"></i> Add New Admin
        </a>
      </div>
    </div>

    <div class="row my-2">
      <div class="col-md-12">
        <form action="<?php echo base_url(); ?>admin/admins<?php echo isset($filterRole) ? '/byRole/'.$filterRole : ''; ?>" method="post">
          <div class="input-group custom-search">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" class="form-control" name="searchText" placeholder="Search by name, email or role..." 
                   value="<?php echo !empty($searchText) ? $searchText : ''; ?>" aria-label="Search">
            <button type="submit" class="btn btn-primary">Search</button>
            <?php if(!empty($searchText)) { ?>
            <a href="<?php echo base_url(); ?>admin/admins<?php echo isset($filterRole) ? '/byRole/'.$filterRole : ''; ?>" class="btn btn-secondary">Clear</a>
            <?php } ?>
          </div>
        </form>
      </div>
    </div>

    <!-- Department Filter Tabs -->
    <?php $this->load->helper('role'); ?>
    <ul class="nav nav-tabs custom-tabs" id="adminTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <a class="nav-link <?php echo !isset($filterRole) ? 'active' : ''; ?>" href="<?php echo base_url(); ?>admin/admins">
          All Admins
        </a>
      </li>
      <?php 
        $departments = get_department_structure();

        
        foreach ($departments as $deptKey => $dept): 
      ?>
      <li class="nav-item" role="presentation">
        <a class="nav-link" href="<?php echo base_url(); ?>admin/byDepartment/<?php echo $deptKey; ?>">
          <i class="bi bi-<?php echo $dept['icon']; ?> text-<?php echo $dept['color']; ?>"></i> 
          <?php echo $dept['name']; ?>
        </a>
      </li>
      <?php endforeach; ?>
    </ul>

    <?php
    $success = $this->session->flashdata('success');
    $error = $this->session->flashdata('error');
    if($success) {
        echo '<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>';
    }
    if($error) {
        echo '<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>';
    }
    ?>

    <div class="card">
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-bordered align-middle">
            <thead>
              <tr>
                <th>#</th>
                <th>Name</th>
                <th>Email</th>
                <th>Role</th>
                <th>Phone</th>
                <th>Status</th>
                <th>Created</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php
              if(!empty($admins)) {
                  $count = 1;
                  foreach($admins as $adminId => $admin) {
                      $fullName = isset($admin['fullName']) ? $admin['fullName'] : 'N/A';
                      $email = isset($admin['email']) ? $admin['email'] : 'N/A';
                      $roleKey = isset($admin['roleKey']) ? $admin['roleKey'] : (isset($admin['role']) ? $admin['role'] : 'N/A');
                      $phone = isset($admin['phone']) ? $admin['phone'] : 'N/A';
                      $isActive = isset($admin['isActive']) ? $admin['isActive'] : true;
                      $createdDate = isset($admin['createdDate']) ? date('Y-m-d', $admin['createdDate'] / 1000) : 'N/A';
                      
                      // Get role information from helper
                      $roleInfo = get_role_info($roleKey);
                      $roleBadge = 'bg-' . $roleInfo['color'];
                      $roleIcon = $roleInfo['icon'];
                      $roleTitle = $roleInfo['title'];
                      
                      // Status
                      $statusClass = $isActive ? 'status-proceed' : 'status-reject';
                      $statusText = $isActive ? 'Active' : 'Inactive';
              ?>
              <tr>
                <td><?php echo $count++; ?></td>
                <td><?php echo htmlspecialchars($fullName); ?></td>
                <td><?php echo htmlspecialchars($email); ?></td>
                <td>
                  <span class="badge <?php echo $roleBadge; ?>">
                    <i class="bi bi-<?php echo $roleIcon; ?>"></i> <?php echo $roleTitle; ?>
                  </span>
                  <br>

                </td>
                <td><?php echo htmlspecialchars($phone); ?></td>
                <td class="<?php echo $statusClass; ?>">
                  <span class="status-dot"></span><?php echo $statusText; ?>
                </td>
                <td><?php echo $createdDate; ?></td>
                <td>
                  <a href="<?php echo base_url().'admin/viewAdmin/'.$adminId; ?>" class="btn btn-sm btn-info" title="View">
                    <i class="bi bi-eye"></i>
                  </a>
                  <a href="<?php echo base_url().'admin/editAdmin/'.$adminId; ?>" class="btn btn-sm btn-warning" title="Edit">
                    <i class="bi bi-pencil"></i>
                  </a>
                  <?php if($isActive) { ?>
                  <button class="btn btn-sm btn-secondary toggleStatusBtn" data-adminid="<?php echo $adminId; ?>" data-active="true" title="Deactivate">
                    <i class="bi bi-dash-circle"></i>
                  </button>
                  <?php } else { ?>
                  <button class="btn btn-sm btn-success toggleStatusBtn" data-adminid="<?php echo $adminId; ?>" data-active="false" title="Activate">
                    <i class="bi bi-check-circle"></i>
                  </button>
                  <?php } ?>
                  <button class="btn btn-sm btn-danger deleteAdmin" data-adminid="<?php echo $adminId; ?>" data-name="<?php echo htmlspecialchars($fullName); ?>" title="Delete">
                    <i class="bi bi-trash"></i>
                  </button>
                </td>
              </tr>
              <?php
                  }
              } else {
              ?>
              <tr>
                <td colspan="8" class="text-center">No admin users found</td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script type="text/javascript">
$(document).ready(function() {
    $('.deleteAdmin').click(function(e) {
        e.preventDefault();
        var adminId = $(this).data('adminid');
        var adminName = $(this).data('name');
        
        Swal.fire({
            title: 'Delete Admin User?',
            html: '<strong>' + adminName + '</strong><br><br>This will remove the user from:<br>• Firebase Authentication<br>• Firestore Admin Collection<br><br><span style="color: #dc3545;">This action cannot be undone!</span>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bi bi-trash"></i> Yes, Delete',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Deleting...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?php echo base_url(); ?>admin/deleteAdmin',
                    type: 'POST',
                    data: { adminId: adminId },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Deleted!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message || 'Deletion failed',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    }
                });
            }
        });
    });

    $('.toggleStatusBtn').click(function(e) {
        e.preventDefault();
        var adminId = $(this).data('adminid');
        var isActive = $(this).data('active');
        var action = isActive ? 'deactivate' : 'activate';
        var title = isActive ? 'Deactivate Admin?' : 'Activate Admin?';
        var confirmColor = isActive ? '#ffc107' : '#198754';
        
        Swal.fire({
            title: title,
            html: isActive ? 
                'This will disable login access for this admin user.' : 
                'This will enable login access for this admin user.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: confirmColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: action === 'activate' ? '<i class="bi bi-check-circle"></i> Activate' : '<i class="bi bi-dash-circle"></i> Deactivate',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Processing...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?php echo base_url(); ?>admin/toggleStatus',
                    type: 'POST',
                    data: { 
                        adminId: adminId,
                        currentStatus: isActive
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Success!',
                                text: response.message,
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message,
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    }
                });
            }
        });
    });
});
</script>

