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

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

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

// PIN for confirmation (you should store this in database or environment variable)
$admin_pin = "1234"; // Change this to a secure PIN

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

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    $target_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'update_status':
                $new_status = isset($_POST['status']) ? $_POST['status'] : '';
                $reason = isset($_POST['reason']) ? mysqli_real_escape_string($conn, $_POST['reason']) : '';
                
                if ($target_id > 0 && in_array($new_status, ['verified', 'pending', 'rejected'])) {
                    // Get user details before update
                    $user_sql = "SELECT * FROM users WHERE id = $target_id";
                    $user_result = mysqli_query($conn, $user_sql);
                    $user_data = mysqli_fetch_assoc($user_result);
                    $old_status = $user_data['status'] ?? 'unknown';
                    $username = $user_data['username'] ?? '';
                    $email = $user_data['email'] ?? '';
                    $first_name = $user_data['first_name'] ?? 'User';
                    
                    $sql = "UPDATE users SET status = '$new_status', verification_date = NOW() WHERE id = $target_id";
                    if (mysqli_query($conn, $sql)) {
                        // Log activity
                        logAdminActivity(
                            'User Status Updated',
                            "Changed user ID $target_id status from $old_status to $new_status. Reason: $reason",
                            'Users',
                            $target_id,
                            'users'
                        );
                        
                        // NOTIFICATION: Status Changed (USER)
                        if ($new_status == 'verified') {
                            $mail_subject = "Account Verified Successfully!";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Congratulations <span class='user-name'>" . $first_name . "</span>! 🎉</h2>
                                                
                                                <p class='message'>
                                                    Great news! Your account has been <strong>verified</strong> by our admin team.
                                                </p>

                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Account Status:</strong> <span style='color: #28a745; font-weight: bold;'>VERIFIED ✅</span><br>
                                                        <strong>Verification Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Reason:</strong> " . ($reason ?: 'Account approved') . "<br>
                                                        <strong>Verified By:</strong> " . $admin_name . "
                                                    </div>
                                                </div>

                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/dashboard.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px;'>
                                                        Go to Dashboard
                                                    </a>
                                                </div>
                                            </div>";
                            
                            require_once("../proccess/mail_sender.php");
                        } elseif ($new_status == 'rejected') {
                            $mail_subject = "Account Verification Status";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                                
                                                <p class='message'>
                                                    Your account verification status has been updated.
                                                </p>

                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Account Status:</strong> <span style='color: #dc3545; font-weight: bold;'>REJECTED</span><br>
                                                        <strong>Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Reason:</strong> " . ($reason ?: 'Verification requirements not met') . "<br>
                                                    </div>
                                                </div>

                                                <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #856404;'>📋 Next Steps</h4>
                                                    <p style='color: #856404;'>
                                                        Please contact support for more information about your verification status.
                                                    </p>
                                                </div>

                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/contact.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px;'>
                                                        Contact Support
                                                    </a>
                                                </div>
                                            </div>";
                            
                            require_once("../proccess/mail_sender.php");
                        }
                        
                        // NOTIFICATION: Status Changed (ADMIN)
                        $admin_mail_subject = "User Status Updated - " . $username;
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>User Status Updated</h2>
                                                <p class='message'>
                                                    User status has been changed by " . $admin_name . "
                                                </p>
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>User ID:</strong> " . $target_id . "<br>
                                                        <strong>Username:</strong> " . $username . "<br>
                                                        <strong>Email:</strong> " . $email . "<br>
                                                        <strong>Old Status:</strong> " . $old_status . "<br>
                                                        <strong>New Status:</strong> " . $new_status . "<br>
                                                        <strong>Reason:</strong> " . ($reason ?: 'No reason provided') . "<br>
                                                        <strong>Updated By:</strong> " . $admin_name . "<br>
                                                        <strong>Update Time:</strong> " . date('F j, Y g:i A') . "
                                                    </div>
                                                </div>
                                            </div>";
                        
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "User status updated successfully!";
                    } else {
                        $error = "Failed to update user status.";
                    }
                }
                break;
                
            case 'update_balance':
                $balance_type = isset($_POST['balance_type']) ? $_POST['balance_type'] : '';
                $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
                $note = isset($_POST['note']) ? mysqli_real_escape_string($conn, $_POST['note']) : '';
                
                if ($target_id > 0 && $amount > 0) {
                    // Get user details
                    $user_sql = "SELECT * FROM users WHERE id = $target_id";
                    $user_result = mysqli_query($conn, $user_sql);
                    $user_data = mysqli_fetch_assoc($user_result);
                    $username = $user_data['username'] ?? '';
                    $email = $user_data['email'] ?? '';
                    $first_name = $user_data['first_name'] ?? 'User';
                    $old_balance = $user_data['fund_balance'] ?? 0;
                    
                    if ($balance_type == 'add') {
                        $sql = "UPDATE users SET fund_balance = fund_balance + $amount, available_balance = available_balance + $amount WHERE id = $target_id";
                        $action_desc = "Added $$amount to user balance";
                        $new_balance = $old_balance + $amount;
                        $txn_type = 'deposit';
                    } else {
                        $sql = "UPDATE users SET fund_balance = fund_balance - $amount, available_balance = available_balance - $amount WHERE id = $target_id";
                        $action_desc = "Deducted $$amount from user balance";
                        $new_balance = $old_balance - $amount;
                        $txn_type = 'withdrawal';
                    }
                    
                    if (mysqli_query($conn, $sql)) {
                        // Add transaction record
                        $txn_sql = "INSERT INTO transactions (user_id, amount, type, status, date, description, created_at) 
                                   VALUES ($target_id, $amount, '$txn_type', 'completed', NOW(), 'Admin manual adjustment: $note', NOW())";
                        mysqli_query($conn, $txn_sql);
                        $transaction_id = mysqli_insert_id($conn);
                        
                        // Log activity
                        logAdminActivity(
                            'User Balance Updated',
                            "$action_desc for user ID $target_id. Note: $note",
                            'Users',
                            $target_id,
                            'users'
                        );
                        
                        // NOTIFICATION: Balance Updated (USER)
                        $mail_subject = ($balance_type == 'add' ? 'Funds Added' : 'Funds Deducted') . " to Your Account";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                            
                                            <p class='message'>
                                                Your account balance has been updated by our admin team.
                                            </p>

                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Transaction ID:</strong> TXN-" . $transaction_id . "<br>
                                                    <strong>Action:</strong> " . ($balance_type == 'add' ? '➕ Funds Added' : '➖ Funds Deducted') . "<br>
                                                    <strong>Amount:</strong> <span style='color: " . ($balance_type == 'add' ? '#28a745' : '#dc3545') . "; font-weight: bold;'>$" . number_format($amount, 2) . "</span><br>
                                                    <strong>Previous Balance:</strong> $" . number_format($old_balance, 2) . "<br>
                                                    <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                    <strong>Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Note:</strong> " . ($note ?: 'No additional notes') . "<br>
                                                    <strong>Processed By:</strong> Admin (" . $admin_name . ")
                                                </div>
                                            </div>

                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/wallet.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px;'>
                                                    View Wallet
                                                </a>
                                            </div>
                                        </div>";
                        
                        require_once("../proccess/mail_sender.php");
                        
                        // NOTIFICATION: Balance Updated (ADMIN)
                        $admin_mail_subject = "Balance Adjustment - " . $username;
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>User Balance Adjustment</h2>
                                                <p class='message'>
                                                    A manual balance adjustment has been performed.
                                                </p>
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>User:</strong> " . $username . " (ID: " . $target_id . ")<br>
                                                        <strong>Email:</strong> " . $email . "<br>
                                                        <strong>Action:</strong> " . ($balance_type == 'add' ? 'Add' : 'Deduct') . "<br>
                                                        <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                        <strong>Previous Balance:</strong> $" . number_format($old_balance, 2) . "<br>
                                                        <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                        <strong>Note:</strong> " . ($note ?: 'No note') . "<br>
                                                        <strong>Adjusted By:</strong> " . $admin_name . "<br>
                                                        <strong>Date:</strong> " . date('F j, Y g:i A') . "
                                                    </div>
                                                </div>
                                            </div>";
                        
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "User balance updated successfully!";
                    } else {
                        $error = "Failed to update user balance.";
                    }
                }
                break;
                
            case 'delete_user':
                if ($target_id > 0) {
                    // Get user info before deletion
                    $user_sql = "SELECT * FROM users WHERE id = $target_id";
                    $user_result = mysqli_query($conn, $user_sql);
                    $user_data = mysqli_fetch_assoc($user_result);
                    $username = $user_data['username'] ?: '';
                    $email = $user_data['email'] ?: '';
                    $first_name = $user_data['first_name'] ?: 'User';
                    
                    // Soft delete (update status)
                    $sql = "UPDATE users SET status = 'rejected', verification_date = NOW() WHERE id = $target_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        // Log activity
                        logAdminActivity(
                            'User Deleted',
                            "Deleted user $username ($email)",
                            'Users',
                            $target_id,
                            'users'
                        );
                        
                        // NOTIFICATION: Account Deactivated (USER)
                        $mail_subject = "Account Deactivation Notice";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                            
                                            <p class='message'>
                                                Your account has been deactivated by our admin team.
                                            </p>

                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Account Status:</strong> <span style='color: #dc3545; font-weight: bold;'>DEACTIVATED</span><br>
                                                    <strong>Deactivation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Processed By:</strong> " . $admin_name . "
                                                </div>
                                            </div>

                                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #721c24;'>ℹ️ Important Information</h4>
                                                <p style='color: #721c24;'>
                                                    If you believe this was done in error or have questions, please contact our support team.
                                                </p>
                                            </div>

                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/contact.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px;'>
                                                    Contact Support
                                                </a>
                                            </div>
                                        </div>";
                        
                        require_once("../proccess/mail_sender.php");
                        
                        // NOTIFICATION: User Deleted (ADMIN)
                        $admin_mail_subject = "User Account Deactivated - " . $username;
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>User Account Deactivated</h2>
                                                <p class='message'>
                                                    A user account has been deactivated by " . $admin_name . "
                                                </p>
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>User ID:</strong> " . $target_id . "<br>
                                                        <strong>Username:</strong> " . $username . "<br>
                                                        <strong>Email:</strong> " . $email . "<br>
                                                        <strong>Action:</strong> Account Deactivation<br>
                                                        <strong>Deactivated By:</strong> " . $admin_name . "<br>
                                                        <strong>Deactivation Time:</strong> " . date('F j, Y g:i A') . "
                                                    </div>
                                                </div>
                                            </div>";
                        
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "User has been deactivated successfully!";
                    } else {
                        $error = "Failed to delete user.";
                    }
                }
                break;
        }
    }
}

