<?php $reports = $reports ?? []; ?>

<main class="main-wrapper">
  <div class="main-content reports-page">
    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between mb-4">
      <div>
        <h2 class="page-title mb-1">Pending Reports</h2>
        <p class="text-muted mb-0">Review community submissions and take the appropriate moderation action.</p>
          </div>
      <div class="mt-3 mt-md-0">
        <div class="input-group reports-search">
          <span class="input-group-text"><i class="bi bi-search"></i></span>
          <input type="text" id="reportSearch" class="form-control" placeholder="Search by user, reporter, or reason" aria-label="Search reports">
        </div>
      </div>
        </div>

    <div id="reports-alert"></div>

    <?php if (empty($reports)): ?>
      <div class="card border-0 shadow-sm">
        <div class="card-body text-center py-5">
          <img src="<?php echo base_url('assets/images/empty-state.png'); ?>" alt="No reports" class="empty-illustration mb-3">
          <h5 class="fw-semibold">No pending reports</h5>
          <p class="text-muted mb-0">Great news! There are currently no reports awaiting review.</p>
        </div>
      </div>
    <?php else: ?>
      <div class="row g-4" id="reports-container">
        <?php foreach ($reports as $report):
          $reportId         = $report['id'];
          $reportedUserId   = $report['reportedUserId'] ?? '';
          $reportedUserName = $report['reportedUserName'] ?? 'Unknown user';
          $reporterId       = $report['reporterUserId'] ?? '';
          $reporterName     = $report['reporterName'] ?? 'Anonymous';
          $reason           = $report['reason'] ?? 'No reason provided';
          $note             = $report['note'] ?? '';
          $createdAt        = isset($report['createdAt']) && $report['createdAt'] > 0 ? date('M j, Y g:i A', $report['createdAt'] / 1000) : 'Unknown';
          $attachment       = $report['attachmentUrl'] ?? '';
          $evidenceList     = [];
          if (is_array($attachment)) {
              $evidenceList = array_filter($attachment);
          } elseif (!empty($attachment)) {
              $evidenceList = [$attachment];
          }
        ?>
          <div class="col-xl-6 report-card-wrapper">
            <div
              class="card report-card shadow-sm border-0"
              data-report-id="<?php echo htmlspecialchars($reportId); ?>"
              data-user-id="<?php echo htmlspecialchars($reportedUserId); ?>"
              data-reported-name="<?php echo htmlspecialchars($reportedUserName); ?>"
            >
              <div class="card-header bg-white border-0 d-flex justify-content-between align-items-start">
                <div>
                  <span class="badge bg-primary-soft text-primary">Report #<?php echo htmlspecialchars(substr($reportId, -6)); ?></span>
                  <h5 class="report-reason mb-0 mt-2"><?php echo htmlspecialchars($reason); ?></h5>
                  <small class="text-muted">Submitted on <?php echo htmlspecialchars($createdAt); ?></small>
    </div>
                <span class="badge bg-danger-soft text-danger text-uppercase">Pending</span>
        </div>
              <div class="card-body">
                <dl class="row mb-0">
                  <dt class="col-sm-5">Reported User</dt>
                  <dd class="col-sm-7 mb-2">
                    <span class="fw-semibold d-block"><?php echo htmlspecialchars($reportedUserName); ?></span>
                    <?php if (!empty($reportedUserId)): ?>
                      <small class="text-muted">User ID: <?php echo htmlspecialchars($reportedUserId); ?></small>
                    <?php endif; ?>
                  </dd>

                  <dt class="col-sm-5">Reporter</dt>
                  <dd class="col-sm-7 mb-2">
                    <span class="fw-semibold d-block"><?php echo htmlspecialchars($reporterName); ?></span>
                    <?php if (!empty($reporterId)): ?>
                      <small class="text-muted">User ID: <?php echo htmlspecialchars($reporterId); ?></small>
                    <?php endif; ?>
                  </dd>

                  <?php if (!empty($note)): ?>
                    <dt class="col-sm-5">Reporter Note</dt>
                    <dd class="col-sm-7 mb-2 text-muted"><?php echo nl2br(htmlspecialchars($note)); ?></dd>
                  <?php endif; ?>

                  <?php if (!empty($evidenceList)): ?>
                    <dt class="col-sm-5">Evidence</dt>
                    <dd class="col-sm-7 mb-2">
                      <div class="evidence-grid">
                        <?php foreach ($evidenceList as $index => $url):
                          $isImage = preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $url);
                        ?>
                          <a href="<?php echo htmlspecialchars($url); ?>" target="_blank" class="evidence-item <?php echo $isImage ? 'has-thumbnail' : ''; ?>">
                            <?php if ($isImage): ?>
                              <img src="<?php echo htmlspecialchars($url); ?>" alt="Evidence <?php echo $index + 1; ?>" class="img-fluid rounded">
                            <?php else: ?>
                              <i class="bi bi-link-45deg"></i> Attachment <?php echo $index + 1; ?>
                            <?php endif; ?>
                          </a>
                        <?php endforeach; ?>
          </div>
                    </dd>
                  <?php endif; ?>
                </dl>
        </div>
              <div class="card-footer bg-transparent border-0 pt-0">
                <div class="d-flex flex-wrap gap-2 justify-content-end">
                  <button type="button" class="btn btn-outline-warning btn-report-action btn-report-warning" data-report-id="<?php echo htmlspecialchars($reportId); ?>">
                    <i class="bi bi-exclamation-triangle me-1"></i>Send Warning
                  </button>
                  <button type="button" class="btn btn-outline-danger btn-report-action btn-report-suspend" data-report-id="<?php echo htmlspecialchars($reportId); ?>">
                    <i class="bi bi-shield-exclamation me-1"></i>Suspend
                  </button>
                  <button type="button" class="btn btn-outline-secondary btn-report-action btn-report-delete" data-report-id="<?php echo htmlspecialchars($reportId); ?>">
                    <i class="bi bi-trash me-1"></i>Delete
                  </button>
      </div>
    </div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</main>

