<?php
    $customers = isset($customers) && is_array($customers) ? $customers : [];
    $warnedCount = count($customers);
    $totalWarnings = 0;
    $needsEscalation = 0;
    $avgWarnings = 0;

    if ($warnedCount > 0) {
        foreach ($customers as $customer) {
            $count = isset($customer['warningCount']) ? (int)$customer['warningCount'] : 0;
            $totalWarnings += $count;
            if ($count >= 3) {
                $needsEscalation++;
            }
        }
        $avgWarnings = $totalWarnings / $warnedCount;
    }
?>

<style>
    .warned-hero {
        background: linear-gradient(120deg, #f97316, #ea580c);
        border-radius: 24px;
        padding: 32px;
        color: #fff;
        margin-bottom: 28px;
        position: relative;
        overflow: hidden;
        box-shadow: 0 25px 50px -12px rgba(234, 88, 12, 0.35);
    }
    .warned-hero::after {
        content: "";
        position: absolute;
        inset: 0;
        background: radial-gradient(circle at top right, rgba(255,255,255,0.4), transparent 55%);
        opacity: 0.5;
    }
    .warned-hero h1 {
        font-size: 1.85rem;
        font-weight: 700;
    }
    .warned-hero p {
        margin: 6px 0 16px;
        opacity: 0.9;
    }
    .warned-metrics .card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 12px 32px rgba(15, 23, 42, 0.08);
        transition: transform 0.25s ease;
    }
    .warned-metrics .card:hover {
        transform: translateY(-4px);
    }
    .warned-metrics .metric-label {
        font-size: 0.85rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #fbbf24;
    }
    .warned-metrics .metric-value {
        font-size: 1.8rem;
        font-weight: 700;
        color: #0f172a;
    }
    .filter-card {
        border: none;
        border-radius: 16px;
        padding: 20px;
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.06);
        margin-bottom: 28px;
    }
    .filter-card .form-control {
        border-radius: 14px;
        padding: 12px 14px;
        border-color: #e2e8f0;
    }
    .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="warned-hero">
        <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between position-relative">
            <div>
                <h1>Warned Customers</h1>
                <p>Review customers who have received policy warnings, prioritize escalations, and keep the platform safe.</p>
                <span class="badge bg-white text-warning fw-semibold px-4 py-2">
                    <i class="bi bi-exclamation-triangle me-2"></i><?php echo number_format($warnedCount); ?> warned 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-warning fw-semibold px-4 py-2">
                    <i class="bi bi-plus-circle me-2"></i>Add Customer
                </a>
            </div>
        </div>
    </section>

    <section class="warned-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 warnings</div>
                        <div class="metric-value text-warning"><?php echo number_format($totalWarnings); ?></div>
                        <div class="text-muted">Across these accounts</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Escalations</div>
                        <div class="metric-value text-danger"><?php echo number_format($needsEscalation); ?></div>
                        <div class="text-muted">3+ warnings</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Avg warnings</div>
                        <div class="metric-value text-warning"><?php echo number_format($avgWarnings, 1); ?></div>
                        <div class="text-muted">Per warned user</div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="metric-label">Action rate</div>
                        <div class="metric-value text-success">
                            <?php echo $warnedCount > 0 ? number_format(($needsEscalation / $warnedCount) * 100, 0) . '%' : '0%'; ?>
                        </div>
                        <div class="text-muted">Need suspension</div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="filter-card bg-white">
        <form action="<?php echo base_url(); ?>customer/warned" 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 warned users</label>
                <div class="input-group">
                    <span class="input-group-text bg-white border-end-0">
                        <i class="bi bi-search text-warning"></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/warned" 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" href="<?php echo base_url(); ?>customer/active">Active Users</a>
      </li>
      <li class="nav-item" role="presentation">
        <a class="nav-link active" 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'] ?? 'warning');

                      $statusClass = 'status-warn';
                      $statusText = $status === 'warning' ? 'Warning' : 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><span class="badge bg-warning text-dark"><?php echo $warningCount; ?> warning<?php echo $warningCount != 1 ? 's' : ''; ?></span></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($status !== 'suspend' && $status !== 'suspended') { ?>
                  <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 } ?>
                </td>
              </tr>
              <?php
                  }
              } else {
              ?>
              <tr>
                <td colspan="9" class="text-center">No warned 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 Another Warning?',
            html: 'Current warnings: <strong>' + currentWarnings + '</strong><br><br>This customer already has warnings. Add another one?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            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: 'Warning Added!',
                                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') || 'warning').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 access in Firebase Auth<br>• Set status to active<br>• Reset warning count to 0'
            : 'This will:<br>• Disable access in Firebase Auth<br>• Set status to suspend<br><br>Use this if the warnings require escalated action.';
        
        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'
                        });
                    }
                });
            }
        });
    });
});
</script>

