<?php 
session_start();
include('includes/head.php');

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// PIN for confirmation
$admin_pin = "1234"; // Change this to a secure PIN

// Handle actions
$action = isset($_GET['action']) ? $_GET['action'] : '';
$doc_id = isset($_GET['id']) ? intval($_GET['doc_id']) : 0;
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    $target_id = isset($_POST['doc_id']) ? intval($_POST['doc_id']) : 0;
    $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'verify_document':
                $status = isset($_POST['status']) ? $_POST['status'] : '';
                $notes = isset($_POST['notes']) ? mysqli_real_escape_string($conn, $_POST['notes']) : '';
                
                if ($target_id > 0 && in_array($status, ['verified', 'pending', 'rejected'])) {
                    $sql = "UPDATE kyc_documents SET verification_status = '$status' WHERE id = $target_id";
                    if (mysqli_query($conn, $sql)) {
                        // Get document and user details for notification
                        $doc_sql = "SELECT d.*, u.username, u.email, u.first_name, u.last_name, u.status as user_status 
                                   FROM kyc_documents d 
                                   LEFT JOIN users u ON d.user_id = u.id 
                                   WHERE d.id = $target_id";
                        $doc_result = mysqli_query($conn, $doc_sql);
                        $doc_data = mysqli_fetch_assoc($doc_result);
                        
                        // Log activity
                        logAdminActivity(
                            'KYC Document Verified',
                            "Updated KYC document (ID: $target_id, Type: {$doc_data['document_type']}) status to $status for user {$doc_data['username']}. Notes: $notes",
                            'KYC',
                            $target_id,
                            'kyc_documents'
                        );
                        
                        // NOTIFICATION: KYC Document Status Update (USER)
                        $mail_subject = "KYC Verification " . ucfirst($status);
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Hello <span class='user-name'>" . $doc_data['first_name'] . "</span>,</h2>
                                            
                                            <p class='message'>
                                                " . ($status == 'verified' ? 
                                                    "✅ <strong>Good news!</strong> Your KYC document has been verified successfully." : 
                                                    ($status == 'rejected' ? 
                                                    "⚠️ <strong>Action needed.</strong> Your KYC document was not approved." : 
                                                    "📋 <strong>Your KYC document status has been updated to pending.")) . "
                                            </p>

                                            <!-- KYC Status Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Document ID:</strong> KYC-" . $target_id . "<br>
                                                    <strong>Document Type:</strong> " . ($type_labels[$doc_data['document_type']] ?? $doc_data['document_type']) . "<br>
                                                    <strong>Verification Status:</strong> 
                                                        <span style='color: " . 
                                                            ($status == 'verified' ? '#28a745' : 
                                                            ($status == 'rejected' ? '#dc3545' : '#ffc107')) . 
                                                        "; font-weight: bold;'>" . strtoupper($status) . "</span><br>
                                                    <strong>Verification Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    " . ($notes ? "<strong>Admin Notes:</strong> " . htmlspecialchars($notes) . "<br>" : "") . "
                                                    <strong>Verified By:</strong> " . $admin_name . " (Admin)
                                                </div>
                                            </div>";

                        // Add status-specific content
                        if ($status == 'verified') {
                            $mail_message .= "<!-- Verified Content -->
                                            <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #155724;'>✅ Verification Successful</h4>
                                                <p style='color: #155724;'>
                                                    Your document has been approved. You now have full access to all platform features including deposits, withdrawals, and trading bots.
                                                </p>
                                            </div>
                                            
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/dashboard.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #28a745; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                    Go to Dashboard
                                                </a>
                                            </div>";
                        } elseif ($status == 'rejected') {
                            $mail_message .= "<!-- Rejected Content -->
                                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #721c24;'>⚠️ Document Not Approved</h4>
                                                <p style='color: #721c24;'>
                                                    <strong>Reason:</strong> " . ($notes ?: 'Document could not be verified. Please submit a clear, valid document.') . "<br><br>
                                                    <strong>Next Steps:</strong> Please upload a new, clear document following our KYC guidelines.
                                                </p>
                                            </div>
                                            
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/kyc.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                    Upload New Document
                                                </a>
                                            </div>";
                        } else {
                            $mail_message .= "<!-- Pending Content -->
                                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #856404;'>⏳ Under Review</h4>
                                                <p style='color: #856404;'>
                                                    Your document is currently being reviewed by our compliance team. This usually takes 1-2 business days.
                                                </p>
                                            </div>";
                        }

                        $mail_message .= "<!-- Support Section -->
                                        <div class='support-section'>
                                            <p class='support-text'>Questions about your KYC verification?</p>
                                            <a href='" . $myUrl . "/support.php?category=kyc' class='support-link'>Contact Compliance Team</a>
                                        </div>
                                    </div>";

                        // Send user notification
                        $user_email = $doc_data['email'];
                        $first_name = $doc_data['first_name'];
                        require_once("../proccess/mail_sender.php");
                        
                        // NOTIFICATION: KYC Document Status Update (ADMIN)
                        $admin_mail_subject = "KYC Document " . ucfirst($status) . " - User: " . $doc_data['username'];
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>KYC Document Status Updated</h2>
                                                
                                                <p class='message'>
                                                    A KYC document has been processed by " . $admin_name . ".
                                                </p>

                                                <!-- Document Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Document ID:</strong> KYC-" . $target_id . "<br>
                                                        <strong>User:</strong> " . $doc_data['first_name'] . " " . $doc_data['last_name'] . " (" . $doc_data['username'] . ")<br>
                                                        <strong>User Email:</strong> " . $doc_data['email'] . "<br>
                                                        <strong>Document Type:</strong> " . ($type_labels[$doc_data['document_type']] ?? $doc_data['document_type']) . "<br>
                                                        <strong>New Status:</strong> <span style='color: " . 
                                                            ($status == 'verified' ? '#28a745' : 
                                                            ($status == 'rejected' ? '#dc3545' : '#ffc107')) . 
                                                        "; font-weight: bold;'>" . strtoupper($status) . "</span><br>
                                                        <strong>Processed By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                        <strong>Processed Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        " . ($notes ? "<strong>Admin Notes:</strong> " . htmlspecialchars($notes) . "<br>" : "") . "
                                                        <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                                    </div>
                                                </div>

                                                <!-- Admin Actions -->
                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/admin/users.php?id=" . $doc_data['user_id'] . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                        View User Profile
                                                    </a>
                                                    <a href='" . $myUrl . "/admin/kyc.php?user_id=" . $doc_data['user_id'] . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                        View User Documents
                                                    </a>
                                                </div>
                                            </div>";

                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "Document status updated successfully!";
                    } else {
                        $error = "Failed to update document status.";
                    }
                }
                break;
                
            case 'bulk_verify':
                $doc_ids = isset($_POST['doc_ids']) ? $_POST['doc_ids'] : array();
                $bulk_status = isset($_POST['bulk_status']) ? $_POST['bulk_status'] : '';
                
                if (!empty($doc_ids) && in_array($bulk_status, ['verified', 'pending', 'rejected'])) {
                    $id_list = implode(',', array_map('intval', $doc_ids));
                    $sql = "UPDATE kyc_documents SET verification_status = '$bulk_status' WHERE id IN ($id_list)";
                    
                    if (mysqli_query($conn, $sql)) {
                        // Log activity
                        logAdminActivity(
                            'Bulk KYC Verification',
                            "Updated $bulk_status status for " . count($doc_ids) . " KYC documents",
                            'KYC',
                            null,
                            'kyc_documents'
                        );
                        
                        // NOTIFICATION: Bulk KYC Update (ADMIN)
                        $admin_mail_subject = "Bulk KYC Documents Updated - " . ucfirst($bulk_status);
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Bulk KYC Update Completed</h2>
                                                
                                                <p class='message'>
                                                    " . count($doc_ids) . " KYC documents have been updated in bulk by " . $admin_name . ".
                                                </p>

                                                <!-- Bulk Update Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Action:</strong> Bulk Status Update<br>
                                                        <strong>New Status:</strong> <span style='color: " . 
                                                            ($bulk_status == 'verified' ? '#28a745' : 
                                                            ($bulk_status == 'rejected' ? '#dc3545' : '#ffc107')) . 
                                                        "; font-weight: bold;'>" . strtoupper($bulk_status) . "</span><br>
                                                        <strong>Documents Affected:</strong> " . count($doc_ids) . "<br>
                                                        <strong>Processed By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                        <strong>Processed Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                                    </div>
                                                </div>

                                                <!-- Document List -->
                                                <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #495057;'>📄 Affected Documents</h4>
                                                    <p style='color: #495057; font-size: 12px; max-height: 200px; overflow-y: auto;'>
                                                        " . implode(', ', $doc_ids) . "
                                                    </p>
                                                </div>
                                            </div>";

                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = count($doc_ids) . " document(s) updated to $bulk_status!";
                    } else {
                        $error = "Failed to update documents.";
                    }
                }
                break;
                
            case 'delete_document':
                if ($target_id > 0) {
                    // Get document info before deletion
                    $doc_sql = "SELECT d.*, u.username, u.email, u.first_name FROM kyc_documents d 
                               LEFT JOIN users u ON d.user_id = u.id 
                               WHERE d.id = $target_id";
                    $doc_result = mysqli_query($conn, $doc_sql);
                    $doc_data = mysqli_fetch_assoc($doc_result);
                    
                    // Delete document file from server
                    if (file_exists($doc_data['document_path'])) {
                        unlink($doc_data['document_path']);
                    }
                    
                    // Delete from database
                    $sql = "DELETE FROM kyc_documents WHERE id = $target_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        // Log activity
                        logAdminActivity(
                            'KYC Document Deleted',
                            "Deleted KYC document (ID: $target_id, Type: {$doc_data['document_type']}) for user {$doc_data['username']}",
                            'KYC',
                            $target_id,
                            'kyc_documents'
                        );
                        
                        // NOTIFICATION: KYC Document Deleted (ADMIN)
                        $admin_mail_subject = "KYC Document Deleted";
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>KYC Document Deleted</h2>
                                                
                                                <p class='message'>
                                                    A KYC document has been permanently deleted from the system.
                                                </p>

                                                <!-- Deletion Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Document ID:</strong> KYC-" . $target_id . "<br>
                                                        <strong>User:</strong> " . $doc_data['first_name'] . " (" . $doc_data['username'] . ")<br>
                                                        <strong>User Email:</strong> " . $doc_data['email'] . "<br>
                                                        <strong>Document Type:</strong> " . ($type_labels[$doc_data['document_type']] ?? $doc_data['document_type']) . "<br>
                                                        <strong>Deleted By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                        <strong>Deletion Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                                        <strong>File Removed:</strong> " . ($doc_data['document_path'] ? 'Yes' : 'File not found') . "
                                                    </div>
                                                </div>
                                            </div>";

                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "Document deleted successfully!";
                    } else {
                        $error = "Failed to delete document.";
                    }
                }
                break;
        }
    }
}

