<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/kyc.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
if (!hasPermission('manage_users')) { die("Access Denied."); }

$user_id = $_SESSION['user_id'];
kyc_ensure_schema($db);

$me_row = $db->select("SELECT id, name FROM users WHERE id = ?", [$user_id]);
$me = !empty($me_row) ? $me_row[0] : ['id' => $user_id, 'name' => 'Admin'];

$success_msg = '';
if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }

// AJAX: KYC details for the review modal
if (isset($_GET['ajax']) && $_GET['ajax'] === 'kyc') {
    header('Content-Type: application/json');
    $uid = intval($_GET['uid'] ?? 0);
    $r = $db->select("SELECT * FROM kyc_details WHERE user_id = ?", [$uid]);
    echo json_encode(!empty($r) ? $r[0] : null);
    exit;
}

// Approve / Reject
if (isset($_POST['kyc_action'])) {
    $tid    = intval($_POST['target_user_id']);
    $act    = $_POST['kyc_action'];
    $remark = sanitize($_POST['kyc_remark'] ?? '');
    if (in_array($act, ['approved', 'rejected'])) {
        $db->insert("UPDATE kyc_details SET status = ?, admin_remark = ? WHERE user_id = ?", [$act, $remark, $tid]);
        try {
            $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name) VALUES (?, 'KYC Status', 'pending', ?, ?, ?)",
                [$tid, ucfirst($act) . ($remark ? " ($remark)" : ''), $me['id'], $me['name']]);
        } catch (\Throwable $e) {}
        $_SESSION['flash_success'] = "KYC " . ucfirst($act) . " successfully!";
    }
    redirect('kyc_pending.php' . (isset($_GET['status']) ? '?status=' . $_GET['status'] : ''));
}

