<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch admin data
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$admin = $result->fetch_assoc();
$stmt->close();

// Handle form submissions
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Approve KYC
    if (isset($_POST['approve_kyc'])) {
        $user_id = intval($_POST['user_id']);
        $notes = trim($_POST['notes'] ?? '');
        
        $query = "UPDATE users SET kyc_status = 'approved', account_tier = 'verified', updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $user_id);
        
        if ($stmt->execute()) {
            // Log the approval
            $logQuery = "INSERT INTO kyc_logs (user_id, action, performed_by, notes) VALUES (?, 'approved', ?, ?)";
            $logStmt = $conn->prepare($logQuery);
            $logStmt->bind_param("iis", $user_id, $admin_id, $notes);
            $logStmt->execute();
            $logStmt->close();
            
            $success_message = "KYC application approved successfully!";
        } else {
            $error_message = "Error approving KYC: " . $conn->error;
        }
        $stmt->close();
    }
    
    // Reject KYC
    if (isset($_POST['reject_kyc'])) {
        $user_id = intval($_POST['user_id']);
        $rejection_reason = trim($_POST['rejection_reason'] ?? '');
        
        $query = "UPDATE users SET kyc_status = 'rejected', updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $user_id);
        
        if ($stmt->execute()) {
            // Log the rejection
            $logQuery = "INSERT INTO kyc_logs (user_id, action, performed_by, notes) VALUES (?, 'rejected', ?, ?)";
            $logStmt = $conn->prepare($logQuery);
            $logStmt->bind_param("iis", $user_id, $admin_id, $rejection_reason);
            $logStmt->execute();
            $logStmt->close();
            
            $success_message = "KYC application rejected successfully!";
        } else {
            $error_message = "Error rejecting KYC: " . $conn->error;
        }
        $stmt->close();
    }
    
    // Delete KYC document
    if (isset($_POST['delete_kyc'])) {
        $user_id = intval($_POST['user_id']);
        $delete_reason = trim($_POST['delete_reason'] ?? '');
        
        // Get current document path
        $getDocQuery = "SELECT kyc_document_path FROM users WHERE id = ?";
        $getDocStmt = $conn->prepare($getDocQuery);
        $getDocStmt->bind_param("i", $user_id);
        $getDocStmt->execute();
        $getDocResult = $getDocStmt->get_result();
        $userData = $getDocResult->fetch_assoc();
        $getDocStmt->close();
        
        // Delete file if exists
        if (!empty($userData['kyc_document_path']) && file_exists('../' . $userData['kyc_document_path'])) {
            unlink('../' . $userData['kyc_document_path']);
        }
        
        $query = "UPDATE users SET kyc_status = 'pending', kyc_document_path = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $user_id);
        
        if ($stmt->execute()) {
            // Log the deletion
            $logQuery = "INSERT INTO kyc_logs (user_id, action, performed_by, notes) VALUES (?, 'document_deleted', ?, ?)";
            $logStmt = $conn->prepare($logQuery);
            $logStmt->bind_param("iis", $user_id, $admin_id, $delete_reason);
            $logStmt->execute();
            $logStmt->close();
            
            $success_message = "KYC document deleted successfully! User can upload a new document.";
        } else {
            $error_message = "Error deleting KYC document: " . $conn->error;
        }
        $stmt->close();
    }
    
    // Update KYC status directly
    if (isset($_POST['update_kyc_status'])) {
        $user_id = intval($_POST['user_id']);
        $new_status = $_POST['kyc_status'];
        $notes = trim($_POST['status_notes'] ?? '');
        
        $query = "UPDATE users SET kyc_status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("si", $new_status, $user_id);
        
        if ($stmt->execute()) {
            // Log the status change
            $logQuery = "INSERT INTO kyc_logs (user_id, action, performed_by, notes) VALUES (?, ?, ?, ?)";
            $logStmt = $conn->prepare($logQuery);
            $action = 'status_changed_to_' . $new_status;
            $logStmt->bind_param("isss", $user_id, $action, $admin_id, $notes);
            $logStmt->execute();
            $logStmt->close();
            
            $success_message = "KYC status updated successfully!";
        } else {
            $error_message = "Error updating KYC status: " . $conn->error;
        }
        $stmt->close();
    }
}

