<?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">
										<h4 class="box-title"><i class="fas fa-upload me-2"></i>Withdrawals Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" onclick="window.location.reload()">
												<i class="fas fa-sync-alt me-1"></i> Refresh
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-2 col-md-4 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']['count']; ?></h1>
														<p class="text-white mb-0">Total</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['total']['amount'], 2); ?></p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 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']['count']; ?></h1>
														<p class="text-white mb-0">Pending</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['pending']['amount'], 2); ?></p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['processing']['count']; ?></h1>
														<p class="text-white mb-0">Processing</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['processing']['amount'], 2); ?></p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 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['completed']['count']; ?></h1>
														<p class="text-white mb-0">Completed</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['completed']['amount'], 2); ?></p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 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']['count']; ?></h1>
														<p class="text-white mb-0">Rejected</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['rejected']['amount'], 2); ?></p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-12">
												<div class="box bg-gradient-secondary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['cancelled']['count']; ?></h1>
														<p class="text-white mb-0">Cancelled</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['cancelled']['amount'], 2); ?></p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-10">
												<form method="GET" class="row">
													<div class="col-md-3">
														<div class="form-group">
															<select class="form-control" name="status" onchange="this.form.submit()">
																<option value="">All Status</option>
																<option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
																<option value="processing" <?php echo $filter_status == 'processing' ? 'selected' : ''; ?>>Processing</option>
																<option value="completed" <?php echo $filter_status == 'completed' ? 'selected' : ''; ?>>Completed</option>
																<option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
																<option value="cancelled" <?php echo $filter_status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>" placeholder="From Date">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>" placeholder="To Date">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<input type="text" class="form-control" name="search" placeholder="Search..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-12">
														<button type="submit" class="btn btn-primary me-2"><i class="fas fa-search me-1"></i> Filter</button>
														<?php if ($search || $filter_status || $date_from || $date_to): ?>
															<a href="withdrawals.php" class="btn btn-secondary">Clear</a>
														<?php endif; ?>
													</div>
												</form>
											</div>
											<div class="col-md-2 text-end">
												<div class="dropdown">
													<button class="btn btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
														<i class="fas fa-download me-1"></i> Export
													</button>
													<div class="dropdown-menu">
														<a class="dropdown-item" href="export_withdrawals.php?format=csv&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
															<i class="fas fa-file-csv"></i> CSV
														</a>
														<a class="dropdown-item" href="export_withdrawals.php?format=excel&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
															<i class="fas fa-file-excel"></i> Excel
														</a>
													</div>
												</div>
											</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; ?>
										
										<!-- Bulk Actions -->
										<form method="POST" id="bulkForm" class="mb-3">
											<input type="hidden" name="action_type" value="bulk_action">
											<div class="row">
												<div class="col-md-4">
													<select class="form-control" name="bulk_status" required>
														<option value="">Bulk Action</option>
														<option value="processing">Mark as Processing</option>
														<option value="completed">Mark as Completed</option>
														<option value="rejected">Reject Selected</option>
														<option value="cancelled">Cancel Selected</option>
													</select>
												</div>
												<div class="col-md-4">
													<input type="password" class="form-control" name="admin_pin" placeholder="Admin PIN" required>
												</div>
												<div class="col-md-4">
													<button type="submit" class="btn btn-primary" onclick="return confirmBulkAction()">
														<i class="fas fa-play me-1"></i> Apply
													</button>
													<button type="button" class="btn btn-secondary" onclick="selectAll()">
														<i class="fas fa-check-square me-1"></i> Select All
													</button>
												</div>
											</div>
										</form>
										
										<!-- Withdrawals Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="withdrawalsTable">
												<thead class="bg-light">
													<tr>
														<th width="50">
															<input type="checkbox" id="selectAll">
														</th>
														<th>ID</th>
														<th>User</th>
														<th>Amount</th>
														<th>Destination</th>
														<th>Status</th>
														<th>Created</th>
														<th>Processed</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($withdrawal = mysqli_fetch_assoc($result)): ?>
															<?php
															$status_color = isset($status_colors[$withdrawal['status']]) ? $status_colors[$withdrawal['status']] : 'secondary';
															$created_date = date('M d, Y H:i', strtotime($withdrawal['created_at']));
															$processed_date = $withdrawal['processed_at'] ? date('M d, Y H:i', strtotime($withdrawal['processed_at'])) : '-';
															$net_amount = $withdrawal['amount'] - $withdrawal['fee'];
															?>
															<tr>
																<td>
																	<input type="checkbox" class="row-checkbox" name="selected_ids[]" value="<?php echo $withdrawal['id']; ?>">
																</td>
																<td>WD-<?php echo $withdrawal['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($withdrawal['username']); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($withdrawal['email']); ?></small>
																		</div>
																	</div>
																</td>
																<td>
																	<p class="mb-0 fw-500">$<?php echo number_format($withdrawal['amount'], 2); ?></p>
																	<small class="text-mute">Fee: $<?php echo number_format($withdrawal['fee'], 2); ?></small>
																	<br>
																	<small class="text-success">Net: $<?php echo number_format($net_amount, 2); ?></small>
																</td>
																<td>
																	<p class="mb-0"><small><?php echo htmlspecialchars($withdrawal['destination_address']); ?></small></p>
																	<?php if ($withdrawal['transaction_hash']): ?>
																		<small class="text-info">Hash: <?php echo substr($withdrawal['transaction_hash'], 0, 20) . '...'; ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($withdrawal['status']); ?></span>
																	<?php if ($withdrawal['balance_source'] != 'available_balance'): ?>
																		<br><small class="text-mute">Source: <?php echo $withdrawal['balance_source']; ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $created_date; ?></p>
																	<small class="text-mute"><?php echo time_ago($withdrawal['created_at']); ?> ago</small>
																</td>
																<td>
																	<?php echo $processed_date; ?>
																	<?php if ($withdrawal['processed_by']): ?>
																		<br><small class="text-mute">By: Admin <?php echo $withdrawal['processed_by']; ?></small>
																	<?php endif; ?>
																</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="#viewModal" 
																			   data-id="<?php echo $withdrawal['id']; ?>"
																			   data-user="<?php echo htmlspecialchars($withdrawal['username']); ?>"
																			   data-amount="<?php echo $withdrawal['amount']; ?>"
																			   data-fee="<?php echo $withdrawal['fee']; ?>"
																			   data-total="<?php echo $withdrawal['total_amount']; ?>"
																			   data-address="<?php echo htmlspecialchars($withdrawal['destination_address']); ?>"
																			   data-hash="<?php echo $withdrawal['transaction_hash']; ?>"
																			   data-status="<?php echo $withdrawal['status']; ?>"
																			   data-created="<?php echo $withdrawal['created_at']; ?>"
																			   data-processed="<?php echo $withdrawal['processed_at']; ?>"
																			   data-source="<?php echo $withdrawal['balance_source']; ?>">
																				<i class="fas fa-eye me-2"></i> View Details
																			</a>
																			<?php if ($withdrawal['status'] == 'pending'): ?>
																				<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#statusModal" 
																				   data-id="<?php echo $withdrawal['id']; ?>"
																				   data-current-status="<?php echo $withdrawal['status']; ?>">
																					<i class="fas fa-play me-2"></i> Start Processing
																				</a>
																			<?php elseif ($withdrawal['status'] == 'processing'): ?>
																				<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#completeModal" 
																				   data-id="<?php echo $withdrawal['id']; ?>">
																					<i class="fas fa-check me-2"></i> Mark as Completed
																				</a>
																			<?php endif; ?>
																			<?php if (in_array($withdrawal['status'], ['pending', 'processing'])): ?>
																				<a class="dropdown-item text-warning" href="#" data-bs-toggle="modal" data-bs-target="#statusModal" 
																				   data-id="<?php echo $withdrawal['id']; ?>"
																				   data-current-status="<?php echo $withdrawal['status']; ?>">
																					<i class="fas fa-edit me-2"></i> Change Status
																				</a>
																			<?php endif; ?>
																			<div class="dropdown-divider"></div>
																			<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $withdrawal['id']; ?>)">
																				<i class="fas fa-trash me-2"></i> Delete
																			</a>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="9" class="text-center py-20">
																<i class="fas fa-money-bill-wave fa-2x text-mute mb-3"></i>
																<h5>No withdrawals found</h5>
																<p class="text-mute">Try adjusting your search or filters</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Stats Summary -->
										<div class="row mt-20">
											<div class="col-md-12">
												<div class="box bg-light">
													<div class="box-body">
														<div class="row">
															<div class="col-md-3 text-center">
																<h3 class="text-primary">$<?php echo number_format($status_counts['total']['amount'], 2); ?></h3>
																<p class="text-mute mb-0">Total Withdrawal Amount</p>
															</div>
															<div class="col-md-3 text-center">
																<h3 class="text-warning">$<?php echo number_format($status_counts['pending']['amount'], 2); ?></h3>
																<p class="text-mute mb-0">Pending Amount</p>
															</div>
															<div class="col-md-3 text-center">
																<h3 class="text-success">$<?php echo number_format($status_counts['completed']['amount'], 2); ?></h3>
																<p class="text-mute mb-0">Completed Amount</p>
															</div>
															<div class="col-md-3 text-center">
																<h3 class="text-danger">$<?php echo number_format($status_counts['rejected']['amount'] + $status_counts['cancelled']['amount'], 2); ?></h3>
																<p class="text-mute mb-0">Rejected/Cancelled Amount</p>
															</div>
														</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 Viewing Withdrawal Details -->
		<div class="modal fade" id="viewModal" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="viewModalLabel">Withdrawal Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body">
						<div class="row">
							<div class="col-md-6">
								<h6>Transaction Information</h6>
								<table class="table table-sm">
									<tr>
										<td width="40%"><strong>Withdrawal ID:</strong></td>
										<td id="viewId"></td>
									</tr>
									<tr>
										<td><strong>Amount:</strong></td>
										<td id="viewAmount"></td>
									</tr>
									<tr>
										<td><strong>Fee:</strong></td>
										<td id="viewFee"></td>
									</tr>
									<tr>
										<td><strong>Total Amount:</strong></td>
										<td id="viewTotal"></td>
									</tr>
									<tr>
										<td><strong>Status:</strong></td>
										<td id="viewStatus"></td>
									</tr>
									<tr>
										<td><strong>Balance Source:</strong></td>
										<td id="viewSource"></td>
									</tr>
								</table>
							</div>
							<div class="col-md-6">
								<h6>User & Network Information</h6>
								<table class="table table-sm">
									<tr>
										<td width="40%"><strong>User:</strong></td>
										<td id="viewUser"></td>
									</tr>
									<tr>
										<td><strong>Destination Address:</strong></td>
										<td id="viewAddress"><small></small></td>
									</tr>
									<tr>
										<td><strong>Transaction Hash:</strong></td>
										<td id="viewHash"><small></small></td>
									</tr>
									<tr>
										<td><strong>Created:</strong></td>
										<td id="viewCreated"></td>
									</tr>
									<tr>
										<td><strong>Processed:</strong></td>
										<td id="viewProcessed"></td>
									</tr>
								</table>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
						<button type="button" class="btn btn-primary" id="quickActionBtn" onclick="quickAction()">Quick Action</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Changing Status -->
		<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="statusModalLabel">Change Withdrawal Status</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_status">
							<input type="hidden" name="withdrawal_id" id="statusWithdrawalId">
							
							<div class="mb-3">
								<label class="form-label">New Status</label>
								<select class="form-control" name="status" id="statusSelect" required>
									<option value="processing">Processing</option>
									<option value="completed">Completed</option>
									<option value="rejected">Rejected</option>
									<option value="cancelled">Cancelled</option>
								</select>
							</div>
							
							<div class="mb-3" id="transactionHashField" style="display: none;">
								<label class="form-label">Transaction Hash</label>
								<input type="text" class="form-control" name="transaction_hash" placeholder="Enter blockchain transaction hash">
								<small class="text-mute">Required for completed withdrawals</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Reason (Optional)</label>
								<textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for status change..."></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 Completing Withdrawal -->
		<div class="modal fade" id="completeModal" tabindex="-1" aria-labelledby="completeModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="completeModalLabel">Complete Withdrawal</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_status">
							<input type="hidden" name="withdrawal_id" id="completeWithdrawalId">
							<input type="hidden" name="status" value="completed">
							
							<div class="mb-3">
								<label class="form-label">Transaction Hash <span class="text-danger">*</span></label>
								<input type="text" class="form-control" name="transaction_hash" required placeholder="Enter blockchain transaction hash">
								<small class="text-mute">This is the hash from the blockchain transaction</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Notes (Optional)</label>
								<textarea class="form-control" name="reason" rows="3" placeholder="Any additional notes..."></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">Mark as Completed</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Hidden form for single delete -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="update_status">
			<input type="hidden" name="withdrawal_id" id="deleteWithdrawalId">
			<input type="hidden" name="status" value="cancelled">
			<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
			$('#withdrawalsTable').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"
					}
				}
			});
			
			// View Modal
			$('#viewModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var modal = $(this);
				
				modal.find('#viewId').text('WD-' + button.data('id'));
				modal.find('#viewUser').text(button.data('user'));
				modal.find('#viewAmount').text('$' + parseFloat(button.data('amount')).toFixed(2));
				modal.find('#viewFee').text('$' + parseFloat(button.data('fee')).toFixed(2));
				modal.find('#viewTotal').text('$' + parseFloat(button.data('total')).toFixed(2));
				modal.find('#viewAddress').html('<small>' + button.data('address') + '</small>');
				modal.find('#viewHash').html(button.data('hash') ? '<small>' + button.data('hash') + '</small>' : '-');
				modal.find('#viewSource').text(button.data('source'));
				
				// Status with badge
				var status = button.data('status');
				var statusColors = {
					'pending': 'warning',
					'processing': 'info',
					'completed': 'success',
					'rejected': 'danger',
					'cancelled': 'secondary'
				};
				var statusColor = statusColors[status] || 'secondary';
				modal.find('#viewStatus').html('<span class="badge bg-' + statusColor + '">' + status.charAt(0).toUpperCase() + status.slice(1) + '</span>');
				
				// Dates
				modal.find('#viewCreated').text(new Date(button.data('created')).toLocaleString());
				modal.find('#viewProcessed').text(button.data('processed') ? new Date(button.data('processed')).toLocaleString() : '-');
				
				// Set quick action button based on status
				var quickBtn = modal.find('#quickActionBtn');
				if (status == 'pending') {
					quickBtn.text('Start Processing').removeClass('btn-success').addClass('btn-primary');
					quickBtn.attr('onclick', 'startProcessing(' + button.data('id') + ')');
				} else if (status == 'processing') {
					quickBtn.text('Mark as Completed').removeClass('btn-primary').addClass('btn-success');
					quickBtn.attr('onclick', 'completeProcessing(' + button.data('id') + ')');
				} else {
					quickBtn.hide();
				}
			});
			
			// Status Modal
			$('#statusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var modal = $(this);
				
				modal.find('#statusWithdrawalId').val(button.data('id'));
				modal.find('#statusSelect').val(button.data('current-status'));
				
				// Show/hide transaction hash field based on status
				$('#statusSelect').change(function() {
					if ($(this).val() == 'completed') {
						$('#transactionHashField').show();
					} else {
						$('#transactionHashField').hide();
					}
				});
				
				// Trigger change to set initial state
				$('#statusSelect').trigger('change');
			});
			
			// Complete Modal
			$('#completeModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var modal = $(this);
				
				modal.find('#completeWithdrawalId').val(button.data('id'));
			});
			
			// Select All functionality
			$('#selectAll').change(function() {
				$('.row-checkbox').prop('checked', $(this).prop('checked'));
			});
			
			// Auto-refresh stats every 30 seconds
			startAutoRefresh();
		});
		
		// Select All withdrawals
		function selectAll() {
			$('.row-checkbox').prop('checked', true);
			$('#selectAll').prop('checked', true);
		}
		
		// Confirm Bulk Action
		function confirmBulkAction() {
			var selectedCount = $('.row-checkbox:checked').length;
			if (selectedCount === 0) {
				Swal.fire('Error', 'Please select at least one withdrawal.', 'error');
				return false;
			}
			
			var status = $('select[name="bulk_status"]').val();
			if (!status) {
				Swal.fire('Error', 'Please select an action.', 'error');
				return false;
			}
			
			var pin = $('input[name="admin_pin"]').val();
			if (!pin) {
				Swal.fire('Error', 'Please enter your PIN.', 'error');
				return false;
			}
			
			return confirm('Are you sure you want to update ' + selectedCount + ' withdrawal(s) to "' + status + '"?');
		}
		
		// Confirm Delete
		function confirmDelete(withdrawalId) {
			Swal.fire({
				title: 'Cancel Withdrawal?',
				html: `
					<p>This will cancel the withdrawal and return funds to the user.</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: 'Cancel Withdrawal',
				cancelButtonText: 'Back',
				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) {
					document.getElementById('deleteWithdrawalId').value = withdrawalId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		
		// Quick Actions
		function startProcessing(id) {
			$('#viewModal').modal('hide');
			$('#statusWithdrawalId').val(id);
			$('#statusSelect').val('processing');
			$('#statusModal').modal('show');
		}
		
		function completeProcessing(id) {
			$('#viewModal').modal('hide');
			$('#completeWithdrawalId').val(id);
			$('#completeModal').modal('show');
		}
		
		function quickAction() {
			// This is handled by the onclick attribute set in the modal
		}
		
		// Auto-refresh stats
		let refreshInterval;
		
		function startAutoRefresh() {
			refreshInterval = setInterval(function() {
				refreshStats();
			}, 30000); // 30 seconds
		}
		
		function refreshStats() {
			$.ajax({
				url: 'ajax/get_withdrawal_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.count);
						$('.bg-gradient-primary .text-white-50').text('$' + stats.total.amount);
						
						$('.bg-gradient-warning .fw-500').text(stats.pending.count);
						$('.bg-gradient-warning .text-white-50').text('$' + stats.pending.amount);
						
						$('.bg-gradient-info .fw-500').text(stats.processing.count);
						$('.bg-gradient-info .text-white-50').text('$' + stats.processing.amount);
						
						$('.bg-gradient-success .fw-500').text(stats.completed.count);
						$('.bg-gradient-success .text-white-50').text('$' + stats.completed.amount);
						
						$('.bg-gradient-danger .fw-500').text(stats.rejected.count);
						$('.bg-gradient-danger .text-white-50').text('$' + stats.rejected.amount);
						
						$('.bg-gradient-secondary .fw-500').text(stats.cancelled.count);
						$('.bg-gradient-secondary .text-white-50').text('$' + stats.cancelled.amount);
						
						// Update summary
						$('.text-primary').text('$' + stats.total.amount);
						$('.text-warning').text('$' + stats.pending.amount);
						$('.text-success').text('$' + stats.completed.amount);
						$('.text-danger').text('$' + (parseFloat(stats.rejected.amount) + parseFloat(stats.cancelled.amount)));
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}
		</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);
		}
		.row-checkbox {
			width: 18px;
			height: 18px;
		}
		#selectAll {
			width: 18px;
			height: 18px;
		}
		</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";
    }
}
?>