$status_filter = $_GET['status'] ?? 'pending';
if (!in_array($status_filter, ['pending', 'approved', 'rejected', 'all'])) $status_filter = 'pending';
$where  = ($status_filter === 'all') ? '1' : 'k.status = ?';
$params = ($status_filter === 'all') ? [] : [$status_filter];
$rows = $db->select("SELECT k.*, u.name, u.mobile, u.email, u.profile_pic, u.user_type
                     FROM kyc_details k JOIN users u ON u.id = k.user_id
                     WHERE $where ORDER BY (k.updated_at IS NULL), k.updated_at DESC, k.created_at DESC", $params);

$counts = ['pending' => 0, 'approved' => 0, 'rejected' => 0];
foreach ($counts as $st => $_) {
    $c = $db->select("SELECT COUNT(*) AS c FROM kyc_details WHERE status = ?", [$st]);
    $counts[$st] = !empty($c) ? intval($c[0]['c']) : 0;
}

$user = $db->select("SELECT * FROM users WHERE id = ?", [$user_id])[0] ?? ['name' => 'Admin', 'profile_pic' => ''];
$raw_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;
function userCodeK($id) { return 'WBMCZ' . str_pad($id, 4, '0', STR_PAD_LEFT); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYC Pending - Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50" x-data="kycApp()">
<div class="flex h-screen overflow-hidden">
    <!-- SIDEBAR -->
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
        <header class="h-20 bg-white flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40">
            <div class="flex items-center">
                <button @click="sidebarOpen=!sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg hover:bg-gray-100"><i class="fas fa-bars text-xl"></i></button>
                <h2 class="text-xl font-bold hidden md:block text-slate-800">KYC Verification</h2>
            </div>
            <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                <img src="<?php echo $profile_image_url; ?>" class="w-10 h-10 rounded-full border-2 border-emerald-100 object-cover">
            <?php else: ?>
                <div class="w-10 h-10 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center font-bold"><?php echo strtoupper(substr($user['name'],0,1)); ?></div>
            <?php endif; ?>
        </header>

        <main class="flex-1 overflow-y-auto p-4 md:p-6">
            <div class="mb-5">
                <h2 class="text-2xl font-bold text-slate-800 mb-1">KYC Pending & Review</h2>
                <p class="text-gray-500 text-sm">Review submitted KYC, view / download documents, then approve or reject.</p>
            </div>

            <?php if ($success_msg): ?>
                <div class="mb-4 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm"><i class="fas fa-check-circle text-xl mr-3"></i><span class="font-medium"><?php echo $success_msg; ?></span></div>
            <?php endif; ?>

            <!-- Status tabs -->
            <div class="flex flex-wrap gap-2 mb-5">
                <?php
                $tabs = [
                    'pending'  => ['Pending',  'amber',   $counts['pending']],
                    'approved' => ['Approved', 'emerald', $counts['approved']],
                    'rejected' => ['Rejected', 'rose',    $counts['rejected']],
                    'all'      => ['All',      'slate',   array_sum($counts)],
                ];
                foreach ($tabs as $key => $t):
                    $active = ($status_filter === $key);
                ?>
                <a href="?status=<?php echo $key; ?>" class="px-4 py-2 rounded-xl text-sm font-bold border transition-all <?php echo $active ? 'bg-'.$t[1].'-500 text-white border-'.$t[1].'-500 shadow' : 'bg-white text-slate-600 border-slate-200 hover:border-'.$t[1].'-300'; ?>">
                    <?php echo $t[0]; ?> <span class="ml-1 text-xs opacity-80">(<?php echo $t[2]; ?>)</span>
                </a>
                <?php endforeach; ?>
            </div>

            <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-sm">
                        <thead>
                            <tr class="bg-slate-50 text-[11px] uppercase text-slate-500 tracking-wider">
                                <th class="p-4">User</th>
                                <th class="p-4">Type</th>
                                <th class="p-4">Submitted / Updated</th>
                                <th class="p-4">Status</th>
                                <th class="p-4 text-right">Review</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                            <?php if(!empty($rows)): foreach($rows as $r):
                                $sm = ['pending'=>['Pending','bg-amber-100 text-amber-700'],'approved'=>['Approved','bg-emerald-100 text-emerald-700'],'rejected'=>['Rejected','bg-rose-100 text-rose-700']];
                                $jsName = htmlspecialchars(addslashes($r['name']), ENT_QUOTES);
                                $when = !empty($r['updated_at']) ? $r['updated_at'] : $r['created_at'];
                            ?>
                            <tr class="hover:bg-slate-50/50">
                                <td class="p-4">
                                    <div class="flex items-center gap-3">
                                        <?php if(!empty($r['profile_pic']) && file_exists('../uploads/profiles/'.$r['profile_pic'])): ?>
                                            <img src="../uploads/profiles/<?php echo $r['profile_pic']; ?>" class="w-10 h-10 rounded-full object-cover border">
                                        <?php else: ?>
                                            <div class="w-10 h-10 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center font-bold"><?php echo strtoupper(substr($r['name'],0,1)); ?></div>
                                        <?php endif; ?>
                                        <div>
                                            <p class="font-bold text-slate-800"><?php echo htmlspecialchars($r['name']); ?></p>
                                            <p class="text-xs text-slate-500"><?php echo userCodeK($r['user_id']); ?> &bull; <?php echo htmlspecialchars($r['mobile']); ?></p>
                                        </div>
                                    </div>
                                </td>
                                <td class="p-4"><span class="text-xs font-semibold uppercase text-slate-500"><?php echo $r['user_type']==='admin' ? 'Staff' : ucfirst($r['user_type']); ?></span></td>
                                <td class="p-4 text-xs text-slate-500 whitespace-nowrap"><?php echo date('d M Y, h:i A', strtotime($when)); ?></td>
                                <td class="p-4"><span class="text-[10px] font-bold px-2.5 py-1 rounded-full uppercase <?php echo $sm[$r['status']][1] ?? 'bg-slate-100 text-slate-500'; ?>"><?php echo $sm[$r['status']][0] ?? $r['status']; ?></span></td>
                                <td class="p-4 text-right">
                                    <button @click="openKyc(<?php echo $r['user_id']; ?>, '<?php echo $jsName; ?>')" class="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold shadow"><i class="fas fa-eye mr-1"></i>Review</button>
                                </td>
                            </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="5" class="p-12 text-center text-gray-500">
                                    <div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 text-gray-400 text-2xl border"><i class="fas fa-id-card"></i></div>
                                    <p class="text-lg font-medium">No KYC submissions in this category.</p>
                                </td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- ===== KYC REVIEW MODAL ===== -->
<div x-show="modal" x-transition.opacity style="display:none;" class="fixed inset-0 z-[100] flex items-center justify-center p-4">
    <div class="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" @click="modal=false"></div>
    <div class="relative w-full max-w-3xl bg-white rounded-2xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
        <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-5 py-4 flex items-center justify-between flex-shrink-0">
            <h3 class="text-white font-bold text-lg"><i class="fas fa-id-card mr-2"></i>KYC — <span x-text="curName"></span></h3>
            <button @click="modal=false" class="text-white/80 hover:text-white text-2xl leading-none">&times;</button>
        </div>
        <div class="px-5 py-2 bg-blue-50 text-blue-800 text-xs font-semibold border-b border-blue-100 flex-shrink-0">
            Status: <span class="uppercase" x-text="kyc?.status || '—'"></span>
        </div>
        <div class="p-5 overflow-y-auto text-sm">
            <template x-if="loading"><p class="text-center text-slate-400 py-6"><i class="fas fa-spinner fa-spin mr-2"></i>Loading...</p></template>
            <template x-if="!loading && !kyc"><p class="text-center text-slate-400 py-8">No KYC found.</p></template>
            <div x-show="!loading && kyc" class="space-y-5">
                <?php
                // section => [title, color, [ [field,label], ... ], [ [fileField,label], ... ] ]
                $secDefs = [
                    ['Personal Details', 'amber',   [['full_name','Name'],['gender','Gender'],['dob','DOB'],['father_name','Father'],['email','Email'],['aadhar_number','Aadhar'],['pancard_number','PAN']], [['aadhar_front','Aadhar Front'],['aadhar_back','Aadhar Back'],['pan_card','PAN Card'],['photo','Photo']]],
                    ['Address Details',  'blue',    [['village','Village'],['post_office','Post Office'],['block_city','Block/City'],['landmark','Landmark'],['district','District'],['state','State'],['pincode','Pincode']], [['address_proof','Address Proof']]],
                    ['Bank Details',     'rose',    [['bank_name','Bank'],['branch_name','Branch'],['account_number','Account'],['ifsc_code','IFSC']], [['bank_passbook','Passbook']]],
                    ['Business Details', 'emerald', [['business_name','Business'],['business_phone','Phone'],['business_email','Email'],['biz_village','Village'],['biz_post_office','Post Office'],['biz_block_city','Block/City'],['biz_landmark','Landmark'],['biz_district','District'],['biz_state','State'],['biz_pincode','Pincode']], [['business_proof','Business Proof']]],
                ];
                foreach ($secDefs as $sd):
                ?>
                <div>
                    <p class="text-[11px] font-bold uppercase tracking-wide text-<?php echo $sd[1]; ?>-600 mb-2 border-b pb-1"><?php echo $sd[0]; ?></p>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-x-4 gap-y-1.5">
                        <?php foreach ($sd[2] as $f): ?>
                            <p><span class="text-slate-400"><?php echo $f[1]; ?>:</span> <b x-text="kyc?.<?php echo $f[0]; ?> || '—'"></b></p>
                        <?php endforeach; ?>
                    </div>
                    <div class="flex flex-wrap gap-2 mt-2">
                        <?php foreach ($sd[3] as $fl): ?>
                            <template x-if="kyc?.<?php echo $fl[0]; ?>">
                                <span class="inline-flex items-center gap-1 bg-slate-100 rounded-lg px-2 py-1 text-[11px]">
                                    <span class="font-semibold text-slate-600"><?php echo $fl[1]; ?>:</span>
                                    <a :href="'../uploads/kyc/'+kyc?.<?php echo $fl[0]; ?>" target="_blank" class="text-blue-600 hover:text-blue-800 font-bold"><i class="fas fa-eye"></i> View</a>
                                    <a :href="'../uploads/kyc/'+kyc?.<?php echo $fl[0]; ?>" :download="kyc?.<?php echo $fl[0]; ?>" class="text-emerald-600 hover:text-emerald-800 font-bold"><i class="fas fa-download"></i> Download</a>
                                </span>
                            </template>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <form method="POST" class="px-5 py-4 border-t border-slate-100 bg-slate-50 flex-shrink-0" x-show="!loading && kyc">
            <input type="hidden" name="target_user_id" :value="curId">
            <input type="text" name="kyc_remark" placeholder="Remark (optional, shown to user if rejected)" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-blue-400">
            <div class="flex justify-end gap-2">
                <button type="submit" name="kyc_action" value="rejected" class="px-5 py-2 text-sm font-bold text-white bg-rose-600 hover:bg-rose-700 rounded-lg shadow"><i class="fas fa-times mr-1"></i>Reject</button>
                <button type="submit" name="kyc_action" value="approved" class="px-5 py-2 text-sm font-bold text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow"><i class="fas fa-check mr-1"></i>Approve</button>
            </div>
        </form>
    </div>
</div>

<script>
function kycApp() {
    return {
        sidebarOpen: window.innerWidth >= 768,
        modal: false, loading: false, curId: null, curName: '', kyc: null,
        openKyc(id, name) {
            this.curId = id; this.curName = name; this.kyc = null; this.modal = true; this.loading = true;
            fetch('kyc_pending.php?ajax=kyc&uid=' + id).then(r => r.json()).then(d => { this.kyc = d; this.loading = false; }).catch(() => { this.loading = false; });
        }
    }
}
</script>
</body>
</html>