<div class="modal fade" id="reportsAlertModal" tabindex="-1" aria-labelledby="reportsAlertModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="reportsAlertModalLabel">Notification</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
        </div>

<style>
  .reports-page {
    padding: 1.5rem;
  }
  .page-title {
    font-weight: 600;
  }
  .reports-search .form-control {
    min-width: 260px;
  }
  .report-card-wrapper {
    transition: transform 0.2s ease;
  }
  .report-card-wrapper.removed {
    opacity: 0;
    transform: translateY(10px);
  }
  .report-card {
    border-radius: 16px;
    overflow: hidden;
  }
  .report-reason {
    font-weight: 600;
  }
  .evidence-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }
  .evidence-item {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.35rem 0.65rem;
    border-radius: 10px;
    border: 1px solid rgba(148, 163, 184, 0.3);
    color: #475569;
    font-size: 0.85rem;
    transition: all 0.2s ease;
    text-decoration: none;
  }
  .evidence-item.has-thumbnail {
    padding: 0;
    border: none;
  }
  .evidence-item img {
    width: 68px;
    height: 68px;
    object-fit: cover;
    border-radius: 10px;
  }
  .evidence-item:hover {
    border-color: rgba(79, 70, 229, 0.4);
    color: #4f46e5;
    text-decoration: none;
  }
  .btn-report-action {
    min-width: 140px;
    border-radius: 999px;
  }
  .empty-illustration {
    max-width: 160px;
    opacity: 0.8;
  }
</style>

