<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();
$db = getDB();

// Process KYC
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['process_kyc'])) {
    $docId = intval($_POST['document_id']);
    $action = $_POST['kyc_action']; // approve or reject
    $notes = trim($_POST['admin_notes'] ?? '');
    
    // FIX: Using status values that match the ENUM defined in the DB schema ('verified' or 'rejected')
    $newStatus = $action === 'approve' ? 'verified' : 'rejected';
    
    // FIX: Column 'rejection_reason' used instead of non-existent 'admin_notes'
    $stmt = $db->prepare("UPDATE kyc_documents SET status = ?, rejection_reason = ?, reviewed_by = ?, reviewed_at = NOW() WHERE id = ?");
    $stmt->bind_param('ssii', $newStatus, $notes, $admin['id'], $docId);
    $stmt->execute();
    
    // FIX: Modified query parameters to match columns present in database layout
    $doc = $db->query("SELECT user_id, document_type, document_path FROM kyc_documents WHERE id = $docId")->fetch_assoc();
    
    if ($doc) {
        // FIX: Removed non-existent kyc_admin_notes, kyc_reviewed_by, kyc_reviewed_at updates
        $stmt = $db->prepare("UPDATE users SET kyc_status = ? WHERE id = ?");
        $stmt->bind_param('si', $newStatus, $doc['user_id']);
        $stmt->execute();
        
        // Notification
        createNotification($doc['user_id'], 'KYC ' . ucfirst($newStatus), 
            'Your KYC document (' . e(str_replace('_', ' ', $doc['document_type'])) . ') has been ' . $newStatus . '.' . ($notes ? ' Reason/Notes: ' . $notes : ''),
            $action === 'approve' ? 'success' : 'warning'
        );
        
        setFlash('KYC document processed as ' . $newStatus . ' successfully!', 'success');
        header('Location: kyc.php');
        exit();
    }
}

$statusFilter = $_GET['status'] ?? '';

