<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $docId  = (int)$_POST['doc_id'];
    $action = $_POST['action'] ?? '';
    $reason = trim($_POST['reason'] ?? '');
    if ($action === 'approve') {
        $pdo->prepare("UPDATE kyc_documents SET status='verified',reviewed_at=NOW(),reviewed_by=? WHERE id=?")->execute([$_SESSION['admin_id'],$docId]);
        $doc = $pdo->prepare("SELECT user_id FROM kyc_documents WHERE id=? LIMIT 1");
        $doc->execute([$docId]); $r=$doc->fetch();
        if ($r) { $pdo->prepare("UPDATE users SET kyc_status='verified' WHERE id=?")->execute([$r['user_id']]); addNotification($pdo,$r['user_id'],'KYC Verified','Your identity has been verified. You now have full account access.','success'); }
        flash('success','KYC document approved.');
    } elseif ($action === 'reject') {
        $pdo->prepare("UPDATE kyc_documents SET status='rejected',rejection_reason=?,reviewed_at=NOW(),reviewed_by=? WHERE id=?")->execute([$reason,$_SESSION['admin_id'],$docId]);
        $doc = $pdo->prepare("SELECT user_id FROM kyc_documents WHERE id=? LIMIT 1");
        $doc->execute([$docId]); $r=$doc->fetch();
        if ($r) { $pdo->prepare("UPDATE users SET kyc_status='rejected' WHERE id=?")->execute([$r['user_id']]); addNotification($pdo,$r['user_id'],'KYC Rejected','Your KYC submission was rejected. Reason: '.$reason,'danger'); }
        flash('success','KYC document rejected.');
    }
    header('Location: /admin/kyc.php'); exit;
}

$statusFilter = $_GET['status'] ?? 'pending';
$stmt = $pdo->prepare("SELECT k.*, CONCAT(u.first_name,' ',u.last_name) AS user_name, u.email AS user_email, u.account_number FROM kyc_documents k JOIN users u ON k.user_id=u.id WHERE k.status=? ORDER BY k.created_at DESC");
$stmt->execute([$statusFilter]); $docs = $stmt->fetchAll();
$pageTitle = 'KYC Review';
?>
<?php include '../includes/header.php'; ?>
<div class="page-title"><i class="fa fa-id-card me-2 text-danger"></i>KYC Review</div>

<ul class="nav nav-tabs mb-4">
  <?php foreach (['pending'=>'Pending','under_review'=>'Under Review','verified'=>'Verified','rejected'=>'Rejected'] as $s=>$l): ?>
  <li class="nav-item"><a class="nav-link <?= $statusFilter===$s?'active':'' ?>" href="?status=<?= $s ?>"><?= $l ?></a></li>
  <?php endforeach; ?>
</ul>

<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead><tr><th>User</th><th>Type</th><th>Doc #</th><th>Country</th><th>Submitted</th><th>Document</th><th>Status</th><th>Actions</th></tr></thead>
      <tbody>
      <?php if (empty($docs)): ?>
      <tr><td colspan="8" class="text-center py-4 text-muted">No <?= $statusFilter ?> KYC documents.</td></tr>
      <?php else: foreach ($docs as $d): ?>
      <tr>
        <td><div class="fw-bold small"><?= sanitize($d['user_name']) ?></div><div class="text-muted" style="font-size:.75rem"><?= sanitize($d['user_email']) ?><br><?= sanitize($d['account_number']) ?></div></td>
        <td class="small"><?= ucfirst(str_replace('_',' ',$d['document_type'])) ?></td>
        <td class="small"><?= sanitize($d['document_number']??'—') ?></td>
        <td class="small"><?= sanitize($d['country_issued']??'—') ?></td>
        <td class="small"><?= formatDate($d['created_at'],'M j, Y') ?></td>
        <td>
          <?php if ($d['document_path']): ?>
          <a href="/uploads/kyc/<?= urlencode($d['document_path']) ?>" target="_blank" class="btn btn-xs btn-outline-primary"><i class="fa fa-eye me-1"></i>Front</a>
          <?php endif; ?>
          <?php if ($d['back_path']): ?>
          <a href="/uploads/kyc/<?= urlencode($d['back_path']) ?>" target="_blank" class="btn btn-xs btn-outline-secondary ms-1"><i class="fa fa-eye me-1"></i>Back</a>
          <?php endif; ?>
          <?php if ($d['selfie_path']): ?>
          <a href="/uploads/kyc/<?= urlencode($d['selfie_path']) ?>" target="_blank" class="btn btn-xs btn-outline-info ms-1"><i class="fa fa-camera me-1"></i>Selfie</a>
          <?php endif; ?>
        </td>
        <td><?= statusBadge($d['status']) ?><?php if ($d['rejection_reason']): ?><div class="text-danger small"><?= sanitize(substr($d['rejection_reason'],0,30)) ?></div><?php endif; ?></td>
        <td>
          <?php if (in_array($d['status'],['pending','under_review'])): ?>
          <form method="POST" class="d-flex gap-1">
            <?= csrf_field() ?><input type="hidden" name="doc_id" value="<?= $d['id'] ?>">
            <button name="action" value="approve" class="btn btn-xs btn-success" data-confirm="Approve this KYC document?"><i class="fa fa-check"></i> Approve</button>
            <button type="button" class="btn btn-xs btn-danger" data-bs-toggle="modal" data-bs-target="#rejectModal" data-docid="<?= $d['id'] ?>"><i class="fa fa-times"></i> Reject</button>
          </form>
          <?php else: ?>
          <a href="/admin/user-edit.php?id=<?= $d['user_id'] ?>" class="btn btn-xs btn-outline-secondary"><i class="fa fa-user"></i></a>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include '../includes/footer.php'; ?>
<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header bg-danger text-white"><h5 class="modal-title">Reject KYC Document</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="reject"><input type="hidden" name="doc_id" id="rejectDocId">
    <div class="mb-3"><label class="form-label">Rejection Reason *</label><textarea name="reason" class="form-control" rows="3" placeholder="Explain why the document was rejected..." required></textarea></div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-danger fw-bold">Reject Document</button></div>
  </form>
</div></div></div>
<script>
document.querySelectorAll('[data-bs-target="#rejectModal"]').forEach(btn => {
  btn.addEventListener('click', () => { document.getElementById('rejectDocId').value = btn.dataset.docid; });
});
</script>
