<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content">
    <div class="row my-2">
      <div class="col-md-6">
        <h4><i class="bi bi-patch-check-fill text-primary"></i> Blue Tick Requests</h4>
      </div>
      <div class="col-md-6 text-end">
        <a href="<?= base_url('tick/verified'); ?>" class="btn btn-primary">
          <i class="bi bi-patch-check"></i> View Verified Users
        </a>
      </div>
    </div>

    <div class="row my-2">
      <div class="col-md-12">
        <form action="<?= base_url('tick/requests'); ?>" 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, username or email..." 
                   value="<?= !empty($searchText) ? htmlspecialchars($searchText) : ''; ?>" aria-label="Search">
            <button type="submit" class="btn btn-primary">Search</button>
            <?php if(!empty($searchText)): ?>
            <a href="<?= base_url('tick/requests'); ?>" class="btn btn-secondary">Clear</a>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>

    <!-- Tabs -->
    <ul class="nav nav-tabs custom-tabs" id="tickTabs" role="tablist">
      <li class="nav-item" role="presentation">
        <a class="nav-link active" href="<?= base_url('tick/requests'); ?>">
          <i class="bi bi-clock-history"></i> Pending Requests (<?= count($tickRequests); ?>)
        </a>
      </li>
      <li class="nav-item" role="presentation">
        <a class="nav-link" href="<?= base_url('tick/verified'); ?>">
          <i class="bi bi-patch-check-fill"></i> Verified Users
        </a>
      </li>
      <li class="nav-item" role="presentation">
        <a class="nav-link" href="<?= base_url('tick/rejected'); ?>">
          <i class="bi bi-x-circle"></i> Rejected Requests
        </a>
      </li>
    </ul>

    <?php
    $success = $this->session->flashdata('success');
    $error = $this->session->flashdata('error');
    
    if(!empty($success)): ?>
        <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
            <?= $success; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif;
    
    if(!empty($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert">
            <?= $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="row">
      <?php
      if(!empty($tickRequests)) {
          foreach($tickRequests as $userId => $user) {
              $fullName = isset($user['fullName']) ? $user['fullName'] : 'N/A';
              $userName = isset($user['userName']) ? $user['userName'] : 'N/A';
              $email = isset($user['email']) ? $user['email'] : 'N/A';
              $followersCount = isset($user['userFollowers']) ? count($user['userFollowers']) : 0;
              $followingCount = isset($user['userFollowings']) ? count($user['userFollowings']) : 0;
              $userCoins = isset($user['userCoins']) ? $user['userCoins'] : 0;
              $requestDate = isset($user['tickRequestDate']) ? date('M j, Y', $user['tickRequestDate'] / 1000) : 
                            (isset($user['joinDate']) ? date('M j, Y', $user['joinDate'] / 1000) : 'N/A');
      ?>
      <div class="col-md-6 mb-4">
        <div class="report-card">
          <!-- Header -->
          <div class="report-header">
            <i class="bi bi-person-circle"></i> <?= htmlspecialchars($fullName); ?> (@<?= htmlspecialchars($userName); ?>)
          </div>

          <!-- Body -->
          <div class="report-body p-3">
            <div class="d-flex gap-2 align-items-center mb-2">
              <div class="report-label">User:</div>
              <div><?= htmlspecialchars($email); ?></div>
            </div>
            <div class="d-flex gap-2 align-items-center mb-2">
              <div class="report-label">Followers:</div>
              <div><?= number_format($followersCount); ?></div>
            </div>
            <div class="d-flex gap-2 align-items-center mb-2">
              <div class="report-label">Following:</div>
              <div><?= number_format($followingCount); ?></div>
            </div>
            <div class="d-flex gap-2 align-items-center mb-2">
              <div class="report-label">Coins:</div>
              <div><?= number_format($userCoins); ?></div>
            </div>
                            <div class="d-flex gap-2 align-items-center mb-2">
                                <div class="report-label">Status:</div>
                                <div><span class="badge bg-warning">requested</span></div>
                            </div>
            <div class="d-flex gap-2 align-items-center mb-2">
              <div class="report-label">Requested:</div>
              <div><?= $requestDate; ?></div>
            </div>
            
            <div class="row mb-3 mt-3">
              <div class="col-12 report-label">Admin note:</div>
              <div class="col-12 mt-2">
                <textarea class="form-control custom-input admin-note-<?= $userId; ?>" placeholder="Enter note or rejection reason" rows="3"></textarea>
              </div>
            </div>

            <!-- Buttons -->
            <div class="d-flex justify-content-end gap-2">
              <button class="btn btn-success custom-btn approveTick" 
                      data-userid="<?= $userId; ?>" 
                      data-email="<?= htmlspecialchars($email); ?>" 
                      data-name="<?= htmlspecialchars($fullName); ?>">
                <i class="bi bi-check-circle"></i> Approve
              </button>
              <button class="btn btn-danger custom-btn rejectTick" 
                      data-userid="<?= $userId; ?>" 
                      data-email="<?= htmlspecialchars($email); ?>" 
                      data-name="<?= htmlspecialchars($fullName); ?>">
                <i class="bi bi-x-circle"></i> Reject
              </button>
            </div>
          </div>
        </div>
      </div>
      <?php
          }
      } else {
      ?>
      <div class="col-12">
        <div class="card">
          <div class="card-body text-center py-5">
            <i class="bi bi-inbox" style="font-size: 64px; color: #ccc;"></i>
            <h5 class="text-muted mt-3">No Pending Blue Tick Requests</h5>
            <p class="text-muted">When users request verification, they will appear here</p>
          </div>
        </div>
      </div>
      <?php } ?>
    </div>
  </div>
</main>
<!--end main wrapper-->

<script>
$(document).ready(function() {
    // Approve Tick Request
    $('.approveTick').click(function(e) {
        e.preventDefault();
        var userId = $(this).data('userid');
        var email = $(this).data('email');
        var userName = $(this).data('name');
        
        // Get the admin note (optional for approval)
        var note = $('.admin-note-' + userId).val();
        
        Swal.fire({
            title: 'Approve Blue Tick?',
            html: '<div class="text-center"><i class="bi bi-patch-check-fill text-primary" style="font-size: 64px;"></i></div><br>' +
                  '<strong>' + userName + '</strong> will receive a verified badge.<br><br>Are you sure?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#198754',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bi bi-check-circle"></i> Approve',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Processing...',
                    text: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?= base_url('tick/approveRequest'); ?>',
                    type: 'POST',
                    data: { 
                        userId: userId,
                        email: email,
                        note: note
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Approved!',
                                html: '<i class="bi bi-patch-check-fill text-primary" style="font-size: 48px;"></i><br><br>' + response.message,
                                icon: 'success',
                                confirmButtonColor: '#198754'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                title: 'Error',
                                text: response.message,
                                icon: 'error',
                                confirmButtonColor: '#dc3545'
                            });
                        }
                    }
                });
            }
        });
    });

    // Reject Tick Request
    $('.rejectTick').click(function(e) {
        e.preventDefault();
        var userId = $(this).data('userid');
        var email = $(this).data('email');
        var userName = $(this).data('name');
        
        // Get the admin note from the card's textarea
        var reason = $('.admin-note-' + userId).val();
        
        if (!reason || reason.trim() === '') {
            Swal.fire({
                title: 'Admin Note Required',
                text: 'Please enter a note or rejection reason before rejecting',
                icon: 'warning',
                confirmButtonColor: '#ffc107'
            });
            return;
        }
        
        Swal.fire({
            title: 'Reject Tick Request?',
            html: '<strong>' + userName + '</strong><br><br>The admin note will be saved as the rejection reason.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="bi bi-x-circle"></i> Reject',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Processing...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                $.ajax({
                    url: '<?= base_url('tick/rejectRequest'); ?>',
                    type: 'POST',
                    data: { 
                        userId: userId,
                        email: email,
                        reason: reason
                    },
                    dataType: 'json',
                    success: function(response) {
                        if(response.status == true) {
                            Swal.fire({
                                title: 'Rejected',
                                text: response.message,
                                icon: 'info',
                                confirmButtonColor: '#0d6efd'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    }
                });
            }
        });
    });
});
</script>