// FIX: Sorting and filtering by 'created_at' since 'uploaded_at' does not exist
if ($statusFilter) {
    // Treat 'approved' as 'verified' in filter requests to map properly with database backend configuration
    $dbStatus = $statusFilter === 'approved' ? 'verified' : $statusFilter;
    $stmt = $db->prepare("SELECT k.*, u.first_name, u.last_name, u.email, u.kyc_status as user_kyc_status FROM kyc_documents k JOIN users u ON k.user_id = u.id WHERE k.status = ? ORDER BY k.created_at DESC");
    $stmt->bind_param('s', $dbStatus);
    $stmt->execute();
    $documents = $stmt->get_result();
} else {
    $documents = $db->query("SELECT k.*, u.first_name, u.last_name, u.email, u.kyc_status as user_kyc_status FROM kyc_documents k JOIN users u ON k.user_id = u.id ORDER BY k.created_at DESC");
}

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYC Verification - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <div class="tabs">
                <a href="kyc.php" class="tab-btn <?php echo $statusFilter === '' ? 'active' : ''; ?>">All</a>
                <a href="?status=pending" class="tab-btn <?php echo $statusFilter === 'pending' ? 'active' : ''; ?>">Pending</a>
                <a href="?status=approved" class="tab-btn <?php echo $statusFilter === 'approved' ? 'active' : ''; ?>">Approved (Verified)</a>
                <a href="?status=rejected" class="tab-btn <?php echo $statusFilter === 'rejected' ? 'active' : ''; ?>">Rejected</a>
            </div>
            
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Document File</th>
                                    <th>Type</th>
                                    <th>Status</th>
                                    <th>Rejection Reason / Notes</th>
                                    <th>Uploaded At</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($documents && $documents->num_rows > 0): ?>
                                    <?php while ($doc = $documents->fetch_assoc()): ?>
                                        <tr>
                                            <td>
                                                <div style="font-weight: 600; font-size: 13px;"><?php echo e($doc['first_name'] . ' ' . $doc['last_name']); ?></div>
                                                <div style="font-size: 11px; color: var(--gray);"><?php echo e($doc['email']); ?></div>
                                            </td>
                                            <td>
                                                <a href="../<?php echo e($doc['document_path']); ?>" target="_blank" style="color: var(--primary); font-weight: 600; font-size: 13px;">
                                                    📄 View Document
                                                </a>
                                            </td>
                                            <td><span style="text-transform: capitalize;"><?php echo str_replace('_', ' ', e($doc['document_type'])); ?></span></td>
                                            <td>
                                                <span class="kyc-status <?php echo e($doc['status']); ?>">
                                                    <?php echo $doc['status'] === 'verified' ? 'Approved' : ucfirst(e($doc['status'])); ?>
                                                </span>
                                            </td>
                                            <td style="font-size: 12px;"><?php echo e($doc['rejection_reason'] ?? '-'); ?></td>
                                            <td style="font-size: 12px;"><?php echo formatDateShort($doc['created_at']); ?></td>
                                            <td>
                                                <?php if ($doc['status'] === 'pending' || $doc['status'] === 'under_review'): ?>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="openModal('modal-kyc-<?php echo $doc['id']; ?>')">Review</button>
                                                <?php else: ?>
                                                    <span style="font-size: 12px; color: var(--gray);">Reviewed</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="7" class="text-center" style="padding: 40px; color: var(--gray);">No KYC documents found</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php 
    if ($documents && $documents->num_rows > 0):
        $documents->data_seek(0);
        while ($doc = $documents->fetch_assoc()): 
            if ($doc['status'] !== 'pending' && $doc['status'] !== 'under_review') continue;
    ?>
    <div class="modal-overlay" id="modal-kyc-<?php echo $doc['id']; ?>">
        <div class="modal">
            <div class="modal-header">
                <span class="modal-title">Review KYC Document</span>
                <button class="modal-close" onclick="closeModal('modal-kyc-<?php echo $doc['id']; ?>')">✕</button>
            </div>
            <div class="modal-body">
                <div style="margin-bottom: 20px;">
                    <div style="font-size: 13px; margin-bottom: 8px;"><strong>User:</strong> <?php echo e($doc['first_name'] . ' ' . $doc['last_name']); ?> (<?php echo e($doc['email']); ?>)</div>
                    <div style="font-size: 13px; margin-bottom: 8px;"><strong>Document:</strong> <a href="../<?php echo e($doc['document_path']); ?>" target="_blank" style="color: var(--primary);">View File Link</a></div>
                    <div style="font-size: 13px;"><strong>Type:</strong> <?php echo str_replace('_', ' ', e($doc['document_type'])); ?></div>
                </div>
                
                <iframe src="../<?php echo e($doc['document_path']); ?>" style="width: 100%; height: 300px; border: 1px solid var(--gray-200); border-radius: var(--border-radius); margin-bottom: 20px;"></iframe>
                
                <form method="POST" action="">
                    <input type="hidden" name="document_id" value="<?php echo $doc['id']; ?>">
                    <input type="hidden" name="process_kyc" value="1">
                    
                    <div class="form-group">
                        <label class="form-label">Review Notes / Reason for rejection</label>
                        <textarea name="admin_notes" class="form-control" rows="3" placeholder="Add notes or reason if rejecting..."></textarea>
                    </div>
                    
                    <div class="modal-footer" style="padding: 16px 0 0 0; border: none;">
                        <button type="button" class="btn btn-secondary" onclick="closeModal('modal-kyc-<?php echo $doc['id']; ?>')">Cancel</button>
                        <button type="submit" name="kyc_action" value="reject" class="btn btn-danger">Reject</button>
                        <button type="submit" name="kyc_action" value="approve" class="btn btn-success">Approve & Verify</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php 
        endwhile;
    endif; 
    ?>
    
    <script src="../assets/js/main.js"></script>
</body>
</html>