// Get filter parameters
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build query
$sql = "SELECT d.*, u.username, u.email, u.status as user_status, u.first_name, u.last_name 
        FROM kyc_documents d 
        LEFT JOIN users u ON d.user_id = u.id 
        WHERE 1=1";

$count_sql = "SELECT COUNT(*) as total FROM kyc_documents d 
              LEFT JOIN users u ON d.user_id = u.id 
              WHERE 1=1";

// Apply filters
if ($filter_status && $filter_status != 'all') {
    $sql .= " AND d.verification_status = '$filter_status'";
    $count_sql .= " AND d.verification_status = '$filter_status'";
}

if ($filter_type && $filter_type != 'all') {
    $sql .= " AND d.document_type = '$filter_type'";
    $count_sql .= " AND d.document_type = '$filter_type'";
}

if ($search) {
    $sql .= " AND (u.username LIKE '%$search%' OR u.email LIKE '%$search%' OR u.first_name LIKE '%$search%' OR u.last_name LIKE '%$search%')";
    $count_sql .= " AND (u.username LIKE '%$search%' OR u.email LIKE '%$search%' OR u.first_name LIKE '%$search%' OR u.last_name LIKE '%$search%')";
}

if ($date_from) {
    $sql .= " AND DATE(d.upload_date) >= '$date_from'";
    $count_sql .= " AND DATE(d.upload_date) >= '$date_from'";
}

