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

// Get user ID
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($user_id == 0) {
    header('Location: users.php');
    exit();
}

// Get user details
$sql = "SELECT * FROM users WHERE id = $user_id";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);

if (!$user) {
    header('Location: users.php');
    exit();
}

// Get user's KYC documents
$kyc_sql = "SELECT * FROM kyc_documents WHERE user_id = $user_id";
$kyc_result = mysqli_query($conn, $kyc_sql);

// Get user's bot subscriptions
$subscription_sql = "SELECT s.*, p.plan_name, p.subscription_fee 
                     FROM user_bot_subscriptions s 
                     LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id 
                     WHERE s.user_id = $user_id 
                     ORDER BY s.created_at DESC";
$subscription_result = mysqli_query($conn, $subscription_sql);

// Get user's recent transactions
$transaction_sql = "SELECT * FROM transactions 
                    WHERE user_id = $user_id 
                    ORDER BY created_at DESC 
                    LIMIT 10";
$transaction_result = mysqli_query($conn, $transaction_sql);

// Get user's support tickets
$ticket_sql = "SELECT * FROM support_tickets 
               WHERE user_id = $user_id 
               ORDER BY created_at DESC 
               LIMIT 5";
$ticket_result = mysqli_query($conn, $ticket_sql);

// Get admin details for notification
$admin_id = $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? 1;
$adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_name = $adminData['first_name'] ?? 'Administrator';
$admin_email = $adminData['email'] ?? 'admin@system.com';

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

