<?php
    $customers = isset($customers) && is_array($customers) ? $customers : [];
    $totalActive = count($customers);
    $warnedActive = 0;
    $avgCoins = 0;
    $highValue = 0;

    if ($totalActive > 0) {
        foreach ($customers as $customer) {
            $warnings = isset($customer['warningCount']) ? (int)$customer['warningCount'] : 0;
            if ($warnings > 0) {
                $warnedActive++;
            }
            $coins = isset($customer['userCoins']) ? (int)$customer['userCoins'] : 0;
            $avgCoins += $coins;
            if ($coins > $highValue) {
                $highValue = $coins;
            }
        }
        $avgCoins = $avgCoins / $totalActive;
    }
?>

<style>
    .active-hero {
        background: linear-gradient(120deg, #0ea5e9, #2563eb);
        border-radius: 24px;
        padding: 32px;
        color: #fff;
        margin-bottom: 28px;
        position: relative;
        overflow: hidden;
        box-shadow: 0 18px 40px rgba(14, 165, 233, 0.35);
    }
    .active-hero::after {
        content: "";
        position: absolute;
        inset: 0;
        background: radial-gradient(circle at top right, rgba(255,255,255,0.4), transparent 55%);
        opacity: 0.6;
    }
    .active-hero h1 {
        font-size: 1.9rem;
        font-weight: 700;
    }
    .active-hero p {
        margin: 8px 0 14px;
        opacity: 0.9;
    }
    .active-hero .badge {
        background: rgba(255,255,255,0.2);
        padding: 8px 14px;
        border-radius: 999px;
        font-weight: 600;
    }
    .active-metrics .card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 12px 30px rgba(15, 23, 42, 0.08);
        transition: transform 0.25s ease;
    }
    .active-metrics .card:hover {
        transform: translateY(-4px);
    }
    .active-metrics .metric-label {
        font-size: 0.85rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #94a3b8;
        margin-bottom: 4px;
    }
    .active-metrics .metric-value {
        font-size: 1.8rem;
        font-weight: 700;
        color: #0f172a;
    }
    .filter-card {
        border: none;
        border-radius: 16px;
        padding: 20px;
        box-shadow: 0 10px 26px rgba(15, 23, 42, 0.05);
        margin-bottom: 28px;
    }
    .filter-card .form-control {
        border-radius: 14px;
        padding: 12px 14px;
        border-color: #e2e8f0;
    }
    .filter-card .btn {
        border-radius: 14px;
        padding: 10px 20px;
    }
    .table-card {
        border: none;
        border-radius: 20px;
        box-shadow: 0 16px 32px rgba(15, 23, 42, 0.08);
    }
</style>

<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content">
    <section class="active-hero">
        <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between position-relative">
            <div>
                <h1>Active Customers</h1>
                <p>These members are verified, approved, and actively engaging with the platform.</p>
                <span class="badge">
                    <i class="bi bi-graph-up-arrow me-2"></i><?php echo number_format($totalActive); ?> active users
                </span>
            </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 Customer
                </a>
            </div>
        </div>
    </section>

    <section class="active-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">Total Active</div>
                        <div class="metric-value text-primary"><?php echo number_format($totalActive); ?></div>
                        <div class="text-muted">Currently approved</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Warned (active)</div>
                        <div class="metric-value text-warning"><?php echo number_format($warnedActive); ?></div>
                        <div class="text-muted">Need attention</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Average Coins</div>
                        <div class="metric-value text-success"><?php echo number_format($avgCoins, 0); ?></div>
                        <div class="text-muted">Per active user</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Top Balance</div>
                        <div class="metric-value text-success"><?php echo number_format($highValue); ?></div>
                        <div class="text-muted">Highest coin holder</div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="filter-card bg-white">
        <form action="<?php echo base_url(); ?>customer/active" method="post" class="row g-3 align-items-end">
            <div class="col-md-8">
                <label for="searchText" class="form-label fw-semibold text-muted">Search active users</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 or username..."
                           value="<?php echo !empty($searchText) ? $searchText : ''; ?>">
                </div>
            </div>
            <div class="col-md-4 d-flex gap-2">
                <button type="submit" class="btn btn-primary px-4 w-100">Search</button>
                <?php if(!empty($searchText)) { ?>
                    <a href="<?php echo base_url(); ?>customer/active" class="btn btn-outline-secondary w-100">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" href="<?php echo base_url(); ?>customer/customers">All Users</a>
      </li>
      <li class="nav-item" role="presentation">
        <a class="nav-link active" 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 align-middle mb-0">
            <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' || $warningCount > 0) {
                          $statusClass = 'status-warn';
                          $statusText = 'Warned (Active)';
                      } elseif ($status !== 'active') {
                          $statusClass = 'status-proceed';
                          $statusText = 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>
                  <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>
                  <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>
                </td>
              </tr>
              <?php
                  }
              } else {
              ?>
              <tr>
                <td colspan="9" class="text-center">No active customers found</td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script type="text/javascript">
$(document).ready(function() {
    $('.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 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 actionText = isSuspended
            ? 'This will:<br>• Enable the user in Firebase Auth<br>• Set their status to active<br>• Reset warning count to 0'
            : 'This will:<br>• Disable the user in Firebase Auth<br>• Set their status to suspend<br>• Block platform access immediately';
        
        Swal.fire({
            title: title,
            html: actionText,
            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'
                        });
                    }
                });
            }
        });
    });
});
</script>