if ($date_to) {
    $sql .= " AND DATE(d.upload_date) <= '$date_to'";
    $count_sql .= " AND DATE(d.upload_date) <= '$date_to'";
}

// Get counts for stats
$count_result = mysqli_query($conn, "SELECT verification_status, COUNT(*) as count FROM kyc_documents GROUP BY verification_status");
$status_counts = array('pending' => 0, 'verified' => 0, 'rejected' => 0, 'total' => 0);
while ($row = mysqli_fetch_assoc($count_result)) {
    $status_counts[$row['verification_status']] = $row['count'];
}
$status_counts['total'] = array_sum($status_counts);

// Get document type counts
$type_result = mysqli_query($conn, "SELECT document_type, COUNT(*) as count FROM kyc_documents GROUP BY document_type");
$type_counts = array();
while ($row = mysqli_fetch_assoc($type_result)) {
    $type_counts[$row['document_type']] = $row['count'];
}

// Add sorting
$sql .= " ORDER BY d.upload_date DESC";

// Execute query
$result = mysqli_query($conn, $sql);

// Status colors
$status_colors = array(
    'verified' => 'success',
    'pending' => 'warning',
    'rejected' => 'danger'
);

// Document type labels
$type_labels = array(
    'id_document' => 'ID Document',
    'proof_address' => 'Proof of Address',
    'proof_income' => 'Proof of Income',
    'selfie' => 'Selfie with ID',
    'bank_statement' => 'Bank Statement'
);
?>