<script>
  (function() {
    const container = document.getElementById('reports-container');
    const alertBox = document.getElementById('reports-alert');
    const searchInput = document.getElementById('reportSearch');
    const endpoints = {
      warning: '<?php echo base_url('site/reportSendWarning'); ?>',
      suspend: '<?php echo base_url('site/reportSuspend'); ?>',
      delete: '<?php echo base_url('site/reportDelete'); ?>'
    };

    const showAlert = (title, message, type = 'info') => {
      const iconMap = {
        success: 'success',
        warning: 'warning',
        danger: 'error',
        info: 'info'
      };
      const icon = iconMap[type] || 'info';
      if (typeof Swal !== 'undefined') {
        Swal.fire({
          title,
          text: message,
          icon,
          confirmButtonColor: '#4f46e5'
        });
      } else {
        window.alert(`${title}: ${message}`);
      }
    };

    const removeCard = (card) => {
      if (!card) return;
      const wrapper = card.parentElement;
      if (wrapper) {
        wrapper.classList.add('removed');
        setTimeout(() => wrapper.remove(), 250);
      }
      checkEmptyState();
    };

    const checkEmptyState = () => {
      if (!container) return;
      if (!container.querySelector('.report-card')) {
        const emptyCard = document.createElement('div');
        emptyCard.className = 'card border-0 shadow-sm';
        emptyCard.innerHTML = `
          <div class="card-body text-center py-5">
            <img src="<?php echo base_url('assets/images/empty-state.png'); ?>" alt="No reports" class="empty-illustration mb-3">
            <h5 class="fw-semibold">No pending reports</h5>
            <p class="text-muted mb-0">Great news! There are currently no reports awaiting review.</p>
          </div>`;
        container.parentElement.appendChild(emptyCard);
      }
    };

    const setButtonState = (button, loading, label) => {
      if (!button) return;
      if (loading) {
        button.dataset.originalLabel = button.innerHTML;
        button.disabled = true;
        button.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>' + label;
      } else {
        button.disabled = false;
        button.innerHTML = button.dataset.originalLabel || button.innerHTML;
      }
    };

    const handleAction = (button, type) => {
      if (!button) return;
      const card = button.closest('.report-card');
      if (!card) return;

      const reportId = card.getAttribute('data-report-id');
      if (!reportId) {
        showAlert('Missing data', 'Report id missing.', 'danger');
        return;
      }

      const reportedName = card.getAttribute('data-reported-name') || 'this user';
      const confirmConfig = {
        warning: {
          title: 'Send warning?',
          text: `Record a warning against ${reportedName}?`,
          confirmColor: '#4f46e5'
        },
        suspend: {
          title: 'Suspend user?',
          text: `${reportedName} will be suspended for 2 hours.`,
          confirmColor: '#d97706'
        },
        delete: {
          title: 'Delete report?',
          text: 'This report will be removed permanently.',
          confirmColor: '#d33'
        }
      };
      const confirmTitle = confirmConfig[type]?.title || 'Are you sure?';
      const confirmText  = confirmConfig[type]?.text || 'Continue with this action?';
      const confirmColor = confirmConfig[type]?.confirmColor || '#4f46e5';

      const executeAction = () => {
        setButtonState(button, true, 'Processing...');

        fetch(endpoints[type], {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest'
          },
          body: new URLSearchParams({ reportId })
        })
          .then(response => response.json())
          .then(data => {
            if (!data || data.success !== true) {
              const message = data && data.message ? data.message : 'Something went wrong. Please try again.';
              showAlert('Action failed', message, 'danger');
              return;
            }

            if (type === 'warning') {
              const warningCount = data.warningCount ?? 'updated';
              showAlert('Warning recorded', `Warning recorded successfully (total warnings: ${warningCount}).`, 'success');
              if (data.autoSuspended) {
                showAlert('Auto suspension', 'User automatically suspended for 2 hours after exceeding the warning threshold.', 'warning');
              }
            } else if (type === 'suspend') {
              showAlert('User suspended', 'User suspended for 2 hours and report resolved.', 'success');
            } else if (type === 'delete') {
              showAlert('Report deleted', 'The report has been deleted.', 'info');
            }

            removeCard(card);
          })
          .catch(() => {
            showAlert('Network error', 'Network error. Please try again.', 'danger');
          })
          .finally(() => setButtonState(button, false));
      };

      if (typeof Swal !== 'undefined') {
        Swal.fire({
          title: confirmTitle,
          text: confirmText,
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: confirmColor,
          cancelButtonColor: '#6b7280',
          confirmButtonText: 'Yes, continue'
        }).then((result) => {
          if (result.isConfirmed) {
            executeAction();
          }
        });
      } else if (confirm(confirmText)) {
        executeAction();
      }
    };

    if (container) {
      container.addEventListener('click', (event) => {
        const warningBtn = event.target.closest('.btn-report-warning');
        const suspendBtn = event.target.closest('.btn-report-suspend');
        const deleteBtn = event.target.closest('.btn-report-delete');

        if (warningBtn) {

          event.preventDefault();
          handleAction(warningBtn, 'warning');
        }
        if (suspendBtn) {
          event.preventDefault();
          handleAction(suspendBtn, 'suspend');
        }
        if (deleteBtn) {
          event.preventDefault();
          handleAction(deleteBtn, 'delete');
        }
      });
    }

    if (searchInput && container) {
      searchInput.addEventListener('input', () => {
        const query = searchInput.value.toLowerCase();
        container.querySelectorAll('.report-card-wrapper').forEach(wrapper => {
          const card = wrapper.querySelector('.report-card');
          const text = card ? card.innerText.toLowerCase() : '';
          wrapper.classList.toggle('d-none', !text.includes(query));
        });
      });
    }
  })();
</script>
