<?php
include('include/header.php');
$page_title = WEB_NAME . " | KYC Verifications";

try {
    $stmt = $pdo->query(
        "SELECT k.*, u.username, u.email, u.phone, u.full_name AS user_fullname
         FROM kyc_verifications k
         LEFT JOIN users u ON k.user_id = u.id
         ORDER BY FIELD(k.status, 'pending', 'approved', 'rejected'), k.created_at DESC"
    );
    $kyc_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $kyc_list = []; }

$pending_count  = 0;
$approved_count = 0;
$rejected_count = 0;
foreach ($kyc_list as $k) {
    if ($k['status'] === 'pending') $pending_count++;
    elseif ($k['status'] === 'approved') $approved_count++;
    else $rejected_count++;
}
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">KYC Verifications</h1>
        <span class="badge badge-warning px-3 py-2"><?php echo $pending_count; ?> Pending</span>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-4 mb-3">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div>
                    <div class="h5 mb-0 font-weight-bold"><?php echo $pending_count; ?></div>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Approved</div>
                    <div class="h5 mb-0 font-weight-bold"><?php echo $approved_count; ?></div>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="card border-left-danger shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Rejected</div>
                    <div class="h5 mb-0 font-weight-bold"><?php echo $rejected_count; ?></div>
                </div>
            </div>
        </div>
    </div>

    <!-- KYC Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-shield-halved mr-2"></i>KYC Submissions</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="kycTable" width="100%">
                    <thead class="thead-light">
                        <tr>
                            <th>#</th>
                            <th>User</th>
                            <th>Full Name (KYC)</th>
                            <th>DOB</th>
                            <th>BVN</th>
                            <th>NIN</th>
                            <th>Documents</th>
                            <th>Status</th>
                            <th>Submitted</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($kyc_list as $i => $k):
                            if ($k['status'] === 'pending') $badge = 'badge-warning';
                            elseif ($k['status'] === 'approved') $badge = 'badge-success';
                            else $badge = 'badge-danger';
                        ?>
                        <tr>
                            <td><?php echo $i + 1; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($k['username'] ?? ''); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars($k['email'] ?? ''); ?></small><br>
                                <small class="text-muted"><?php echo htmlspecialchars($k['phone'] ?? ''); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($k['full_name']); ?></td>
                            <td><?php echo date('M d, Y', strtotime($k['dob'])); ?></td>
                            <td><code><?php echo !empty($k['bvn']) ? htmlspecialchars($k['bvn']) : '<span class="text-muted">N/A</span>'; ?></code></td>
                            <td><code><?php echo !empty($k['nin']) ? htmlspecialchars($k['nin']) : '<span class="text-muted">N/A</span>'; ?></code></td>
                            <td>
                                <?php if (!empty($k['id_card_file'])): ?>
                                <a href="../uploads/kyc/<?php echo htmlspecialchars($k['id_card_file']); ?>" target="_blank" class="btn btn-sm btn-outline-primary mb-1"><i class="fas fa-id-card"></i> ID</a>
                                <?php endif; ?>
                                <?php if (!empty($k['selfie_file'])): ?>
                                <a href="../uploads/kyc/<?php echo htmlspecialchars($k['selfie_file']); ?>" target="_blank" class="btn btn-sm btn-outline-info"><i class="fas fa-camera"></i> Selfie</a>
                                <?php endif; ?>
                            </td>
                            <td><span class="badge <?php echo $badge; ?>"><?php echo ucfirst($k['status']); ?></span></td>
                            <td><small><?php echo date('M d, Y H:i', strtotime($k['created_at'])); ?></small></td>
                            <td>
                                <?php if ($k['status'] === 'pending'): ?>
                                <button class="btn btn-sm btn-success mb-1" onclick="approveKyc(<?php echo $k['id']; ?>)">
                                    <i class="fas fa-check"></i> Approve
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="rejectKyc(<?php echo $k['id']; ?>)">
                                    <i class="fas fa-times"></i> Reject
                                </button>
                                <?php elseif ($k['status'] === 'approved'): ?>
                                <span class="text-success"><i class="fas fa-check-circle"></i> Verified</span>
                                <?php else: ?>
                                <small class="text-muted"><?php echo htmlspecialchars($k['admin_note'] ?? 'Rejected'); ?></small>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
function approveKyc(id) {
    if (!confirm('Approve this KYC submission?')) return;
    $.ajax({
        url: 'ajax/kyc_admin.php',
        type: 'POST',
        data: { action: 'approve', kyc_id: id },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1') { alert('Approved!'); location.reload(); }
            else alert(res.msg || 'Failed.');
        }
    });
}

function rejectKyc(id) {
    var reason = prompt('Rejection reason (shown to user):');
    if (reason === null) return;
    $.ajax({
        url: 'ajax/kyc_admin.php',
        type: 'POST',
        data: { action: 'reject', kyc_id: id, reason: reason },
        dataType: 'json',
        success: function(res) {
            if (res.status === '1') { alert('Rejected.'); location.reload(); }
            else alert(res.msg || 'Failed.');
        }
    });
}

$(document).ready(function() {
    if ($.fn.DataTable) {
        $('#kycTable').DataTable({ order: [[7, 'desc']], pageLength: 25 });
    }
});
</script>

<?php include('include/footer.php'); ?>