<!DOCTYPE html>
<html lang="en">
  	
	
	<body class="hold-transition light-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-id-card me-2"></i>KYC Documents Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#bulkActionModal">
												<i class="fas fa-tasks me-1"></i> Bulk Actions
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['total']; ?></h1>
														<p class="text-white mb-0">Total Documents</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['pending']; ?></h1>
														<p class="text-white mb-0">Pending Review</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['verified']; ?></h1>
														<p class="text-white mb-0">Verified</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['rejected']; ?></h1>
														<p class="text-white mb-0">Rejected</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row">
													<div class="col-md-2">
														<div class="form-group">
															<label>Status</label>
															<select class="form-control" name="status">
																<option value="all">All Status</option>
																<option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
																<option value="verified" <?php echo $filter_status == 'verified' ? 'selected' : ''; ?>>Verified</option>
																<option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Document Type</label>
															<select class="form-control" name="type">
																<option value="all">All Types</option>
																<?php foreach ($type_labels as $key => $label): ?>
																	<option value="<?php echo $key; ?>" <?php echo $filter_type == $key ? 'selected' : ''; ?>>
																		<?php echo $label; ?>
																	</option>
																<?php endforeach; ?>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Date From</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label>Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label>Search Users</label>
															<input type="text" class="form-control" name="search" placeholder="Username, email, name..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-1">
														<div class="form-group">
															<label>&nbsp;</label>
															<div class="d-flex">
																<button type="submit" class="btn btn-primary"><i class="fas fa-filter"></i></button>
																<?php if ($filter_status || $filter_type || $search || $date_from || $date_to): ?>
																	<a href="kyc_documents.php" class="btn btn-secondary ms-2">Clear</a>
																<?php endif; ?>
															</div>
														</div>
													</div>
												</form>
											</div>
										</div>
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Documents Table -->
										<div class="table-responsive">
											<form method="POST" id="bulkForm">
												<input type="hidden" name="action_type" value="bulk_verify">
												<table class="table table-hover table-bordered" id="documentsTable">
													<thead class="bg-light">
														<tr>
															<th width="30">
																<input type="checkbox" id="selectAll">
															</th>
															<th>ID</th>
															<th>User</th>
															<th>Document Type</th>
															<th>Status</th>
															<th>Upload Date</th>
															<th>Preview</th>
															<th>Actions</th>
														</tr>
													</thead>
													<tbody>
														<?php if (mysqli_num_rows($result) > 0): ?>
															<?php while ($doc = mysqli_fetch_assoc($result)): ?>
																<?php
																$doc_id = $doc['id'];
																$status_color = isset($status_colors[$doc['verification_status']]) ? $status_colors[$doc['verification_status']] : 'secondary';
																$upload_date = date('M d, Y H:i', strtotime($doc['upload_date']));
																$user_status_color = isset($status_colors[$doc['user_status']]) ? $status_colors[$doc['user_status']] : 'secondary';
																$type_label = isset($type_labels[$doc['document_type']]) ? $type_labels[$doc['document_type']] : ucfirst(str_replace('_', ' ', $doc['document_type']));
																?>
																<tr>
																	<td>
																		<input type="checkbox" class="doc-checkbox" name="doc_ids[]" value="<?php echo $doc_id; ?>">
																	</td>
																	<td><?php echo $doc_id; ?></td>
																	<td>
																		<div class="d-flex align-items-center">
																			<div class="me-10">
																				<div class="bg-primary rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																					<i class="fas fa-user text-white"></i>
																				</div>
																			</div>
																			<div>
																				<p class="mb-0 fw-500"><?php echo htmlspecialchars($doc['username']); ?></p>
																				<small class="text-mute"><?php echo htmlspecialchars($doc['first_name'] . ' ' . $doc['last_name']); ?></small>
																				<div class="mt-1">
																					<span class="badge bg-<?php echo $user_status_color; ?>"><?php echo ucfirst($doc['user_status']); ?></span>
																				</div>
																			</div>
																		</div>
																	</td>
																	<td>
																		<span class="badge bg-info"><?php echo $type_label; ?></span>
																	</td>
																	<td>
																		<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($doc['verification_status']); ?></span>
																	</td>
																	<td>
																		<p class="mb-0"><?php echo $upload_date; ?></p>
																		<small class="text-mute"><?php echo time_ago($doc['upload_date']); ?> ago</small>
																	</td>
																	<td>
																		<a href="#" class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#previewModal" 
																		   data-doc-path="<?php echo htmlspecialchars($doc['document_path']); ?>"
																		   data-doc-type="<?php echo $doc['document_type']; ?>">
																			<i class="fas fa-eye me-1"></i> Preview
																		</a>
																	</td>
																	<td>
																		<div class="btn-group">
																			<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																				<i class="fas fa-cog"></i>
																			</button>
																			<div class="dropdown-menu">
																				<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#verifyModal" 
																				   data-doc-id="<?php echo $doc_id; ?>"
																				   data-user-id="<?php echo $doc['user_id']; ?>"
																				   data-current-status="<?php echo $doc['verification_status']; ?>">
																					<i class="fas fa-check-circle me-2"></i> Verify/Reject
																				</a>
																				<a class="dropdown-item" href="<?php echo $doc['document_path']; ?>" target="_blank">
																					<i class="fas fa-download me-2"></i> Download
																				</a>
																				<a class="dropdown-item" href="view_user.php?id=<?php echo $doc['user_id']; ?>">
																					<i class="fas fa-user me-2"></i> View User
																				</a>
																				<div class="dropdown-divider"></div>
																				<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $doc_id; ?>)">
																					<i class="fas fa-trash me-2"></i> Delete
																				</a>
																			</div>
																		</div>
																	</td>
																</tr>
															<?php endwhile; ?>
														<?php else: ?>
															<tr>
																<td colspan="8" class="text-center py-20">
																	<i class="fas fa-id-card fa-2x text-mute mb-3"></i>
																	<h5>No KYC documents found</h5>
																	<p class="text-mute">Try adjusting your search or filters</p>
																</td>
															</tr>
														<?php endif; ?>
													</tbody>
												</table>
											</form>
										</div>
										
										<!-- Document Type Distribution -->
										<div class="row mt-30">
											<div class="col-md-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-pie me-2"></i>Document Type Distribution</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<?php foreach ($type_counts as $type => $count): ?>
																<?php 
																$type_color = match($type) {
																	'id_document' => 'primary',
																	'proof_address' => 'success',
																	'proof_income' => 'warning',
																	'selfie' => 'info',
																	default => 'secondary'
																};
																$type_label = isset($type_labels[$type]) ? $type_labels[$type] : ucfirst(str_replace('_', ' ', $type));
																$percentage = $status_counts['total'] > 0 ? round(($count / $status_counts['total']) * 100, 1) : 0;
																?>
																<div class="col-md-6 mb-3">
																	<div class="d-flex justify-content-between align-items-center">
																		<div>
																			<span class="badge bg-<?php echo $type_color; ?> me-2"><?php echo $type_label; ?></span>
																		</div>
																		<div class="text-end">
																			<h5 class="mb-0"><?php echo $count; ?></h5>
																			<small class="text-mute"><?php echo $percentage; ?>%</small>
																		</div>
																	</div>
																	<div class="progress mt-1" style="height: 5px;">
																		<div class="progress-bar bg-<?php echo $type_color; ?>" style="width: <?php echo $percentage; ?>%"></div>
																	</div>
																</div>
															<?php endforeach; ?>
														</div>
													</div>
												</div>
											</div>
											<div class="col-md-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-bar me-2"></i>Status Overview</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<?php foreach ($status_counts as $status => $count): ?>
																<?php if ($status != 'total'): ?>
																	<?php 
																	$status_color = $status_colors[$status] ?: 'secondary';
																	$percentage = $status_counts['total'] > 0 ? round(($count / $status_counts['total']) * 100, 1) : 0;
																	?>
																	<div class="col-md-4 mb-3">
																		<div class="text-center p-3 bg-light rounded">
																			<h2 class="fw-500 text-<?php echo $status_color; ?>"><?php echo $count; ?></h2>
																			<p class="text-mute mb-0"><?php echo ucfirst($status); ?></p>
																			<small class="text-mute"><?php echo $percentage; ?>%</small>
																		</div>
																	</div>
																<?php endif; ?>
															<?php endforeach; ?>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Document Verification -->
		<div class="modal fade" id="verifyModal" tabindex="-1" aria-labelledby="verifyModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="verifyModalLabel">Verify/Reject Document</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="verify_document">
							<input type="hidden" name="doc_id" id="verifyDocId">
							<input type="hidden" name="user_id" id="verifyUserId">
							
							<div class="mb-3">
								<label class="form-label">New Status</label>
								<select class="form-control" name="status" required id="verifyStatus">
									<option value="verified">✓ Verified</option>
									<option value="pending">⏳ Pending</option>
									<option value="rejected">✗ Rejected</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Notes/Reason (Optional)</label>
								<textarea class="form-control" name="notes" rows="3" placeholder="Enter verification notes or reason for rejection..."></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Update Status</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Bulk Actions -->
		<div class="modal fade" id="bulkActionModal" tabindex="-1" aria-labelledby="bulkActionModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST" id="bulkActionForm">
						<input type="hidden" name="action_type" value="bulk_verify">
						<div class="modal-header">
							<h5 class="modal-title" id="bulkActionModalLabel">Bulk Actions</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="mb-3">
								<label class="form-label">Action</label>
								<select class="form-control" name="bulk_status" required>
									<option value="">Select Action</option>
									<option value="verified">Mark as Verified</option>
									<option value="pending">Mark as Pending</option>
									<option value="rejected">Mark as Rejected</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
							
							<div class="alert alert-info">
								<i class="fas fa-info-circle me-2"></i>
								This action will affect <span id="selectedCount">0</span> selected document(s)
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary" id="bulkActionBtn" disabled>Apply Action</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Document Preview -->
		<div class="modal fade" id="previewModal" tabindex="-1" aria-labelledby="previewModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="previewModalLabel">Document Preview</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body text-center">
						<div id="previewContent">
							<!-- Preview will be loaded here -->
						</div>
						<div class="mt-3">
							<a href="#" id="downloadLink" class="btn btn-primary">
								<i class="fas fa-download me-1"></i> Download Document
							</a>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Hidden form for individual deletion -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_document">
			<input type="hidden" name="doc_id" id="deleteDocId">
			<input type="hidden" name="admin_pin" id="deletePin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<!-- DataTables -->
		<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
		<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#documentsTable').DataTable({
				"pageLength": 25,
				"order": [[1, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Select All checkbox
			$('#selectAll').click(function() {
				$('.doc-checkbox').prop('checked', this.checked);
				updateSelectedCount();
			});
			
			// Update selected count when checkboxes change
			$('.doc-checkbox').change(function() {
				if (!this.checked) {
					$('#selectAll').prop('checked', false);
				}
				updateSelectedCount();
			});
			
			// Verify Modal
			$('#verifyModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var docId = button.data('doc-id');
				var userId = button.data('user-id');
				var currentStatus = button.data('current-status');
				var modal = $(this);
				
				modal.find('#verifyDocId').val(docId);
				modal.find('#verifyUserId').val(userId);
				modal.find('#verifyStatus').val(currentStatus);
				modal.find('.modal-title').text('Verify Document #' + docId);
			});
			
			// Preview Modal
			$('#previewModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var docPath = button.data('doc-path');
				var docType = button.data('doc-type');
				var modal = $(this);
				
				// Set download link
				modal.find('#downloadLink').attr('href', docPath);
				
				// Show loading
				modal.find('#previewContent').html(`
					<div class="text-center py-5">
						<div class="spinner-border text-primary" role="status">
							<span class="visually-hidden">Loading...</span>
						</div>
						<p class="mt-3">Loading document preview...</p>
					</div>
				`);
				
				// Check file extension
				var extension = docPath.split('.').pop().toLowerCase();
				var previewHtml = '';
				
				if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(extension)) {
					// Image preview
					previewHtml = `<img src="${docPath}" class="img-fluid" style="max-height: 500px;" alt="Document Preview">`;
				} else if (['pdf'].includes(extension)) {
					// PDF preview using iframe
					previewHtml = `<iframe src="${docPath}" width="100%" height="500px" frameborder="0"></iframe>`;
				} else {
					// Generic file preview
					previewHtml = `
						<div class="alert alert-info">
							<i class="fas fa-file me-2"></i>
							This document type cannot be previewed in the browser.
							Please download the file to view it.
						</div>
					`;
				}
				
				// Update preview after a short delay
				setTimeout(function() {
					modal.find('#previewContent').html(previewHtml);
				}, 500);
			});
			
			// Bulk action form submission
			$('#bulkActionForm').submit(function(e) {
				var selectedCount = $('.doc-checkbox:checked').length;
				if (selectedCount === 0) {
					e.preventDefault();
					Swal.fire({
						icon: 'warning',
						title: 'No Documents Selected',
						text: 'Please select at least one document to perform bulk action.',
					});
					return false;
				}
				
				// Add selected document IDs to form
				$('.doc-checkbox:checked').each(function() {
					$('#bulkActionForm').append('<input type="hidden" name="doc_ids[]" value="' + $(this).val() + '">');
				});
				
				return true;
			});
			
			// Auto-refresh stats every 30 seconds
			setInterval(function() {
				refreshStats();
			}, 30000);
		});
		
		// Update selected document count
		function updateSelectedCount() {
			var selectedCount = $('.doc-checkbox:checked').length;
			$('#selectedCount').text(selectedCount);
			
			if (selectedCount > 0) {
				$('#bulkActionBtn').prop('disabled', false);
			} else {
				$('#bulkActionBtn').prop('disabled', true);
			}
		}
		
		// Confirm Delete with PIN
		function confirmDelete(docId) {
			Swal.fire({
				title: 'Delete Document?',
				html: `
					<p>This action cannot be undone. The document will be permanently deleted from the server.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Document',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the delete form
					document.getElementById('deleteDocId').value = docId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		
		// Refresh stats
		function refreshStats() {
			$.ajax({
				url: 'ajax/get_kyc_stats.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total);
						$('.bg-gradient-warning .fw-500').text(stats.pending);
						$('.bg-gradient-success .fw-500').text(stats.verified);
						$('.bg-gradient-danger .fw-500').text(stats.rejected);
						
						// Show notification if there are new pending documents
						if (stats.new_pending > 0) {
							Swal.fire({
								toast: true,
								position: 'top-end',
								icon: 'info',
								title: stats.new_pending + ' new pending document(s)',
								showConfirmButton: false,
								timer: 2000
							});
						}
					}
				}
			});
		}
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		#previewContent img {
			max-width: 100%;
			border: 1px solid #dee2e6;
			border-radius: 5px;
		}
		</style>
		
	</body>
</html>

<?php
// Helper function to show time ago
function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return $diff . " seconds";
    } elseif ($diff < 3600) {
        return floor($diff / 60) . " minutes";
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . " hours";
    } elseif ($diff < 604800) {
        return floor($diff / 86400) . " days";
    } elseif ($diff < 2592000) {
        return floor($diff / 604800) . " weeks";
    } elseif ($diff < 31536000) {
        return floor($diff / 2592000) . " months";
    } else {
        return floor($diff / 31536000) . " years";
    }
}
?>