<?php
    $customers = isset($customers) && is_array($customers) ? $customers : [];
    $totalCustomers = count($customers);
    $statusCounters = [
        'active'   => 0,
        'warning'   => 0,
        'suspend'  => 0,
        'other'    => 0,
    ];
    $warningTotal = 0;
    $avgCoins = 0;

    if ($totalCustomers > 0) {
        foreach ($customers as $customer) {
            $status = strtolower($customer['status'] ?? 'active');
            if (isset($statusCounters[$status])) {
                $statusCounters[$status]++;
            } elseif ($status === 'suspended') {
                $statusCounters['suspend']++;
            } else {
                $statusCounters['other']++;
            }
            $warningTotal += isset($customer['warningCount']) ? (int)$customer['warningCount'] : 0;
            $avgCoins += isset($customer['userCoins']) ? (int)$customer['userCoins'] : 0;
        }
        $avgCoins = $avgCoins / $totalCustomers;
    }
?>

<style>
    .customers-hero {
        background: linear-gradient(120deg, #2563eb, #7c3aed);
        border-radius: 24px;
        padding: 32px 36px;
        color: #ffffff;
        box-shadow: 0 25px 50px -12px rgba(79, 70, 229, 0.35);
        margin-bottom: 28px;
        position: relative;
        overflow: hidden;
    }
    .customers-hero::after {
        content: "";
        position: absolute;
        inset: 0;
        background: radial-gradient(circle at top right, rgba(255,255,255,0.45), transparent 55%);
        opacity: 0.5;
        z-index: 0;
        pointer-events: none;
    }
    .customers-hero > * {
        position: relative;
        z-index: 1;
    }
    .customers-hero h1 {
        font-size: 1.9rem;
        font-weight: 700;
        margin-bottom: 6px;
    }
    .customers-hero p {
        margin: 0;
        opacity: 0.85;
        max-width: 600px;
    }
    .customers-hero .hero-stat {
        display: inline-flex;
        align-items: center;
        gap: 10px;
        background: rgba(255,255,255,0.18);
        padding: 10px 16px;
        border-radius: 999px;
        font-weight: 600;
        margin-top: 18px;
    }
    .customers-metrics .card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 15px 35px rgba(15, 23, 42, 0.08);
        transition: transform 0.25s ease, box-shadow 0.25s ease;
    }
    .customers-metrics .card:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 40px rgba(15, 23, 42, 0.15);
    }
    .customers-metrics .metric-label {
        font-size: 0.85rem;
        text-transform: uppercase;
        letter-spacing: 0.06em;
        color: #94a3b8;
    }
    .customers-metrics .metric-value {
        font-size: 1.9rem;
        font-weight: 700;
        color: #0f172a;
    }
    .filter-card {
        border: none;
        border-radius: 18px;
        padding: 20px;
        box-shadow: 0 12px 30px rgba(15, 23, 42, 0.05);
        margin-bottom: 28px;
    }
    .filter-card .form-control {
        border-radius: 14px;
        padding: 12px 16px;
        border-color: #e2e8f0;
    }
    .filter-card .btn-primary {
        border-radius: 14px;
        padding: 10px 22px;
    }
    .table-card {
        border: none;
        border-radius: 20px;
        box-shadow: 0 16px 38px rgba(15, 23, 42, 0.08);
    }
    .table thead th {
        text-transform: uppercase;
        letter-spacing: 0.05em;
        font-size: 0.75rem;
        background: #f8fafc;
        border-bottom: 1px solid #e2e8f0;
        color: #475569;
    }
    .status-pill {
        display: inline-flex;
        align-items: center;
        padding: 6px 14px;
        border-radius: 999px;
        font-weight: 600;
        font-size: 0.8rem;
    }
    .status-pill.status-proceed {
        background: rgba(34, 197, 94, 0.15);
        color: #15803d;
    }
    .status-pill.status-warn {
        background: rgba(251, 191, 36, 0.2);
        color: #b45309;
    }
    .status-pill.status-reject {
        background: rgba(248, 113, 113, 0.2);
        color: #b91c1c;
    }
    @media (max-width: 767.98px) {
        .customers-hero {
            padding: 24px;
        }
        .customers-hero h1 {
            font-size: 1.5rem;
        }
        .customers-metrics .metric-value {
            font-size: 1.5rem;
        }
    }
</style>

