<?php
$pageTitle = 'KYC Verification';
/**
 * Admin KYC Management
 */
require_once 'includes/header.php';

$filter = $_GET['status'] ?? 'submitted';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $userId = $_POST['user_id'] ?? 0;
    
    if ($action === 'approve') {
        dbUpdate('users', ['kyc_status' => 'verified'], 'id = :uid', ['uid' => $userId]);
        dbUpdate('user_kyc', ['status' => 'verified', 'verified_at' => date('Y-m-d H:i:s')], 'user_id = :uid', ['uid' => $userId]);
        echo '<div class="alert alert-success"><i class="fas fa-check"></i> KYC Approved!</div>';
    } elseif ($action === 'reject') {
        $reason = $_POST['reason'] ?? 'Documents not acceptable';
        dbUpdate('users', ['kyc_status' => 'rejected'], 'id = :uid', ['uid' => $userId]);
        dbUpdate('user_kyc', ['status' => 'rejected', 'rejection_reason' => $reason], 'user_id = :uid', ['uid' => $userId]);
        echo '<div class="alert alert-success"><i class="fas fa-check"></i> KYC Rejected!</div>';
    }
}

// Build the query based on filter
if ($filter === 'all') {
    $where = "u.kyc_status IN ('submitted','verified','rejected')";
} elseif ($filter === 'submitted') {
    $where = "u.kyc_status = 'submitted'";
} elseif ($filter === 'verified') {
    $where = "u.kyc_status = 'verified'";
} elseif ($filter === 'rejected') {
    $where = "u.kyc_status = 'rejected'";
} else {
    $where = "u.kyc_status = 'submitted'";
}