// Handle form submissions (from this page)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $admin_pin = "1234"; // Same PIN as before
    
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
        
        switch ($action_type) {
            case 'update_profile':
                $first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
                $last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
                $email = mysqli_real_escape_string($conn, $_POST['email']);
                $phone = mysqli_real_escape_string($conn, $_POST['phone']);
                $address = mysqli_real_escape_string($conn, $_POST['address']);
                $city = mysqli_real_escape_string($conn, $_POST['city']);
                $province = mysqli_real_escape_string($conn, $_POST['province']);
                $postal_code = mysqli_real_escape_string($conn, $_POST['postal_code']);
                
                // Capture old values for notification
                $old_values = array(
                    'first_name' => $user['first_name'],
                    'last_name' => $user['last_name'],
                    'email' => $user['email'],
                    'phone' => $user['phone'],
                    'address' => $user['address'],
                    'city' => $user['city'],
                    'province' => $user['province'],
                    'postal_code' => $user['postal_code']
                );
                
                $update_sql = "UPDATE users SET 
                              first_name = '$first_name',
                              last_name = '$last_name',
                              email = '$email',
                              phone = '$phone',
                              address = '$address',
                              city = '$city',
                              province = '$province',
                              postal_code = '$postal_code'
                              WHERE id = $user_id";
                
                if (mysqli_query($conn, $update_sql)) {
                    logAdminActivity(
                        'User Profile Updated',
                        "Updated profile for user {$user['username']}",
                        'Users',
                        $user_id,
                        'users'
                    );
                    
                    // NOTIFICATION: Profile Updated (USER)
                    $mail_subject = "Your Profile Has Been Updated";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Hello <span class='user-name'>" . $user['first_name'] . "</span>,</h2>
                                        
                                        <p class='message'>
                                            Your account profile has been updated by an administrator.
                                        </p>

                                        <!-- Profile Updates -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Update Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>Updated By:</strong> " . $admin_name . " (Admin)<br>
                                                <strong>Changes Made:</strong><br>
                                                <table style='width: 100%; border-collapse: collapse; margin-top: 10px;'>
                                                    <tr>
                                                        <th style='border: 1px solid #dee2e6; padding: 8px; text-align: left;'>Field</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 8px; text-align: left;'>Previous</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 8px; text-align: left;'>New</th>
                                                    </tr>";
                    
                    // Add changed fields
                    if ($old_values['first_name'] != $first_name) {
                        $mail_message .= "<tr><td style='border: 1px solid #dee2e6; padding: 8px;'>First Name</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $old_values['first_name'] . "</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $first_name . "</td></tr>";
                    }
                    if ($old_values['last_name'] != $last_name) {
                        $mail_message .= "<tr><td style='border: 1px solid #dee2e6; padding: 8px;'>Last Name</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $old_values['last_name'] . "</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $last_name . "</td></tr>";
                    }
                    if ($old_values['email'] != $email) {
                        $mail_message .= "<tr><td style='border: 1px solid #dee2e6; padding: 8px;'>Email</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $old_values['email'] . "</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $email . "</td></tr>";
                    }
                    if ($old_values['phone'] != $phone) {
                        $mail_message .= "<tr><td style='border: 1px solid #dee2e6; padding: 8px;'>Phone</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $old_values['phone'] . "</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $phone . "</td></tr>";
                    }
                    if ($old_values['address'] != $address) {
                        $mail_message .= "<tr><td style='border: 1px solid #dee2e6; padding: 8px;'>Address</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $old_values['address'] . "</td>
                                         <td style='border: 1px solid #dee2e6; padding: 8px;'>" . $address . "</td></tr>";
                    }
                    
                    $mail_message .= "</table>
                                            </div>
                                        </div>

                                        <!-- Security Notice -->
                                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #856404;'>🔒 Security Notice</h4>
                                            <p style='color: #856404;'>
                                                If you didn't request these changes, please contact support immediately.
                                            </p>
                                        </div>

                                        <!-- Action Button -->
                                        <div style='text-align: center; margin: 30px 0;'>
                                            <a href='" . $myUrl . "/profile.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                View Your Profile
                                            </a>
                                        </div>

                                        <!-- Support Section -->
                                        <div class='support-section'>
                                            <p class='support-text'>Questions about your profile?</p>
                                            <a href='" . $myUrl . "/support.php' class='support-link'>Contact Support</a>
                                        </div>
                                    </div>";

                    // Send user notification
                    $user_email = $user['email'];
                    $first_name = $user['first_name'];
                    require_once("../proccess/mail_sender.php");

                    // NOTIFICATION: Profile Updated (ADMIN)
                    $admin_mail_subject = "User Profile Updated - " . $user['username'];
                    $admin_mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>User Profile Updated</h2>
                                            
                                            <p class='message'>
                                                A user profile has been updated by an administrator.
                                            </p>

                                            <!-- Update Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>User ID:</strong> " . $user_id . "<br>
                                                    <strong>Username:</strong> " . $user['username'] . "<br>
                                                    <strong>Email:</strong> " . $user['email'] . "<br>
                                                    <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                                </div>
                                            </div>

                                            <!-- Admin Actions -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/admin/user-details.php?id=" . $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;'>
                                                    View Updated Profile
                                                </a>
                                            </div>
                                        </div>";

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Profile updated successfully!";
                    // Refresh user data
                    $result = mysqli_query($conn, $sql);
                    $user = mysqli_fetch_assoc($result);
                } else {
                    $error = "Failed to update profile.";
                }
                break;
                
            case 'verify_kyc':
                $doc_id = isset($_POST['doc_id']) ? intval($_POST['doc_id']) : 0;
                $status = isset($_POST['status']) ? $_POST['status'] : 'verified';
                
                // Get KYC document details before update
                $kyc_doc_sql = "SELECT * FROM kyc_documents WHERE id = $doc_id AND user_id = $user_id";
                $kyc_doc_result = mysqli_query($conn, $kyc_doc_sql);
                $kyc_doc = mysqli_fetch_assoc($kyc_doc_result);
                
                $kyc_sql = "UPDATE kyc_documents SET verification_status = '$status' WHERE id = $doc_id AND user_id = $user_id";
                if (mysqli_query($conn, $kyc_sql)) {
                    logAdminActivity(
                        'KYC Document Verified',
                        "Updated KYC document status to $status for user {$user['username']}",
                        'KYC',
                        $doc_id,
                        'kyc_documents'
                    );
                    
                    // If KYC is verified, update user status to verified
                    if ($status == 'verified') {
                        $update_user_sql = "UPDATE users SET status = 'verified', verification_date = NOW() WHERE id = $user_id";
                        mysqli_query($conn, $update_user_sql);
                    }
                    
                    // NOTIFICATION: KYC Status Update (USER)
                    $mail_subject = "KYC Verification " . ($status == 'verified' ? "Approved" : ($status == 'rejected' ? "Rejected" : "Updated"));
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Hello <span class='user-name'>" . $user['first_name'] . "</span>,</h2>
                                        
                                        <p class='message'>
                                            " . ($status == 'verified' ? 
                                                "🎉 <strong>Congratulations! Your KYC verification has been approved.</strong>" : 
                                                ($status == 'rejected' ? 
                                                "❌ <strong>Your KYC verification was not approved.</strong>" : 
                                                "📝 <strong>Your KYC verification status has been updated.</strong>")) . "
                                        </p>

                                        <!-- KYC Status Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Document ID:</strong> " . $kyc_doc['document_type'] . "<br>
                                                <strong>Document Number:</strong> " . ($kyc_doc['document_number'] ?? 'N/A') . "<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>
                                                <strong>Verified By:</strong> " . $admin_name . " (Admin)
                                            </div>
                                        </div>
                                        
                                        " . ($status == 'verified' ? 
                                            '<div style="background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;">
                                                <h4 style="color: #155724;">✅ Account Fully Verified</h4>
                                                <p style="color: #155724;">
                                                    Your account is now fully verified! You now have access to all platform features including withdrawals and premium trading bots.
                                                </p>
                                            </div>' : 
                                            ($status == 'rejected' ? 
                                            '<div style="background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;">
                                                <h4 style="color: #721c24;">📋 Reason for Rejection</h4>
                                                <p style="color: #721c24;">
                                                    ' . ($kyc_doc['rejection_reason'] ?? 'Document did not meet verification requirements. Please submit clear, valid documents.') . '
                                                </p>
                                                <p style="color: #721c24; margin-top: 10px;">
                                                    <a href="' . $myUrl . '/kyc.php" style="color: #721c24; font-weight: bold;">Click here to resubmit your documents</a>
                                                </p>
                                            </div>' : '')) . '

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

                    // Send user notification
                    $user_email = $user['email'];
                    $first_name = $user['first_name'];
                    require_once("../proccess/mail_sender.php");

                    // NOTIFICATION: KYC Status Update (ADMIN)
                    $admin_mail_subject = "KYC Document " . ucfirst($status) . " - " . $user['username'];
                    $admin_mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>KYC Document " . ucfirst($status) . "</h2>
                                            
                                            <p class='message'>
                                                A KYC document has been " . $status . " by an administrator.
                                            </p>

                                            <!-- KYC Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>User:</strong> " . $user['username'] . " (ID: " . $user_id . ")<br>
                                                    <strong>Document Type:</strong> " . $kyc_doc['document_type'] . "<br>
                                                    <strong>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') . "
                                                </div>
                                            </div>

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

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "KYC document status updated!";
                    // Refresh KYC data
                    $kyc_result = mysqli_query($conn, $kyc_sql);
                } else {
                    $error = "Failed to update KYC status.";
                }
                break;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
	
	<body class="hold-transition dark-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">
										<div class="d-flex justify-content-between align-items-center">
											<div>
												<h4 class="box-title">
													<i class="fas fa-user me-2"></i>
													User Profile: <?php echo htmlspecialchars($user['username']); ?>
												</h4>
												<p class="mb-0 text-mute">User ID: <?php echo $user['id']; ?></p>
											</div>
											<div>
												<a href="users.php" class="btn btn-light me-2">
													<i class="fas fa-arrow-left me-1"></i> Back to Users
												</a>
												<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editProfileModal">
													<i class="fas fa-edit me-1"></i> Edit Profile
												</button>
											</div>
										</div>
									</div>
									<div class="box-body">
										
										<?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; ?>
										
										<!-- User Info Card -->
										<div class="row">
											<div class="col-md-4">
												<div class="box bg-light">
													<div class="box-body text-center">
														<div class="mb-20">
															<div class="bg-primary rounded-circle w-100 h-100 mx-auto d-flex align-items-center justify-content-center" style="width: 100px; height: 100px;">
																<i class="fas fa-user fa-3x text-white"></i>
															</div>
														</div>
														<h4 class="fw-500"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h4>
														<p class="text-mute">@<?php echo htmlspecialchars($user['username']); ?></p>
														
														<div class="mt-20">
															<span class="badge bg-<?php echo $status_colors[$user['status']]; ?> fs-16">
																<?php echo ucfirst($user['status']); ?>
															</span>
															<?php if ($user['status'] == 'verified' && $user['verification_date']): ?>
																<p class="text-mute mt-2">Verified on: <?php echo date('M d, Y', strtotime($user['verification_date'])); ?></p>
															<?php endif; ?>
														</div>
														
														<div class="mt-30">
															<button class="btn btn-outline-primary me-2" data-bs-toggle="modal" data-bs-target="#statusModal">
																<i class="fas fa-user-check me-1"></i> Change Status
															</button>
															<button class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#balanceModal">
																<i class="fas fa-money-bill-wave me-1"></i> Adjust Balance
															</button>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-md-8">
												<!-- Financial Overview -->
												<div class="box mb-20">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-pie me-2"></i>Financial Overview</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<div class="col-md-4">
																<div class="text-center p-3 bg-light rounded">
																	<h2 class="fw-500 text-primary">$<?php echo number_format($user['fund_balance'], 2); ?></h2>
																	<p class="text-mute mb-0">Total Balance</p>
																</div>
															</div>
															<div class="col-md-4">
																<div class="text-center p-3 bg-light rounded">
																	<h2 class="fw-500 text-success">$<?php echo number_format($user['available_balance'], 2); ?></h2>
																	<p class="text-mute mb-0">Available Balance</p>
																</div>
															</div>
															<div class="col-md-4">
																<div class="text-center p-3 bg-light rounded">
																	<h2 class="fw-500 text-info">$<?php echo number_format($user['total_profit'], 2); ?></h2>
																	<p class="text-mute mb-0">Total Profit</p>
																</div>
															</div>
														</div>
													</div>
												</div>
												
												<!-- Personal Information -->
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-info-circle me-2"></i>Personal Information</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<div class="col-md-6">
																<table class="table table-sm">
																	<tr>
																		<td width="40%"><strong>Email:</strong></td>
																		<td><?php echo htmlspecialchars($user['email']); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Phone:</strong></td>
																		<td><?php echo htmlspecialchars($user['phone']); ?></td>
																	</tr>
																	<tr>
																		<td><strong>ID Number:</strong></td>
																		<td><?php echo htmlspecialchars($user['id_number']); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Date of Birth:</strong></td>
																		<td><?php echo date('M d, Y', strtotime($user['date_of_birth'])); ?></td>
																	</tr>
																</table>
															</div>
															<div class="col-md-6">
																<table class="table table-sm">
																	<tr>
																		<td width="40%"><strong>Address:</strong></td>
																		<td><?php echo htmlspecialchars($user['address']); ?></td>
																	</tr>
																	<tr>
																		<td><strong>City:</strong></td>
																		<td><?php echo htmlspecialchars($user['city']); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Province:</strong></td>
																		<td><?php echo htmlspecialchars($user['province']); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Postal Code:</strong></td>
																		<td><?php echo htmlspecialchars($user['postal_code']); ?></td>
																	</tr>
																</table>
															</div>
														</div>
														<div class="mt-3">
															<p class="mb-1"><strong>Joined:</strong> <?php echo date('F d, Y H:i:s', strtotime($user['registration_date'])); ?></p>
															<p class="mb-0"><strong>Last Login:</strong> 
																<?php 
																// You would need to track last login in your users table
																echo 'Not tracked'; 
																?>
															</p>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Tabs for more details -->
										<div class="row mt-20">
											<div class="col-12">
												<ul class="nav nav-tabs" role="tablist">
													<li class="nav-item">
														<a class="nav-link active" data-bs-toggle="tab" href="#kyc">KYC Documents</a>
													</li>
													<li class="nav-item">
														<a class="nav-link" data-bs-toggle="tab" href="#subscriptions">Bot Subscriptions</a>
													</li>
													<li class="nav-item">
														<a class="nav-link" data-bs-toggle="tab" href="#transactions">Recent Transactions</a>
													</li>
													<li class="nav-item">
														<a class="nav-link" data-bs-toggle="tab" href="#tickets">Support Tickets</a>
													</li>
												</ul>
												
												<div class="tab-content mt-3">
													<!-- KYC Documents Tab -->
													<div class="tab-pane fade show active" id="kyc">
														<?php if (mysqli_num_rows($kyc_result) > 0): ?>
															<div class="row">
																<?php while ($doc = mysqli_fetch_assoc($kyc_result)): ?>
																	<?php
																	$doc_status = $doc['verification_status'];
																	$status_color = $doc_status == 'verified' ? 'success' : ($doc_status == 'rejected' ? 'danger' : 'warning');
																	?>
																	<div class="col-md-4">
																		<div class="box">
																			<div class="box-header">
																				<h6 class="box-title"><?php echo ucfirst(str_replace('_', ' ', $doc['document_type'])); ?></h6>
																				<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($doc_status); ?></span>
																			</div>
																			<div class="box-body">
																				<p class="mb-2"><strong>Uploaded:</strong> <?php echo date('M d, Y H:i', strtotime($doc['upload_date'])); ?></p>
																				<a href="<?php echo $doc['document_path']; ?>" target="_blank" class="btn btn-sm btn-primary">
																					<i class="fas fa-eye me-1"></i> View Document
																				</a>
																				
																				<form method="POST" class="mt-3">
																					<input type="hidden" name="action_type" value="verify_kyc">
																					<input type="hidden" name="doc_id" value="<?php echo $doc['id']; ?>">
																					<div class="d-flex">
																						<select name="status" class="form-control form-control-sm me-2">
																							<option value="pending" <?php echo $doc_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
																							<option value="verified" <?php echo $doc_status == 'verified' ? 'selected' : ''; ?>>Verified</option>
																							<option value="rejected" <?php echo $doc_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
																						</select>
																						<button type="submit" class="btn btn-sm btn-success">
																							<i class="fas fa-check"></i>
																						</button>
																					</div>
																				</form>
																			</div>
																		</div>
																	</div>
																<?php endwhile; ?>
															</div>
														<?php else: ?>
															<div class="alert alert-info">
																<i class="fas fa-info-circle me-2"></i> No KYC documents uploaded yet.
															</div>
														<?php endif; ?>
													</div>
													
													<!-- Bot Subscriptions Tab -->
													<div class="tab-pane fade" id="subscriptions">
														<?php if (mysqli_num_rows($subscription_result) > 0): ?>
															<div class="table-responsive">
																<table class="table table-hover">
																	<thead>
																		<tr>
																			<th>Plan</th>
																			<th>Trading Balance</th>
																			<th>Status</th>
																			<th>Start Date</th>
																			<th>End Date</th>
																			<th>Profit</th>
																		</tr>
																	</thead>
																	<tbody>
																		<?php while ($sub = mysqli_fetch_assoc($subscription_result)): ?>
																			<?php
																			$status_color = $sub['status'] == 'active' ? 'success' : 'secondary';
																			?>
																			<tr>
																				<td><?php echo htmlspecialchars($sub['plan_name']); ?></td>
																				<td>$<?php echo number_format($sub['trading_balance'], 2); ?></td>
																				<td><span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($sub['status']); ?></span></td>
																				<td><?php echo date('M d, Y', strtotime($sub['subscription_start'])); ?></td>
																				<td><?php echo date('M d, Y', strtotime($sub['subscription_end'])); ?></td>
																				<td>$<?php echo number_format($sub['total_profit'], 2); ?></td>
																			</tr>
																		<?php endwhile; ?>
																	</tbody>
																</table>
															</div>
														<?php else: ?>
															<div class="alert alert-info">
																<i class="fas fa-info-circle me-2"></i> No bot subscriptions yet.
															</div>
														<?php endif; ?>
													</div>
													
													<!-- Recent Transactions Tab -->
													<div class="tab-pane fade" id="transactions">
														<?php if (mysqli_num_rows($transaction_result) > 0): ?>
															<div class="table-responsive">
																<table class="table table-hover">
																	<thead>
																		<tr>
																			<th>ID</th>
																			<th>Type</th>
																			<th>Amount</th>
																			<th>Status</th>
																			<th>Date</th>
																			<th>Description</th>
																		</tr>
																	</thead>
																	<tbody>
																		<?php while ($txn = mysqli_fetch_assoc($transaction_result)): ?>
																			<?php
																			$status_color = $txn['status'] == 'completed' ? 'success' : 'warning';
																			$type_color = $txn['type'] == 'profit' ? 'success' : ($txn['type'] == 'deposit' ? 'primary' : 'danger');
																			?>
																			<tr>
																				<td><?php echo $txn['id']; ?></td>
																				<td><span class="badge bg-<?php echo $type_color; ?>"><?php echo ucfirst($txn['type']); ?></span></td>
																				<td>$<?php echo number_format($txn['amount'], 2); ?></td>
																				<td><span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($txn['status']); ?></span></td>
																				<td><?php echo date('M d, Y H:i', strtotime($txn['created_at'])); ?></td>
																				<td><?php echo htmlspecialchars($txn['description']); ?></td>
																			</tr>
																		<?php endwhile; ?>
																	</tbody>
																</table>
															</div>
														<?php else: ?>
															<div class="alert alert-info">
																<i class="fas fa-info-circle me-2"></i> No transactions yet.
															</div>
														<?php endif; ?>
													</div>
													
													<!-- Support Tickets Tab -->
													<div class="tab-pane fade" id="tickets">
														<?php if (mysqli_num_rows($ticket_result) > 0): ?>
															<div class="table-responsive">
																<table class="table table-hover">
																	<thead>
																		<tr>
																			<th>Ticket #</th>
																			<th>Subject</th>
																			<th>Category</th>
																			<th>Status</th>
																			<th>Created</th>
																		</tr>
																	</thead>
																	<tbody>
																		<?php while ($ticket = mysqli_fetch_assoc($ticket_result)): ?>
																			<?php
																			$status_color = $ticket['status'] == 'open' ? 'warning' : ($ticket['status'] == 'resolved' ? 'success' : 'info');
																			?>
																			<tr>
																				<td><?php echo htmlspecialchars($ticket['ticket_number']); ?></td>
																				<td><?php echo htmlspecialchars($ticket['subject']); ?></td>
																				<td><?php echo ucfirst(str_replace('_', ' ', $ticket['category'])); ?></td>
																				<td><span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($ticket['status']); ?></span></td>
																				<td><?php echo date('M d, Y', strtotime($ticket['created_at'])); ?></td>
																			</tr>
																		<?php endwhile; ?>
																	</tbody>
																</table>
															</div>
														<?php else: ?>
															<div class="alert alert-info">
																<i class="fas fa-info-circle me-2"></i> No support tickets yet.
															</div>
														<?php endif; ?>
													</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 Editing Profile -->
		<div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="editProfileModalLabel">Edit User Profile</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="update_profile">
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">First Name <span class="text-danger">*</span></label>
										<input type="text" class="form-control" name="first_name" value="<?php echo htmlspecialchars($user['first_name']); ?>" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Last Name <span class="text-danger">*</span></label>
										<input type="text" class="form-control" name="last_name" value="<?php echo htmlspecialchars($user['last_name']); ?>" required>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Email <span class="text-danger">*</span></label>
										<input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Phone <span class="text-danger">*</span></label>
										<input type="text" class="form-control" name="phone" value="<?php echo htmlspecialchars($user['phone']); ?>" required>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Address</label>
								<textarea class="form-control" name="address" rows="2"><?php echo htmlspecialchars($user['address']); ?></textarea>
							</div>
							
							<div class="row">
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">City</label>
										<input type="text" class="form-control" name="city" value="<?php echo htmlspecialchars($user['city']); ?>">
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Province</label>
										<input type="text" class="form-control" name="province" value="<?php echo htmlspecialchars($user['province']); ?>">
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Postal Code</label>
										<input type="text" class="form-control" name="postal_code" value="<?php echo htmlspecialchars($user['postal_code']); ?>">
									</div>
								</div>
							</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 Profile</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Status and Balance Modals (same as users.php) -->
		<?php include('modals/user_modals.php'); ?>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<script>
		$(document).ready(function() {
			// Auto-refresh user stats every 30 seconds
			setInterval(function() {
				// Update the user's balance display
				$.ajax({
					url: 'ajax/get_user_balance.php',
					type: 'GET',
					data: { user_id: <?php echo $user_id; ?> },
					success: function(data) {
						var balance = JSON.parse(data);
						if (balance.success) {
							// Update balance displays
							$('.text-primary.fw-500').text('$' + balance.fund_balance);
							$('.text-success.fw-500').text('$' + balance.available_balance);
							$('.text-info.fw-500').text('$' + balance.total_profit);
						}
					}
				});
			}, 30000); // 30 seconds
		});
		</script>
		
		<style>
		.nav-tabs .nav-link.active {
			background-color: #f8f9fa;
			border-color: #dee2e6 #dee2e6 #f8f9fa;
		}
		.box {
			border-radius: 10px;
			overflow: hidden;
		}
		</style>
		
	</body>
</html>