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

    <div class="row my-2">
      <div class="col-md-12">
        <form action="<?php echo base_url(); ?>customer/suspended" 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 username..." 
                   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(); ?>customer/suspended" class="btn btn-secondary">Clear</a>
            <?php } ?>
          </div>
        </form>
      </div>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs custom-tabs" id="customerTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <a class="nav-link" href="<?php echo base_url(); ?>customer/customers">All Users</a>
      </li>
      <li class="nav-item" role="presentation">
        <a class="nav-link" href="<?php echo base_url(); ?>customer/active">Active Users</a>
      </li>
      <li class="nav-item" role="presentation">
        <a class="nav-link" href="<?php echo base_url(); ?>customer/warned">Warned Users</a>
      </li>
      <li class="nav-item" role="presentation">
        <a class="nav-link active" href="<?php echo base_url(); ?>customer/suspended">Suspended Users</a>
      </li>
    </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>Username</th>
                <th>Email</th>
                <th>Warnings</th>
                <th>Coins</th>
                <th>Status</th>
                <th>Joined</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php
              if(!empty($customers)) {
                  $count = 1;
                  foreach($customers as $customerId => $customer) {
                      $fullName = isset($customer['fullName']) && $customer['fullName'] !== '' ? $customer['fullName'] : 'N/A';
                      $userName = isset($customer['userName']) && $customer['userName'] !== '' ? $customer['userName'] : 'N/A';
                      $email = isset($customer['email']) && $customer['email'] !== '' ? $customer['email'] : 'N/A';
                      $warningCount = isset($customer['warningCount']) ? (int)$customer['warningCount'] : 0;
                      $userCoins = isset($customer['userCoins']) ? (int)$customer['userCoins'] : 0;
                      $joinDate = isset($customer['createdDate']) ? date('Y-m-d', $customer['createdDate'] / 1000) : 'N/A';
                      $status = strtolower($customer['status'] ?? 'suspend');

                      $statusClass = 'status-reject';
                      $statusText = $status === 'suspend' ? 'Suspended' : ucwords($status);
              ?>
              <tr>
                <td><?php echo $count++; ?></td>
                <td><?php echo htmlspecialchars($fullName); ?></td>
                <td>@<?php echo htmlspecialchars($userName); ?></td>
                <td><?php echo htmlspecialchars($email); ?></td>
                <td><?php echo $warningCount; ?> warning<?php echo $warningCount != 1 ? 's' : ''; ?></td>
                <td><?php echo number_format($userCoins); ?></td>
                <td class="<?php echo $statusClass; ?>">
                  <span class="status-dot"></span><?php echo $statusText; ?>
                </td>
                <td><?php echo $joinDate; ?></td>
                <td>
                  <a href="<?php echo base_url().'customer/viewCustomer/'.$customerId; ?>" class="btn btn-sm btn-info btn-view" title="View">
                    <i class="bi bi-eye"></i>
                  </a>
                  <button class="btn btn-sm btn-success toggleSuspendBtn" data-customerid="<?php echo $customerId; ?>" data-email="<?php echo htmlspecialchars($email); ?>" data-status="<?php echo htmlspecialchars($status); ?>" data-active="false" title="Activate">
                    <i class="bi bi-check-circle"></i> Activate
                  </button>
                  <button class="btn btn-sm btn-dark deleteCustomer" data-customerid="<?php echo $customerId; ?>" data-name="<?php echo htmlspecialchars($fullName); ?>" title="Delete">
                    <i class="bi bi-trash"></i>
                  </button>
                </td>
              </tr>
              <?php
                  }
              } else {
              ?>
              <tr>
                <td colspan="9" class="text-center">No suspended customers found</td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script type="text/javascript">
$(document).ready(function() {
    $('.toggleSuspendBtn').click(function(e) {
        e.preventDefault();
        var customerId = $(this).data('customerid');
        var email = $(this).data('email');
        var status = ($(this).data('status') || 'suspend').toString().toLowerCase();
        var isSuspended = status === 'suspend' || status === 'suspended';
        var title = isSuspended ? 'Activate Customer?' : 'Suspend Customer?';
        var confirmColor = isSuspended ? '#198754' : '#dc3545';
        var confirmText = isSuspended ? '<i class="bi bi-check-circle"></i> Activate' : '<i class="bi bi-ban"></i> Suspend';
        var infoText = isSuspended
            ? 'This will:<br>• Enable the user in Firebase Auth<br>• Set their status to active<br>• Reset warnings to 0'
            : 'This will:<br>• Disable the user in Firebase Auth again<br>• Keep them blocked from logging in.';
        
        Swal.fire({
            title: title,
            html: infoText,
            icon: isSuspended ? 'question' : 'warning',
            showCancelButton: true,
            confirmButtonColor: confirmColor,
            cancelButtonColor: '#6c757d',
            confirmButtonText: confirmText,
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Processing...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?php echo base_url(); ?>customer/toggleSuspend',
                    type: 'POST',
                    data: { 
                        customerId: customerId,
                        email: email,
                        status: status
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Success!',
                                text: response.message || 'Action completed successfully',
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            }).then(() => {
                                location.reload();
                            });
                        } else if(response.status == 'access') {
                            Swal.fire({
                                title: 'Access Denied',
                                text: 'You do not have permission to perform this action',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message || 'Action failed',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            title: 'Error',
                            text: 'Error occurred while performing action',
                            icon: 'error',
                            confirmButtonColor: '#dc3545'
                        });
                    }
                });
            }
        });
    });

    $('.deleteCustomer').click(function(e) {
        e.preventDefault();
        var customerId = $(this).data('customerid');
        var customerName = $(this).data('name');
        
        Swal.fire({
            title: 'Delete Customer?',
            html: '<strong>' + customerName + '</strong><br><br>This will remove the user from:<br>• Firebase Authentication<br>• Firestore Users 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: '<i class="bi bi-x-circle"></i> Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Deleting...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?php echo base_url(); ?>customer/deleteCustomer',
                    type: 'POST',
                    data: { customerId: customerId },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Deleted!',
                                text: response.message || 'Customer deleted successfully',
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            }).then(() => {
                                location.reload();
                            });
                        } else if(response.status == 'access') {
                            Swal.fire({
                                title: 'Access Denied',
                                text: 'You do not have permission to perform this action',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message || 'Customer deletion failed',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            title: 'Error',
                            text: 'Error occurred while deleting customer',
                            icon: 'error',
                            confirmButtonColor: '#dc3545'
                        });
                    }
                });
            }
        });
    });
});
</script>