// Fetch users with KYC data from user_kyc table
$users = dbFetchAll("
    SELECT u.*, 
           k.document_type, k.document_number, 
           k.document_front, k.document_back, k.selfie,
           k.status as kyc_doc_status, k.rejection_reason as kyc_rejection_reason,
           k.created_at as kyc_submitted_at
    FROM users u
    LEFT JOIN user_kyc k ON u.id = k.user_id
    WHERE $where
    ORDER BY k.created_at DESC, u.created_at DESC
    LIMIT 100
");

$stats = [
    'submitted' => dbFetch("SELECT COUNT(*) as c FROM users WHERE kyc_status = 'submitted'")['c'] ?? 0,
    'verified' => dbFetch("SELECT COUNT(*) as c FROM users WHERE kyc_status = 'verified'")['c'] ?? 0,
    'rejected' => dbFetch("SELECT COUNT(*) as c FROM users WHERE kyc_status = 'rejected'")['c'] ?? 0
];
?>

<style>
.kyc-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 1.5rem; margin-bottom: 1rem; }
.kyc-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; }
.kyc-user { display: flex; align-items: center; gap: 1rem; }
.kyc-avatar { width: 48px; height: 48px; border-radius: 50%; background: var(--accent-green); display: flex; align-items: center; justify-content: center; font-weight: 700; color: #000; }
.kyc-docs { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin: 1rem 0; }
.kyc-doc { background: var(--bg-tertiary); border-radius: 8px; padding: 1rem; text-align: center; }
.kyc-doc img { max-width: 100%; max-height: 150px; border-radius: 4px; cursor: pointer; }
.kyc-doc-label { font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem; }
.kyc-info { background: var(--bg-tertiary); border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 1rem; display: flex; gap: 2rem; flex-wrap: wrap; }
.kyc-info-item { display: flex; flex-direction: column; }
.kyc-info-label { font-size: 0.75rem; color: var(--text-muted); }
.kyc-info-value { font-weight: 600; }
.kyc-actions { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.kyc-container { max-height: calc(100vh - 280px); overflow-y: auto; }
</style>

<div class="page-header">
    <h1 class="page-title">KYC Verification</h1>
</div>

<div class="row mb-4">
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon yellow"><i class="fas fa-clock"></i></div>
            <div class="stat-value"><?= number_format($stats['submitted']) ?></div>
            <div class="stat-label">Pending Review</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon green"><i class="fas fa-check"></i></div>
            <div class="stat-value"><?= number_format($stats['verified']) ?></div>
            <div class="stat-label">Verified</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon red"><i class="fas fa-times"></i></div>
            <div class="stat-value"><?= number_format($stats['rejected']) ?></div>
            <div class="stat-label">Rejected</div>
        </div>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <div class="d-flex gap-2">
            <a href="?status=submitted" class="btn btn-sm <?= $filter === 'submitted' ? 'btn-primary' : 'btn-secondary' ?>">Pending</a>
            <a href="?status=verified" class="btn btn-sm <?= $filter === 'verified' ? 'btn-primary' : 'btn-secondary' ?>">Verified</a>
            <a href="?status=rejected" class="btn btn-sm <?= $filter === 'rejected' ? 'btn-primary' : 'btn-secondary' ?>">Rejected</a>
            <a href="?status=all" class="btn btn-sm <?= $filter === 'all' ? 'btn-primary' : 'btn-secondary' ?>">All</a>
        </div>
    </div>
</div>

<div class="kyc-container">
    <?php if (empty($users)): ?>
    <div class="card">
        <div class="card-body text-center py-5">
            <i class="fas fa-id-card fa-3x text-muted mb-3"></i>
            <h3>No KYC Requests</h3>
            <p class="text-muted">No KYC verification requests found</p>
        </div>
    </div>
    <?php else: ?>
    <?php foreach ($users as $u): ?>
    <div class="kyc-card">
        <div class="kyc-header">
            <div class="kyc-user">
                <div class="kyc-avatar"><?= strtoupper(substr($u['first_name'] ?? $u['email'], 0, 1)) ?></div>
                <div>
                    <div class="font-semibold"><?= htmlspecialchars($u['first_name'] ?? '') ?> <?= htmlspecialchars($u['last_name'] ?? '') ?></div>
                    <div class="text-muted text-sm"><?= htmlspecialchars($u['email']) ?></div>
                    <div class="text-muted text-sm">Joined: <?= date('d M Y', strtotime($u['created_at'])) ?></div>
                </div>
            </div>
            <span class="badge badge-<?= $u['kyc_status'] === 'verified' ? 'success' : ($u['kyc_status'] === 'submitted' ? 'warning' : 'danger') ?>">
                <?= $u['kyc_status'] === 'submitted' ? 'Pending Review' : ucfirst($u['kyc_status'] ?? 'none') ?>
            </span>
        </div>
        
        <?php if (!empty($u['document_type'])): ?>
        <div class="kyc-info">
            <div class="kyc-info-item">
                <span class="kyc-info-label">Document Type</span>
                <span class="kyc-info-value"><?= ucfirst(str_replace('_', ' ', $u['document_type'])) ?></span>
            </div>
            <div class="kyc-info-item">
                <span class="kyc-info-label">Document Number</span>
                <span class="kyc-info-value"><?= htmlspecialchars($u['document_number']) ?></span>
            </div>
            <?php if (!empty($u['kyc_submitted_at'])): ?>
            <div class="kyc-info-item">
                <span class="kyc-info-label">Submitted On</span>
                <span class="kyc-info-value"><?= date('d M Y H:i', strtotime($u['kyc_submitted_at'])) ?></span>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="kyc-docs">
            <?php if (!empty($u['document_front'])): ?>
            <div class="kyc-doc">
                <img src="<?= SITE_URL ?>/uploads/kyc/<?= $u['document_front'] ?>" alt="ID Front" onclick="window.open(this.src)">
                <div class="kyc-doc-label">ID Document (Front)</div>
            </div>
            <?php endif; ?>
            <?php if (!empty($u['document_back'])): ?>
            <div class="kyc-doc">
                <img src="<?= SITE_URL ?>/uploads/kyc/<?= $u['document_back'] ?>" alt="ID Back" onclick="window.open(this.src)">
                <div class="kyc-doc-label">ID Document (Back)</div>
            </div>
            <?php endif; ?>
            <?php if (!empty($u['selfie'])): ?>
            <div class="kyc-doc">
                <img src="<?= SITE_URL ?>/uploads/kyc/<?= $u['selfie'] ?>" alt="Selfie" onclick="window.open(this.src)">
                <div class="kyc-doc-label">Selfie with ID</div>
            </div>
            <?php endif; ?>
        </div>
        
        <?php if ($u['kyc_status'] === 'submitted'): ?>
        <div class="kyc-actions">
            <form method="POST" style="display:inline">
                <input type="hidden" name="action" value="approve">
                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                <button type="submit" class="btn btn-success">
                    <i class="fas fa-check"></i> Approve
                </button>
            </form>
            <form method="POST" style="display:inline" onsubmit="return confirm('Reject this KYC?')">
                <input type="hidden" name="action" value="reject">
                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                <input type="text" name="reason" placeholder="Rejection reason" class="form-control" style="width:200px;display:inline-block">
                <button type="submit" class="btn btn-danger">
                    <i class="fas fa-times"></i> Reject
                </button>
            </form>
        </div>
        <?php elseif ($u['kyc_status'] === 'rejected' && !empty($u['kyc_rejection_reason'])): ?>
        <div class="text-danger text-sm">
            <strong>Rejection Reason:</strong> <?= htmlspecialchars($u['kyc_rejection_reason']) ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<?php require_once 'includes/footer.php'; ?>