// Get filter parameters
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';

// Build query
$sql = "SELECT * FROM users WHERE 1=1";
$count_sql = "SELECT COUNT(*) as total FROM users WHERE 1=1";

// Apply filters
if ($filter_status) {
    $sql .= " AND status = '$filter_status'";
    $count_sql .= " AND status = '$filter_status'";
}

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

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

// Add sorting
$sql .= " ORDER BY $sort $order";

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

<!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-users me-2"></i>User Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
												<i class="fas fa-user-plus me-1"></i> Add User
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['total']; ?></h1>
														<p class="text-white mb-0">Total Users</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['verified']; ?></h1>
														<p class="text-white mb-0">Verified</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['pending']; ?></h1>
														<p class="text-white mb-0">Pending</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $status_counts['rejected']; ?></h1>
														<p class="text-white mb-0">Rejected</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-8">
												<form method="GET" class="row">
													<div class="col-md-4">
														<div class="form-group">
															<select class="form-control" name="status" onchange="this.form.submit()">
																<option value="">All Status</option>
																<option value="verified" <?php echo $filter_status == 'verified' ? 'selected' : ''; ?>>Verified</option>
																<option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
																<option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
															</select>
														</div>
													</div>
													<div class="col-md-5">
														<div class="form-group">
															<input type="text" class="form-control" name="search" placeholder="Search users..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-3">
														<button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Search</button>
														<?php if ($search || $filter_status): ?>
															<a href="users.php" class="btn btn-secondary">Clear</a>
														<?php endif; ?>
													</div>
												</form>
											</div>
											<div class="col-md-4 text-end">
												<div class="btn-group">
													<button type="button" class="btn btn-light dropdown-toggle" data-bs-toggle="dropdown">
														<i class="fas fa-download me-1"></i> Export
													</button>
													<div class="dropdown-menu">
														<a class="dropdown-item" href="export_users.php?format=csv&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-csv"></i> CSV</a>
														<a class="dropdown-item" href="export_users.php?format=excel&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-excel"></i> Excel</a>
														<a class="dropdown-item" href="export_users.php?format=pdf&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-pdf"></i> PDF</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; ?>
										
										<!-- Users Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="usersTable">
												<thead class="bg-light">
													<tr>
														<th>ID</th>
														<th>User</th>
														<th>Contact</th>
														<th>Balance</th>
														<th>Status</th>
														<th>KYC</th>
														<th>Joined</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($user = mysqli_fetch_assoc($result)): ?>
															<?php
															$status_color = isset($status_colors[$user['status']]) ? $status_colors[$user['status']] : 'secondary';
															$joined_date = date('M d, Y', strtotime($user['registration_date']));
															$verification_date = $user['verification_date'] ? date('M d, Y', strtotime($user['verification_date'])) : 'Not verified';
															?>
															<tr>
																<td><?php echo $user['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($user['username']); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></small>
																		</div>
																	</div>
																</td>
																<td>
																	<p class="mb-0"><?php echo htmlspecialchars($user['email']); ?></p>
																	<small class="text-mute"><?php echo htmlspecialchars($user['phone']); ?></small>
																</td>
																<td>
																	<p class="mb-0 fw-500">$<?php echo number_format($user['fund_balance'], 2); ?></p>
																	<small class="text-mute">Available: $<?php echo number_format($user['available_balance'], 2); ?></small>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($user['status']); ?></span>
																	<?php if ($user['status'] == 'verified'): ?>
																		<br><small class="text-mute"><?php echo $verification_date; ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<?php if ($user['verification_completed']): ?>
																		<span class="badge bg-success"><i class="fas fa-check me-1"></i> Complete</span>
																	<?php elseif ($user['verification_sumitted']): ?>
																		<span class="badge bg-warning"><i class="fas fa-clock me-1"></i> Pending</span>
																	<?php else: ?>
																		<span class="badge bg-secondary"><i class="fas fa-times me-1"></i> Not Started</span>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $joined_date; ?></p>
																	<small class="text-mute"><?php echo time_ago($user['registration_date']); ?> ago</small>
																</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="view_user.php?id=<?php echo $user['id']; ?>"><i class="fas fa-eye me-2"></i> View</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#editUserModal" data-user-id="<?php echo $user['id']; ?>"><i class="fas fa-edit me-2"></i> Edit</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#statusModal" data-user-id="<?php echo $user['id']; ?>" data-current-status="<?php echo $user['status']; ?>"><i class="fas fa-user-check me-2"></i> Change Status</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#balanceModal" data-user-id="<?php echo $user['id']; ?>"><i class="fas fa-money-bill-wave me-2"></i> Adjust Balance</a>
																			<div class="dropdown-divider"></div>
																			<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $user['id']; ?>)"><i class="fas fa-trash me-2"></i> Delete</a>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="8" class="text-center py-20">
																<i class="fas fa-users fa-2x text-mute mb-3"></i>
																<h5>No users found</h5>
																<p class="text-mute">Try adjusting your search or filters</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Pagination would go here -->
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Changing User 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 User 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="user_id" id="statusUserId">
							
							<div class="mb-3">
								<label class="form-label">New Status</label>
								<select class="form-control" name="status" required>
									<option value="verified">Verified</option>
									<option value="pending">Pending</option>
									<option value="rejected">Rejected</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">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 Adjusting Balance -->
		<div class="modal fade" id="balanceModal" tabindex="-1" aria-labelledby="balanceModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="balanceModalLabel">Adjust User Balance</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_balance">
							<input type="hidden" name="user_id" id="balanceUserId">
							
							<div class="mb-3">
								<label class="form-label">Action</label>
								<select class="form-control" name="balance_type" required>
									<option value="add">Add Funds</option>
									<option value="deduct">Deduct Funds</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Amount ($)</label>
								<input type="number" class="form-control" name="amount" step="0.01" min="0.01" required placeholder="0.00">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Note (Optional)</label>
								<textarea class="form-control" name="note" rows="3" placeholder="Enter reason for balance adjustment..."></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 Balance</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Adding New User -->
		<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST" action="add_user.php">
						<div class="modal-header">
							<h5 class="modal-title" id="addUserModalLabel">Add New User</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">
									<div class="mb-3">
										<label class="form-label">Username <span class="text-danger">*</span></label>
										<input type="text" class="form-control" name="username" required>
									</div>
								</div>
								<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" required>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Password <span class="text-danger">*</span></label>
										<input type="password" class="form-control" name="password" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Confirm Password <span class="text-danger">*</span></label>
										<input type="password" class="form-control" name="confirm_password" required>
									</div>
								</div>
							</div>
							
							<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" 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" required>
									</div>
								</div>
							</div>
							
							<div class="row">
								<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" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">ID Number</label>
										<input type="text" class="form-control" name="id_number">
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Initial Balance ($)</label>
								<input type="number" class="form-control" name="initial_balance" step="0.01" min="0" value="0.00">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Status</label>
								<select class="form-control" name="status">
									<option value="verified">Verified</option>
									<option value="pending" selected>Pending</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Add User</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Deleting User (hidden form) -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_user">
			<input type="hidden" name="user_id" id="deleteUserId">
			<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
			$('#usersTable').DataTable({
				"pageLength": 25,
				"order": [[0, '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"
					}
				}
			});
			
			// Status Modal
			$('#statusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var userId = button.data('user-id');
				var currentStatus = button.data('current-status');
				var modal = $(this);
				
				modal.find('#statusUserId').val(userId);
				modal.find('select[name="status"]').val(currentStatus);
				modal.find('.modal-title').text('Change Status for User #' + userId);
			});
			
			// Balance Modal
			$('#balanceModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var userId = button.data('user-id');
				var modal = $(this);
				
				modal.find('#balanceUserId').val(userId);
				modal.find('.modal-title').text('Adjust Balance for User #' + userId);
			});
		});
		
		// Confirm Delete with PIN
		function confirmDelete(userId) {
			Swal.fire({
				title: 'Delete User?',
				html: `
					<p>This action cannot be undone. The user will be deactivated.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete User',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the delete form
					document.getElementById('deleteUserId').value = userId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_user_stats.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update the stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total);
						$('.bg-gradient-success .fw-500').text(stats.verified);
						$('.bg-gradient-warning .fw-500').text(stats.pending);
						$('.bg-gradient-danger .fw-500').text(stats.rejected);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}, 30000); // 30 seconds
		</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);
		}
		</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";
    }
}
?>