<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

/* ===============================
   HANDLE APPROVE / REJECT
================================ */
if (is_post()) {
    csrf_verify();

    $userId = (int)($_POST['user_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    $note   = trim($_POST['note'] ?? '');

    if ($userId < 1 || !in_array($action, ['approve','reject'], true)) {
        flash('err','Invalid action.');
        redirect('kyc_review.php');
    }

    $status = $action === 'approve' ? 'verified' : 'rejected';

    $st = $conn->prepare("
        UPDATE users
        SET
          kyc_status=?,
          kyc_review_note=?,
          kyc_reviewed_at=NOW()
        WHERE id=?
        LIMIT 1
    ");
    $st->bind_param("ssi", $status, $note, $userId);
    $st->execute();

    flash('msg', "KYC {$status} successfully.");
    redirect('kyc_review.php');
}

/* ===============================
   LOAD PENDING KYC
================================ */
$users = [];
$res = $conn->query("
    SELECT
      id,
      full_name,
      email,
      kyc_type,
      kyc_id_number,
      kyc_country,
      kyc_front,
      kyc_back,
      kyc_selfie,
      kyc_submitted_at
    FROM users
    WHERE kyc_status='pending'
    ORDER BY kyc_submitted_at ASC
");
while ($r = $res->fetch_assoc()) {
    $users[] = $r;
}

$title = 'KYC Review';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<main class="flex-grow-1" style="margin-left:240px; min-height:100vh;">
<div class="container-fluid py-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="fw-bold mb-0">KYC Review</h3>
    <span class="badge bg-warning">
      <?= count($users) ?> Pending
    </span>
  </div>

  <?php if ($m = flash('msg')): ?>
    <div class="alert alert-success"><?= e($m) ?></div>
  <?php endif; ?>
  <?php if ($m = flash('err')): ?>
    <div class="alert alert-danger"><?= e($m) ?></div>
  <?php endif; ?>

  <?php if (!$users): ?>
    <div class="card ab-card p-4 text-center ab-muted">
      No pending KYC submissions.
    </div>
  <?php endif; ?>

  <?php foreach ($users as $u): ?>
    <div class="card ab-card p-4 mb-4">

      <!-- USER INFO -->
      <div class="mb-3">
        <div class="fw-bold"><?= e($u['full_name'] ?? $u['email']) ?></div>
        <div class="ab-muted"><?= e($u['email']) ?></div>
        <div class="small ab-muted">
          Submitted: <?= e($u['kyc_submitted_at']) ?>
        </div>
      </div>

      <!-- KYC DETAILS -->
      <div class="row g-3 mb-3">
        <div class="col-md-4">
          <div class="ab-muted">ID Type</div>
          <div class="fw-semibold"><?= e($u['kyc_type']) ?></div>
        </div>
        <div class="col-md-4">
          <div class="ab-muted">ID Number</div>
          <div class="fw-semibold"><?= e($u['kyc_id_number']) ?></div>
        </div>
        <div class="col-md-4">
          <div class="ab-muted">Country</div>
          <div class="fw-semibold"><?= e($u['kyc_country']) ?></div>
        </div>
      </div>

      <!-- DOCUMENT PREVIEW -->
      <div class="row g-3 mb-3">
        <div class="col-md-4">
          <div class="ab-muted mb-1">Front</div>
          <a href="<?= e($u['kyc_front']) ?>" target="_blank">
            <img src="<?= e($u['kyc_front']) ?>" class="img-fluid rounded border">
          </a>
        </div>
        <div class="col-md-4">
          <div class="ab-muted mb-1">Back</div>
          <a href="<?= e($u['kyc_back']) ?>" target="_blank">
            <img src="<?= e($u['kyc_back']) ?>" class="img-fluid rounded border">
          </a>
        </div>
        <div class="col-md-4">
          <div class="ab-muted mb-1">Selfie</div>
          <?php if ($u['kyc_selfie']): ?>
            <a href="<?= e($u['kyc_selfie']) ?>" target="_blank">
              <img src="<?= e($u['kyc_selfie']) ?>" class="img-fluid rounded border">
            </a>
          <?php else: ?>
            <div class="ab-muted small">Not provided</div>
          <?php endif; ?>
        </div>
      </div>

      <!-- ACTIONS -->
      <form method="post" class="row g-3">
        <?= csrf_field() ?>
        <input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">

        <div class="col-md-8">
          <input
            name="note"
            class="form-control"
            placeholder="Admin note (optional)"
          >
        </div>

        <div class="col-md-4 d-flex gap-2">
          <button
            name="action"
            value="approve"
            class="btn btn-success w-100">
            Approve
          </button>
          <button
            name="action"
            value="reject"
            class="btn btn-danger w-100"
            onclick="return confirm('Reject this KYC?')">
            Reject
          </button>
        </div>
      </form>

    </div>
  <?php endforeach; ?>

</div>
</main>

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