<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content">
    <section class="customers-hero">
        <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between position-relative">
            <div>
                <h1>Users Directory</h1>
                <p>Track every member across the platform, monitor warnings, and respond quickly to risk signals.</p>
                <div class="hero-stat">
                    <i class="bi bi-people-fill"></i>
                    <?php echo number_format($totalCustomers); ?> total accounts
                </div>
            </div>
            <div class="mt-4 mt-lg-0 text-lg-end">
                <a href="<?php echo base_url(); ?>customer/addCustomer" class="btn btn-light text-primary fw-semibold px-4 py-2">
                    <i class="bi bi-plus-circle me-2"></i>Add New User
                </a>
            </div>
        </div>
    </section>

    <section class="customers-metrics mb-4">
        <div class="row g-3">
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Active</div>
                        <div class="metric-value text-success"><?php echo number_format($statusCounters['active']); ?></div>
                        <div class="text-muted">Currently verified & approved</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Warned</div>
                        <div class="metric-value text-warning"><?php echo number_format($statusCounters['warning']); ?></div>
                        <div class="text-muted">Require follow up</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Suspended</div>
                        <div class="metric-value text-danger"><?php echo number_format($statusCounters['suspend']); ?></div>
                        <div class="text-muted">Locked out of access</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Avg. Coins</div>
                        <div class="metric-value text-primary"><?php echo number_format($avgCoins, 0); ?></div>
                        <div class="text-muted">Per customer balance</div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="filter-card bg-white">
        <form action="<?php echo base_url(); ?>customer/customers" method="post" class="row g-3 align-items-center">
            <div class="col-md-8">
                <label for="searchText" class="form-label fw-semibold text-muted">Search customer</label>
                <div class="input-group">
                    <span class="input-group-text bg-white border-end-0">
                        <i class="bi bi-search text-primary"></i>
                    </span>
                    <input type="text"
                           id="searchText"
                           class="form-control border-start-0"
                           name="searchText"
                           placeholder="Name, email, username or phone..."
                           value="<?php echo !empty($searchText) ? $searchText : ''; ?>">
                </div>
            </div>
            <div class="col-md-4 d-flex gap-2 justify-content-md-end pt-3 pt-md-4">
                <button type="submit" class="btn btn-primary px-4">Search</button>
                <?php if(!empty($searchText)) { ?>
                    <a href="<?php echo base_url(); ?>customer/customers" class="btn btn-outline-secondary px-4">Clear</a>
                <?php } ?>
            </div>
        </form>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs custom-tabs" id="customerTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <a class="nav-link active" 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" 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 table-card">
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover mb-0 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'] ?? 'active');

                      $statusClass = 'status-proceed';
                      $statusText = 'Active';
                      if ($status === 'warning') {
                          $statusClass = 'status-warn';
                          $statusText = 'Warning';
                      } elseif ($status === 'suspend' || $status === 'suspended') {
                          $statusClass = 'status-reject';
                          $statusText = 'Suspended';
                      } elseif ($status !== 'active') {
                          $statusClass = 'status-proceed';
                          $statusText = ucwords($status);
                      }

                      $isActiveStatus = !in_array($status, ['suspend', 'suspended'], true);
              ?>
              <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>
                  <span class="status-pill <?php echo $statusClass; ?>">
                    <span class="status-dot me-1"></span><?php echo $statusText; ?>
                  </span>
                </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-warning addWarningBtn d-none" data-customerid="<?php echo $customerId; ?>" data-email="<?php echo htmlspecialchars($email); ?>" data-warnings="<?php echo $warningCount; ?>" title="Add Warning">
                    <i class="bi bi-exclamation-triangle"></i>
                  </button>
                  <?php if($isActiveStatus) { ?>
                  <button class="btn btn-sm btn-danger toggleSuspendBtn" data-customerid="<?php echo $customerId; ?>" data-email="<?php echo htmlspecialchars($email); ?>" data-status="<?php echo htmlspecialchars($status); ?>" data-active="true" title="Suspend">
                    <i class="bi bi-ban"></i>
                  </button>
                  <?php } else { ?>
                  <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>
                  </button>
                  <?php } ?>
                  <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 customers found</td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script type="text/javascript">
$(document).ready(function() {
    $('.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',
            customClass: {
                confirmButton: 'btn btn-danger',
                cancelButton: 'btn btn-secondary'
            }
        }).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 from Auth and Firestore',
                                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'
                        });
                    }
                });
            }
        });
    });

    $('.addWarningBtn').click(function(e) {
        e.preventDefault();
        var customerId = $(this).data('customerid');
        var email = $(this).data('email');
        var currentWarnings = $(this).data('warnings');
        
        Swal.fire({
            title: 'Add Warning',
            html: 'Current warnings: <strong>' + currentWarnings + '</strong><br><br>Are you sure you want to add another warning?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ffc107',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bi bi-exclamation-triangle"></i> Add Warning',
            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/addWarning',
                    type: 'POST',
                    data: { 
                        customerId: customerId,
                        email: email,
                        currentWarnings: currentWarnings
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Success!',
                                text: 'Warning added 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: 'Warning addition failed',
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            title: 'Error',
                            text: 'Error occurred while adding warning',
                            icon: 'error',
                            confirmButtonColor: '#dc3545'
                        });
                    }
                });
            }
        });
    });

    $('.toggleSuspendBtn').click(function(e) {
        e.preventDefault();
        var customerId = $(this).data('customerid');
        var email = $(this).data('email');
        var status = ($(this).data('status') || 'active').toString().toLowerCase();
        var isSuspended = status === 'suspend' || status === 'suspended';
        var action = isSuspended ? 'activate' : 'suspend';
        var title = isSuspended ? 'Activate Customer?' : 'Suspend Customer?';
        var icon = isSuspended ? 'question' : 'warning';
        var confirmColor = isSuspended ? '#198754' : '#dc3545';
        var confirmText = isSuspended ? '<i class="bi bi-check-circle"></i> Activate' : '<i class="bi bi-ban"></i> Suspend';
        var actionText = isSuspended ?
            'This will:<br>• Set status = active in Firestore<br>• Enable user in Firebase Auth<br>• Reset warning count to 0<br><br>The user will be able to login again.' :
            'This will:<br>• Set status = suspend in Firestore<br>• Disable user in Firebase Auth<br><br>The user will be blocked immediately.';
        
        Swal.fire({
            title: title,
            html: actionText,
            icon: icon,
            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 || 'Customer ' + action + 'd 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'
                        });
                    }
                });
            }
        });
    });
});
</script>