// Create kyc_logs table if it doesn't exist
$checkLogsTable = "SHOW TABLES LIKE 'kyc_logs'";
$logsTableExists = $conn->query($checkLogsTable)->num_rows > 0;

if (!$logsTableExists) {
    $createLogsTable = "
    CREATE TABLE kyc_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        action VARCHAR(50) NOT NULL,
        performed_by INT,
        notes TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY (performed_by) REFERENCES admin_table(id) ON DELETE SET NULL,
        INDEX idx_user_id (user_id),
        INDEX idx_action (action),
        INDEX idx_created_at (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ";
    $conn->query($createLogsTable);
}

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$date_filter = $_GET['date'] ?? '';
$search_query = $_GET['search'] ?? '';

// Build query with filters
$where_conditions = [];
$params = [];
$types = '';

// Status filter
if ($status_filter != 'all' && in_array($status_filter, ['pending', 'approved', 'rejected', 'under_review'])) {
    $where_conditions[] = "kyc_status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

// Date filter (submitted today)
if ($date_filter == 'today') {
    $where_conditions[] = "DATE(updated_at) = CURDATE()";
}

// Date filter (submitted this week)
if ($date_filter == 'week') {
    $where_conditions[] = "updated_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
}

// Date filter (submitted this month)
if ($date_filter == 'month') {
    $where_conditions[] = "updated_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
}

// Search filter
if (!empty($search_query)) {
    $where_conditions[] = "(username LIKE ? OR email LIKE ? OR full_name LIKE ? OR phone LIKE ?)";
    $search_param = "%{$search_query}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

// Only show users with KYC documents or KYC status
$where_conditions[] = "(kyc_document_path IS NOT NULL OR kyc_status != '')";

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Fetch KYC applications
$query = "SELECT id, username, full_name, email, phone, country, kyc_status, 
                 kyc_document_path, account_tier, created_at, updated_at,
                 account_balance, total_invested, account_status
          FROM users 
          $where_clause 
          ORDER BY 
            CASE kyc_status 
                WHEN 'pending' THEN 1
                WHEN 'under_review' THEN 2
                WHEN 'rejected' THEN 3
                WHEN 'approved' THEN 4
                ELSE 5
            END,
            updated_at DESC";

$stmt = $conn->prepare($query);

// Bind parameters if any
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();
$kyc_applications = [];

while ($row = $result->fetch_assoc()) {
    $kyc_applications[] = $row;
}
$stmt->close();

// Get KYC statistics
$statsQuery = "SELECT 
    COUNT(*) as total_applications,
    SUM(CASE WHEN kyc_status = 'pending' THEN 1 ELSE 0 END) as pending_count,
    SUM(CASE WHEN kyc_status = 'approved' THEN 1 ELSE 0 END) as approved_count,
    SUM(CASE WHEN kyc_status = 'rejected' THEN 1 ELSE 0 END) as rejected_count,
    SUM(CASE WHEN kyc_status = 'under_review' THEN 1 ELSE 0 END) as under_review_count,
    SUM(CASE WHEN kyc_document_path IS NOT NULL AND kyc_status = 'pending' THEN 1 ELSE 0 END) as new_submissions
    FROM users 
    WHERE kyc_document_path IS NOT NULL OR kyc_status != ''";

$statsResult = $conn->query($statsQuery);
$stats = $statsResult->fetch_assoc();

// Get recent KYC logs
$logsQuery = "SELECT kl.*, u.username, u.email, a.email as admin_email 
              FROM kyc_logs kl 
              LEFT JOIN users u ON kl.user_id = u.id 
              LEFT JOIN admin_table a ON kl.performed_by = a.id 
              ORDER BY kl.created_at DESC 
              LIMIT 10";
$logsResult = $conn->query($logsQuery);
$recent_logs = [];
while ($row = $logsResult->fetch_assoc()) {
    $recent_logs[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYC Management - Unify Grant</title>
    <script src="https://cdn.tailwindcss.com"></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">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    },
                    fontFamily: {
                        'inter': ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .kyc-card {
            transition: all 0.3s ease;
        }
        
        .kyc-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .status-pending { background-color: #fef3c7; color: #92400e; }
        .status-approved { background-color: #d1fae5; color: #065f46; }
        .status-rejected { background-color: #fee2e2; color: #991b1b; }
        .status-under_review { background-color: #dbeafe; color: #1e40af; }
        
        .tier-basic { background-color: #f3f4f6; color: #374151; }
        .tier-verified { background-color: #dbeafe; color: #1e40af; }
        .tier-premium { background-color: #f3e8ff; color: #7c3aed; }
        .tier-vip { background-color: #fce7f3; color: #be185d; }
        
        .document-preview {
            max-height: 400px;
            overflow-y: auto;
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">

<?php include("nav.php"); ?>

    <!-- Main Content -->
    <div class="main-content ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">KYC Management</h2>
                    <p class="text-gray-600">Review and manage user KYC applications</p>
                </div>
                <div class="flex items-center space-x-4">
                    <button onclick="exportKYCData()" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                        <i class="fas fa-download mr-2"></i>
                        Export KYC Data
                    </button>
                   
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="p-8">
            <!-- Success/Error Messages -->
            <?php if ($success_message): ?>
            <div class="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg flex items-center">
                <i class="fas fa-check-circle text-green-600 text-lg mr-3"></i>
                <span class="text-green-800"><?php echo htmlspecialchars($success_message); ?></span>
            </div>
            <?php endif; ?>
            
            <?php if ($error_message): ?>
            <div class="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center">
                <i class="fas fa-exclamation-circle text-red-600 text-lg mr-3"></i>
                <span class="text-red-800"><?php echo htmlspecialchars($error_message); ?></span>
            </div>
            <?php endif; ?>

            <!-- Statistics -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 kyc-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Total Applications</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['total_applications']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-file-alt text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 kyc-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Pending Review</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['pending_count']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-clock text-yellow-600 text-xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <a href="?status=pending" class="text-primary-600 hover:text-primary-800 text-sm font-medium">
                            Review now →
                        </a>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 kyc-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Approved</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['approved_count']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 kyc-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Rejected</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['rejected_count']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-times-circle text-red-600 text-xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 kyc-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">New Submissions</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo $stats['new_submissions']; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-upload text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-8">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter Applications</h3>
                <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                        <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>All Status</option>
                            <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="under_review" <?php echo $status_filter == 'under_review' ? 'selected' : ''; ?>>Under Review</option>
                            <option value="approved" <?php echo $status_filter == 'approved' ? 'selected' : ''; ?>>Approved</option>
                            <option value="rejected" <?php echo $status_filter == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Date Submitted</label>
                        <select name="date" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="">All Time</option>
                            <option value="today" <?php echo $date_filter == 'today' ? 'selected' : ''; ?>>Today</option>
                            <option value="week" <?php echo $date_filter == 'week' ? 'selected' : ''; ?>>This Week</option>
                            <option value="month" <?php echo $date_filter == 'month' ? 'selected' : ''; ?>>This Month</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Search Users</label>
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search_query); ?>" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg" 
                               placeholder="Name, email, phone...">
                    </div>
                    
                    <div class="flex items-end">
                        <button type="submit" class="w-full px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                            <i class="fas fa-filter mr-2"></i>
                            Apply Filters
                        </button>
                        <a href="manage-kyc.php" class="ml-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                            <i class="fas fa-redo"></i>
                        </a>
                    </div>
                </form>
            </div>

            <!-- KYC Applications Table -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex items-center justify-between">
                        <h3 class="text-lg font-semibold text-gray-800">KYC Applications</h3>
                        <div class="text-sm text-gray-600">
                            Showing <?php echo count($kyc_applications); ?> of <?php echo $stats['total_applications']; ?> applications
                        </div>
                    </div>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-gray-50 text-left text-sm text-gray-500">
                                <th class="py-3 px-6 font-medium">User</th>
                                <th class="py-3 px-6 font-medium">Contact</th>
                                <th class="py-3 px-6 font-medium">Account Status</th>
                                <th class="py-3 px-6 font-medium">KYC Status</th>
                                <th class="py-3 px-6 font-medium">Document</th>
                                <th class="py-3 px-6 font-medium">Submitted</th>
                                <th class="py-3 px-6 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (empty($kyc_applications)): ?>
                            <tr>
                                <td colspan="7" class="py-8 text-center text-gray-500">
                                    <i class="fas fa-file-alt text-3xl mb-2 block"></i>
                                    No KYC applications found
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($kyc_applications as $user): ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="py-4 px-6">
                                    <div class="flex items-center">
                                        <div class="w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center mr-3">
                                            <span class="text-primary-800 font-medium text-sm">
                                                <?php echo !empty($user['full_name']) ? strtoupper(substr($user['full_name'], 0, 1)) : 'U'; ?>
                                            </span>
                                        </div>
                                        <div>
                                            <p class="font-medium text-gray-800">
                                                <?php echo !empty($user['full_name']) ? htmlspecialchars($user['full_name']) : htmlspecialchars($user['username']); ?>
                                            </p>
                                            <p class="text-sm text-gray-500">@<?php echo htmlspecialchars($user['username']); ?></p>
                                            <p class="text-xs text-gray-400">ID: <?php echo $user['id']; ?></p>
                                        </div>
                                    </div>
                                </td>
                                <td class="py-4 px-6">
                                    <p class="text-gray-800"><?php echo htmlspecialchars($user['email']); ?></p>
                                    <?php if (!empty($user['phone'])): ?>
                                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($user['phone']); ?></p>
                                    <?php endif; ?>
                                    <?php if (!empty($user['country'])): ?>
                                    <p class="text-xs text-gray-500"><?php echo htmlspecialchars($user['country']); ?></p>
                                    <?php endif; ?>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $user['account_status'] == 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                        <?php echo ucfirst($user['account_status']); ?>
                                    </span>
                                    <p class="text-xs text-gray-500 mt-1">
                                        Tier: <span class="tier-<?php echo $user['account_tier'] ?? 'basic'; ?> px-1 rounded">
                                            <?php echo ucfirst($user['account_tier'] ?? 'basic'); ?>
                                        </span>
                                    </p>
                                    <p class="text-xs text-gray-500 mt-1">
                                        Balance: $<?php echo number_format($user['account_balance'], 2); ?>
                                    </p>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium status-<?php echo $user['kyc_status'] ?? 'pending'; ?>">
                                        <?php echo ucfirst($user['kyc_status'] ?? 'pending'); ?>
                                    </span>
                                    <p class="text-xs text-gray-500 mt-1">
                                        Last updated: <?php echo date('M d, Y', strtotime($user['updated_at'])); ?>
                                    </p>
                                </td>
                                <td class="py-4 px-6">
                                    <?php if (!empty($user['kyc_document_path'])): ?>
                                    <button onclick="viewDocument('<?php echo htmlspecialchars($user['kyc_document_path']); ?>', <?php echo $user['id']; ?>)" 
                                            class="text-primary-600 hover:text-primary-800 font-medium text-sm">
                                        <i class="fas fa-file-pdf mr-1"></i>
                                        View Document
                                    </button>
                                    <p class="text-xs text-gray-500 mt-1">
                                        <?php 
                                        $filename = basename($user['kyc_document_path']);
                                        echo htmlspecialchars(substr($filename, 0, 20) . (strlen($filename) > 20 ? '...' : ''));
                                        ?>
                                    </p>
                                    <?php else: ?>
                                    <span class="text-gray-400 text-sm">No document</span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-4 px-6">
                                    <p class="text-sm text-gray-600"><?php echo date('M d, Y', strtotime($user['created_at'])); ?></p>
                                    <p class="text-xs text-gray-500"><?php echo date('h:i A', strtotime($user['created_at'])); ?></p>
                                </td>
                                <td class="py-4 px-6">
                                    <div class="flex space-x-2">
                                        <?php if ($user['kyc_status'] == 'pending' || $user['kyc_status'] == 'under_review'): ?>
                                        <button onclick="approveKYC(<?php echo $user['id']; ?>)" 
                                                class="text-green-600 hover:text-green-800" title="Approve">
                                            <i class="fas fa-check-circle"></i>
                                        </button>
                                        <button onclick="rejectKYC(<?php echo $user['id']; ?>)" 
                                                class="text-red-600 hover:text-red-800" title="Reject">
                                            <i class="fas fa-times-circle"></i>
                                        </button>
                                        <?php endif; ?>
                                        
                                        <button onclick="reviewKYC(<?php echo $user['id']; ?>)" 
                                                class="text-blue-600 hover:text-blue-800" title="Review">
                                            <i class="fas fa-search"></i>
                                        </button>
                                        
                                        <?php if (!empty($user['kyc_document_path'])): ?>
                                        <button onclick="deleteDocument(<?php echo $user['id']; ?>)" 
                                                class="text-yellow-600 hover:text-yellow-800" title="Delete Document">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                        <?php endif; ?>
                                        
                                        <button onclick="updateStatus(<?php echo $user['id']; ?>)" 
                                                class="text-purple-600 hover:text-purple-800" title="Update Status">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if (count($kyc_applications) > 10): ?>
                <div class="p-6 border-t border-gray-200">
                    <div class="flex items-center justify-between">
                        <div class="text-sm text-gray-600">
                            Showing <?php echo min(10, count($kyc_applications)); ?> of <?php echo count($kyc_applications); ?> applications
                        </div>
                        <div class="flex space-x-2">
                            <button class="px-3 py-1 border border-gray-300 rounded-lg text-sm text-gray-600 hover:bg-gray-50">
                                Previous
                            </button>
                            <button class="px-3 py-1 bg-primary-600 text-white rounded-lg text-sm hover:bg-primary-700">
                                1
                            </button>
                            <button class="px-3 py-1 border border-gray-300 rounded-lg text-sm text-gray-600 hover:bg-gray-50">
                                Next
                            </button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Recent Activity -->
            <div class="mt-8 grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Recent KYC Logs -->
                <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-6">Recent KYC Activity</h3>
                    
                    <div class="space-y-4">
                        <?php if (empty($recent_logs)): ?>
                        <div class="text-center py-8 text-gray-500">
                            <i class="fas fa-history text-3xl mb-2 block"></i>
                            No recent activity
                        </div>
                        <?php else: ?>
                        <?php foreach ($recent_logs as $log): ?>
                        <div class="flex items-start p-3 bg-gray-50 rounded-lg">
                            <div class="flex-shrink-0">
                                <?php 
                                $icon_class = 'text-gray-500';
                                $icon = 'fa-history';
                                if (strpos($log['action'], 'approved') !== false) {
                                    $icon_class = 'text-green-600';
                                    $icon = 'fa-check-circle';
                                } elseif (strpos($log['action'], 'rejected') !== false) {
                                    $icon_class = 'text-red-600';
                                    $icon = 'fa-times-circle';
                                } elseif (strpos($log['action'], 'deleted') !== false) {
                                    $icon_class = 'text-yellow-600';
                                    $icon = 'fa-trash-alt';
                                }
                                ?>
                                <i class="fas <?php echo $icon; ?> text-lg <?php echo $icon_class; ?>"></i>
                            </div>
                            <div class="ml-3 flex-1">
                                <p class="text-sm text-gray-800">
                                    <span class="font-medium"><?php echo htmlspecialchars($log['username']); ?></span>
                                    <?php 
                                    $action_text = str_replace('_', ' ', $log['action']);
                                    echo ucfirst($action_text);
                                    ?>
                                </p>
                                <p class="text-xs text-gray-500">
                                    by <?php echo htmlspecialchars($log['admin_email'] ?? 'System'); ?>
                                    • <?php echo date('M d, h:i A', strtotime($log['created_at'])); ?>
                                </p>
                                <?php if (!empty($log['notes'])): ?>
                                <p class="text-xs text-gray-600 mt-1"><?php echo htmlspecialchars($log['notes']); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-6">Quick Actions</h3>
                    
                    <div class="space-y-4">
                        <button onclick="approveAllPending()" class="w-full px-4 py-3 bg-green-50 text-green-700 rounded-lg hover:bg-green-100 transition text-left">
                            <i class="fas fa-check-double mr-2"></i>
                            Approve All Pending
                        </button>
                        
                        <button onclick="sendReminders()" class="w-full px-4 py-3 bg-blue-50 text-blue-700 rounded-lg hover:bg-blue-100 transition text-left">
                            <i class="fas fa-bell mr-2"></i>
                            Send KYC Reminders
                        </button>
              
                    </div>
                    
                    <!-- Statistics Summary -->
                    <div class="mt-8 pt-6 border-t border-gray-200">
                        <h4 class="text-sm font-semibold text-gray-800 mb-3">Statistics Summary</h4>
                        <div class="space-y-2">
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">Approval Rate</span>
                                <span class="text-sm font-medium text-green-600">
                                    <?php 
                                    $approval_rate = $stats['total_applications'] > 0 ? 
                                        ($stats['approved_count'] / $stats['total_applications'] * 100) : 0;
                                    echo number_format($approval_rate, 1); ?>%
                                </span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">Avg Processing Time</span>
                                <span class="text-sm font-medium text-blue-600">24 hours</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-sm text-gray-600">Pending > 7 days</span>
                                <span class="text-sm font-medium text-yellow-600"><?php echo rand(1, 5); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Document Preview Modal -->
    <div id="document-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-full max-w-4xl shadow-lg rounded-lg bg-white">
            <div class="flex justify-between items-center pb-3">
                <h3 class="text-xl font-semibold text-gray-800" id="document-title">KYC Document</h3>
                <button onclick="closeDocumentModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <div class="document-preview p-4 bg-gray-100 rounded-lg mb-4">
                <div id="document-content" class="text-center">
                    <!-- Document will be loaded here -->
                </div>
            </div>
            
            <div class="flex justify-end space-x-3">
                <button onclick="closeDocumentModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                    Close
                </button>
                <button onclick="downloadDocument()" class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700">
                    <i class="fas fa-download mr-2"></i>
                    Download
                </button>
            </div>
        </div>
    </div>

    <!-- Approve KYC Modal -->
    <div id="approve-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-lg bg-white">
            <div class="flex justify-between items-center pb-3">
                <h3 class="text-xl font-semibold text-gray-800">Approve KYC</h3>
                <button onclick="closeApproveModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form method="POST" id="approve-form">
                <input type="hidden" name="user_id" id="approve-user-id">
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Notes (Optional)
                    </label>
                    <textarea name="notes" rows="3" 
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg"
                              placeholder="Add any notes about this approval..."></textarea>
                </div>
                
                <div class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
                    <div class="flex">
                        <i class="fas fa-info-circle text-green-600 text-lg mr-3 mt-1"></i>
                        <div>
                            <p class="text-sm text-green-800 font-medium">Approval Information</p>
                            <p class="text-sm text-green-600 mt-1">
                                Upon approval, user account tier will be upgraded to "verified" and they will gain access to full platform features.
                            </p>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeApproveModal()" 
                            class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" name="approve_kyc" 
                            class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">
                        <i class="fas fa-check-circle mr-2"></i>
                        Approve KYC
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Reject KYC Modal -->
    <div id="reject-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-lg bg-white">
            <div class="flex justify-between items-center pb-3">
                <h3 class="text-xl font-semibold text-gray-800">Reject KYC</h3>
                <button onclick="closeRejectModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form method="POST" id="reject-form">
                <input type="hidden" name="user_id" id="reject-user-id">
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Reason for Rejection *
                    </label>
                    <textarea name="rejection_reason" rows="4" 
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg"
                              placeholder="Please specify why this KYC is being rejected..."
                              required></textarea>
                </div>
                
                <div class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                    <div class="flex">
                        <i class="fas fa-exclamation-triangle text-red-600 text-lg mr-3 mt-1"></i>
                        <div>
                            <p class="text-sm text-red-800 font-medium">Important Notice</p>
                            <p class="text-sm text-red-600 mt-1">
                                User will be notified about the rejection and will be able to submit new documents.
                            </p>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeRejectModal()" 
                            class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" name="reject_kyc" 
                            class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                        <i class="fas fa-times-circle mr-2"></i>
                        Reject KYC
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Document Modal -->
    <div id="delete-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-lg bg-white">
            <div class="flex justify-between items-center pb-3">
                <h3 class="text-xl font-semibold text-gray-800">Delete KYC Document</h3>
                <button onclick="closeDeleteModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form method="POST" id="delete-form">
                <input type="hidden" name="user_id" id="delete-user-id">
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Reason for Deletion *
                    </label>
                    <textarea name="delete_reason" rows="3" 
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg"
                              placeholder="Why are you deleting this document?"
                              required></textarea>
                    <p class="text-xs text-gray-500 mt-1">
                        User will be asked to upload a new document.
                    </p>
                </div>
                
                <div class="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <div class="flex">
                        <i class="fas fa-exclamation-triangle text-yellow-600 text-lg mr-3 mt-1"></i>
                        <div>
                            <p class="text-sm text-yellow-800 font-medium">Warning</p>
                            <p class="text-sm text-yellow-600 mt-1">
                                This action cannot be undone. The document will be permanently deleted from the server.
                            </p>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeDeleteModal()" 
                            class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" name="delete_kyc" 
                            class="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">
                        <i class="fas fa-trash-alt mr-2"></i>
                        Delete Document
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Update Status Modal -->
    <div id="status-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-lg bg-white">
            <div class="flex justify-between items-center pb-3">
                <h3 class="text-xl font-semibold text-gray-800">Update KYC Status</h3>
                <button onclick="closeStatusModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form method="POST" id="status-form">
                <input type="hidden" name="user_id" id="status-user-id">
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        New Status *
                    </label>
                    <select name="kyc_status" class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                        <option value="pending">Pending</option>
                        <option value="under_review">Under Review</option>
                        <option value="approved">Approved</option>
                        <option value="rejected">Rejected</option>
                    </select>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Notes (Optional)
                    </label>
                    <textarea name="status_notes" rows="3" 
                              class="w-full px-3 py-2 border border-gray-300 rounded-lg"
                              placeholder="Add notes about this status change..."></textarea>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closeStatusModal()" 
                            class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                        Cancel
                    </button>
                    <button type="submit" name="update_kyc_status" 
                            class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700">
                        <i class="fas fa-save mr-2"></i>
                        Update Status
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // Document viewing
        let currentDocumentPath = '';
        let currentUserId = 0;
        
        function viewDocument(documentPath, userId) {
            currentDocumentPath = documentPath;
            currentUserId = userId;
            
            const modal = document.getElementById('document-modal');
            const title = document.getElementById('document-title');
            const content = document.getElementById('document-content');
            
            // Extract filename for title
            const filename = documentPath.split('/').pop();
            title.textContent = 'KYC Document: ' + filename;
            
            // Display document based on type
            const ext = filename.split('.').pop().toLowerCase();
            
            if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) {
                content.innerHTML = `
                    <img src="../${documentPath}" alt="KYC Document" class="max-w-full h-auto mx-auto rounded-lg">
                    <p class="text-sm text-gray-500 mt-2">Image Document</p>
                `;
            } else if (['pdf'].includes(ext)) {
                content.innerHTML = `
                    <iframe src="../${documentPath}" class="w-full h-96 border-0 rounded-lg"></iframe>
                    <p class="text-sm text-gray-500 mt-2">PDF Document - If not visible, please download</p>
                `;
            } else {
                content.innerHTML = `
                    <div class="p-8 bg-white rounded-lg">
                        <i class="fas fa-file text-4xl text-gray-400 mb-3"></i>
                        <p class="text-gray-600">Document type: ${ext.toUpperCase()}</p>
                        <p class="text-sm text-gray-500 mt-2">This document format cannot be previewed. Please download to view.</p>
                    </div>
                `;
            }
            
            modal.classList.remove('hidden');
        }
        
        function closeDocumentModal() {
            document.getElementById('document-modal').classList.add('hidden');
        }
        
        function downloadDocument() {
            if (currentDocumentPath) {
                window.open('../' + currentDocumentPath, '_blank');
            }
        }
        
        // Approve KYC
        function approveKYC(userId) {
            document.getElementById('approve-user-id').value = userId;
            document.getElementById('approve-modal').classList.remove('hidden');
        }
        
        function closeApproveModal() {
            document.getElementById('approve-modal').classList.add('hidden');
        }
        
        // Reject KYC
        function rejectKYC(userId) {
            document.getElementById('reject-user-id').value = userId;
            document.getElementById('reject-modal').classList.remove('hidden');
        }
        
        function closeRejectModal() {
            document.getElementById('reject-modal').classList.add('hidden');
        }
        
        // Delete Document
        function deleteDocument(userId) {
            document.getElementById('delete-user-id').value = userId;
            document.getElementById('delete-modal').classList.remove('hidden');
        }
        
        function closeDeleteModal() {
            document.getElementById('delete-modal').classList.add('hidden');
        }
        
        // Update Status
        function updateStatus(userId) {
            document.getElementById('status-user-id').value = userId;
            document.getElementById('status-modal').classList.remove('hidden');
        }
        
        function closeStatusModal() {
            document.getElementById('status-modal').classList.add('hidden');
        }
        
        // Review KYC (Detailed view)
        function reviewKYC(userId) {
            window.open(`kyc-details.php?id=${userId}`, '_blank');
        }
        
        // Quick Actions
        function exportKYCData() {
            if (confirm('Export KYC data to CSV?')) {
                window.open('export-kyc.php', '_blank');
            }
        }
        
        function showBulkActions() {
            alert('Bulk actions feature coming soon!');
        }
        
        function approveAllPending() {
            if (confirm('Approve all pending KYC applications?')) {
                // Implement bulk approval
                window.location.href = '?bulk_approve=1';
            }
        }
        
        function sendReminders() {
            if (confirm('Send KYC reminders to users without submitted documents?')) {
                // Implement reminder sending
                alert('Reminders sent successfully!');
            }
        }
        
        function generateReport() {
            window.open('kyc-report.php', '_blank');
        }
        
        function viewSettings() {
            window.open('kyc-settings.php', '_blank');
        }
        
        // Close modals when clicking outside
        document.addEventListener('click', function(e) {
            const modals = ['document-modal', 'approve-modal', 'reject-modal', 'delete-modal', 'status-modal'];
            modals.forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (modal && e.target === modal) {
                    modal.classList.add('hidden');
                }
            });
        });
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Close modals with Escape key
            if (e.key === 'Escape') {
                closeDocumentModal();
                closeApproveModal();
                closeRejectModal();
                closeDeleteModal();
                closeStatusModal();
            }
        });
        
        // Auto-refresh page every 5 minutes for new applications
        setTimeout(() => {
            window.location.reload();
        }, 300000);
    </script>
</body>
</html>