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

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

// PIN for confirmation
$admin_pin = "1234";

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

// 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';

// 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'] : '';
    $deposit_id = isset($_POST['deposit_id']) ? intval($_POST['deposit_id']) : 0;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'confirm_deposit':
                $reason = isset($_POST['reason']) ? mysqli_real_escape_string($conn, $_POST['reason']) : '';
                
                if ($deposit_id > 0) {
                    // Get deposit details
                    $deposit_sql = "SELECT d.*, u.username, u.email, u.first_name, u.last_name, u.fund_balance, u.available_balance 
                                   FROM deposits d 
                                   LEFT JOIN users u ON d.user_id = u.id 
                                   WHERE d.id = $deposit_id AND d.status = 'pending'";
                    $deposit_result = mysqli_query($conn, $deposit_sql);
                    
                    if ($deposit_row = mysqli_fetch_assoc($deposit_result)) {
                        $user_id = $deposit_row['user_id'];
                        $amount = $deposit_row['amount'];
                        $username = $deposit_row['username'];
                        $email = $deposit_row['email'];
                        $first_name = $deposit_row['first_name'];
                        $last_name = $deposit_row['last_name'];
                        $old_fund_balance = $deposit_row['fund_balance'];
                        $old_available_balance = $deposit_row['available_balance'];
                        $transaction_hash = $deposit_row['transaction_hash'] ?? 'N/A';
                        $deposit_note = $deposit_row['note'] ?? 'No note';
                        
                        // Start transaction
                        mysqli_begin_transaction($conn);
                        
                        try {
                            // Update deposit status
                            $update_sql = "UPDATE deposits SET 
                                          status = 'confirmed',
                                          confirmed_by = $admin_id,
                                          confirmed_at = NOW()
                                          WHERE id = $deposit_id";
                            
                            if (mysqli_query($conn, $update_sql)) {
                                // Update user balance
                                $new_fund_balance = $old_fund_balance + $amount;
                                $new_available_balance = $old_available_balance + $amount;
                                
                                $balance_sql = "UPDATE users SET 
                                               fund_balance = $new_fund_balance,
                                               available_balance = $new_available_balance
                                               WHERE id = $user_id";
                                
                                if (mysqli_query($conn, $balance_sql)) {
                                    // Add transaction record
                                    $txn_sql = "INSERT INTO transactions 
                                               (user_id, amount, type, status, date, description, reference_id, created_at) 
                                               VALUES 
                                               ($user_id, $amount, 'deposit', 'completed', NOW(), 
                                               'Deposit confirmed by admin', 'DEP-$deposit_id', NOW())";
                                    mysqli_query($conn, $txn_sql);
                                    $transaction_id = mysqli_insert_id($conn);
                                    
                                    // Log admin activity
                                    logAdminActivity(
                                        'Deposit Confirmed',
                                        "Confirmed deposit ID $deposit_id ($$amount) for user $username ($email)",
                                        'Deposits',
                                        $deposit_id,
                                        'deposits'
                                    );
                                    
                                    // Commit transaction
                                    mysqli_commit($conn);
                                    
                                    // NOTIFICATION: Deposit Confirmed (USER)
                                    $mail_subject = "Deposit Confirmed - $" . number_format($amount, 2);
                                    $mail_message = "<!-- Content Section -->
                                                    <div class='email-content'>
                                                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                                        
                                                        <p class='message'>
                                                            ✅ <strong>Your deposit has been confirmed!</strong><br>
                                                            The funds have been added to your account balance.
                                                        </p>

                                                        <!-- Deposit Details -->
                                                        <div class='details-section'>
                                                            <div class='detail-box'>
                                                                <strong>Deposit ID:</strong> DEP-" . $deposit_id . "<br>
                                                                <strong>Amount:</strong> <span style='color: #28a745; font-size: 18px;'>$" . number_format($amount, 2) . "</span><br>
                                                                <strong>Transaction Hash:</strong> " . $transaction_hash . "<br>
                                                                <strong>Note:</strong> " . $deposit_note . "<br>
                                                                <strong>Confirmed Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                                <strong>Confirmed By:</strong> Admin Team<br>
                                                                <strong>Old Balance:</strong> $" . number_format($old_fund_balance, 2) . "<br>
                                                                <strong>New Balance:</strong> <span style='color: #28a745;'>$" . number_format($new_fund_balance, 2) . "</span><br>
                                                                <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>COMPLETED</span>
                                                            </div>
                                                        </div>

                                                        <!-- What's Next -->
                                                        <div class='next-steps'>
                                                            <h3 style='color: #2c3e50;'>🚀 What's Next?</h3>
                                                            <p style='color: #6c757d;'>Your funds are now available for:</p>
                                                            <ul style='color: #6c757d;'>
                                                                <li>Subscribe to AI trading bots</li>
                                                                <li>Withdraw to your wallet</li>
                                                                <li>Transfer to other users</li>
                                                                <li>Hold in your balance</li>
                                                            </ul>
                                                        </div>

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

                                                        <!-- Support Section -->
                                                        <div class='support-section'>
                                                            <p class='support-text'>Thank you for funding your account!</p>
                                                            <a href='" . $myUrl . "/support.php' class='support-link'>Contact Support</a>
                                                        </div>
                                                    </div>";

                                    // Send user notification
                                    require_once("../proccess/mail_sender.php");
                                    
                                    // NOTIFICATION: Deposit Confirmed (ADMIN)
                                    $admin_mail_subject = "Deposit Confirmed - $" . number_format($amount, 2);
                                    $admin_mail_message = "<!-- Content Section -->
                                                        <div class='email-content'>
                                                            <h2 class='greeting'>Deposit Confirmed</h2>
                                                            
                                                            <p class='message'>
                                                                A deposit has been confirmed by an administrator.
                                                            </p>

                                                            <!-- Deposit Details -->
                                                            <div class='details-section'>
                                                                <div class='detail-box'>
                                                                    <strong>Deposit ID:</strong> DEP-" . $deposit_id . "<br>
                                                                    <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                                    <strong>User ID:</strong> " . $user_id . "<br>
                                                                    <strong>Username:</strong> " . $username . "<br>
                                                                    <strong>User Email:</strong> " . $email . "<br>
                                                                    <strong>Confirmed By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                                    <strong>Confirmation Time:</strong> " . date('F j, Y g:i A') . "<br>
                                                                    <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                                                    <strong>Status:</strong> <span style='color: #28a745;'>Confirmed</span>
                                                                </div>
                                                            </div>
                                                        </div>";

                                    // Send admin notification
                                    require_once("../proccess/admin_mailer.php");
                                    
                                    $success = "Deposit confirmed and user balance updated!";
                                } else {
                                    throw new Exception("Failed to update user balance");
                                }
                            } else {
                                throw new Exception("Failed to update deposit status");
                            }
                        } catch (Exception $e) {
                            mysqli_rollback($conn);
                            $error = $e->getMessage();
                        }
                    } else {
                        $error = "Deposit not found or already processed.";
                    }
                }
                break;
                
            case 'reject_deposit':
                $reason = isset($_POST['reason']) ? mysqli_real_escape_string($conn, $_POST['reason']) : '';
                
                if ($deposit_id > 0 && $reason) {
                    // Get deposit details
                    $deposit_sql = "SELECT d.*, u.username, u.email, u.first_name, u.amount, u.transaction_hash 
                                   FROM deposits d 
                                   LEFT JOIN users u ON d.user_id = u.id 
                                   WHERE d.id = $deposit_id AND d.status = 'pending'";
                    $deposit_result = mysqli_query($conn, $deposit_sql);
                    
                    if ($deposit_row = mysqli_fetch_assoc($deposit_result)) {
                        $user_id = $deposit_row['user_id'];
                        $amount = $deposit_row['amount'];
                        $username = $deposit_row['username'];
                        $email = $deposit_row['email'];
                        $first_name = $deposit_row['first_name'];
                        $transaction_hash = $deposit_row['transaction_hash'] ?? 'N/A';
                        
                        // Update deposit status
                        $update_sql = "UPDATE deposits SET 
                                      status = 'rejected',
                                      confirmed_by = $admin_id,
                                      confirmed_at = NOW()
                                      WHERE id = $deposit_id";
                        
                        if (mysqli_query($conn, $update_sql)) {
                            // Add transaction record for audit
                            $txn_sql = "INSERT INTO transactions 
                                       (user_id, amount, type, status, date, description, reference_id, created_at) 
                                       VALUES 
                                       ($user_id, $amount, 'deposit', 'rejected', NOW(), 
                                       'Deposit rejected by admin: $reason', 'DEP-$deposit_id', NOW())";
                            mysqli_query($conn, $txn_sql);
                            
                            // Log admin activity
                            logAdminActivity(
                                'Deposit Rejected',
                                "Rejected deposit ID $deposit_id ($$amount) for user $username ($email). Reason: $reason",
                                'Deposits',
                                $deposit_id,
                                'deposits'
                            );
                            
                            // NOTIFICATION: Deposit Rejected (USER)
                            $mail_subject = "Deposit Rejected - $" . number_format($amount, 2);
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                                
                                                <p class='message'>
                                                    ⚠️ <strong>Your deposit could not be confirmed.</strong><br>
                                                    Please review the details below.
                                                </p>

                                                <!-- Rejection Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Deposit ID:</strong> DEP-" . $deposit_id . "<br>
                                                        <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                        <strong>Transaction Hash:</strong> " . $transaction_hash . "<br>
                                                        <strong>Rejection Reason:</strong> <span style='color: #dc3545;'>" . $reason . "</span><br>
                                                        <strong>Rejected Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>REJECTED</span>
                                                    </div>
                                                </div>

                                                <!-- Common Reasons & Solutions -->
                                                <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #856404;'>💡 Need Help?</h4>
                                                    <p style='color: #856404;'>
                                                        <strong>Common reasons for rejection:</strong><br>
                                                        • Incorrect transaction hash<br>
                                                        • Amount mismatch<br>
                                                        • Unconfirmed blockchain transaction<br>
                                                        • Network congestion<br>
                                                        • Insufficient confirmations
                                                    </p>
                                                    <p style='color: #856404; margin-top: 10px;'>
                                                        <strong>Next steps:</strong> Verify your transaction details and submit a new deposit request.
                                                    </p>
                                                </div>

                                                <!-- Action Buttons -->
                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/deposit.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                        New Deposit
                                                    </a>
                                                    <a href='" . $myUrl . "/support.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                        Contact Support
                                                    </a>
                                                </div>

                                                <!-- Support Section -->
                                                <div class='support-section'>
                                                    <p class='support-text'>Need assistance with your deposit?</p>
                                                    <a href='" . $myUrl . "/support.php' class='support-link'>Contact Our Support Team</a>
                                                </div>
                                            </div>";

                            // Send user notification
                            require_once("../proccess/mail_sender.php");
                            
                            // NOTIFICATION: Deposit Rejected (ADMIN)
                            $admin_mail_subject = "Deposit Rejected - $" . number_format($amount, 2);
                            $admin_mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Deposit Rejected</h2>
                                                    
                                                    <p class='message'>
                                                        A deposit has been rejected by an administrator.
                                                    </p>

                                                    <!-- Rejection Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Deposit ID:</strong> DEP-" . $deposit_id . "<br>
                                                            <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                            <strong>User:</strong> " . $username . " (" . $email . ")<br>
                                                            <strong>Rejection Reason:</strong> " . $reason . "<br>
                                                            <strong>Rejected By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                            <strong>Rejection Time:</strong> " . date('F j, Y g:i A') . "<br>
                                                            <strong>Status:</strong> <span style='color: #dc3545;'>Rejected</span>
                                                        </div>
                                                    </div>
                                                </div>";

                            // Send admin notification
                            require_once("../proccess/admin_mailer.php");
                            
                            $success = "Deposit rejected successfully!";
                        } else {
                            $error = "Failed to reject deposit.";
                        }
                    } else {
                        $error = "Deposit not found or already processed.";
                    }
                } else {
                    $error = "Rejection reason is required.";
                }
                break;
                
            case 'add_deposit':
                $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
                $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
                $transaction_hash = isset($_POST['transaction_hash']) ? mysqli_real_escape_string($conn, $_POST['transaction_hash']) : '';
                $note = isset($_POST['note']) ? mysqli_real_escape_string($conn, $_POST['note']) : '';
                
                if ($user_id > 0 && $amount > 0) {
                    // Get user info
                    $user_sql = "SELECT username, email, first_name, last_name, fund_balance, available_balance FROM users WHERE id = $user_id";
                    $user_result = mysqli_query($conn, $user_sql);
                    
                    if ($user_row = mysqli_fetch_assoc($user_result)) {
                        $username = $user_row['username'];
                        $email = $user_row['email'];
                        $first_name = $user_row['first_name'];
                        $last_name = $user_row['last_name'];
                        $old_fund_balance = $user_row['fund_balance'];
                        $old_available_balance = $user_row['available_balance'];
                        
                        // Insert deposit
                        $insert_sql = "INSERT INTO deposits 
                                      (user_id, amount, transaction_hash, note, status, confirmed_by, created_at) 
                                      VALUES 
                                      ($user_id, $amount, '$transaction_hash', '$note', 'confirmed', $admin_id, NOW())";
                        
                        if (mysqli_query($conn, $insert_sql)) {
                            $new_deposit_id = mysqli_insert_id($conn);
                            
                            // Update user balance
                            $new_fund_balance = $old_fund_balance + $amount;
                            $new_available_balance = $old_available_balance + $amount;
                            
                            $balance_sql = "UPDATE users SET 
                                           fund_balance = $new_fund_balance,
                                           available_balance = $new_available_balance
                                           WHERE id = $user_id";
                            mysqli_query($conn, $balance_sql);
                            
                            // Add transaction record
                            $txn_sql = "INSERT INTO transactions 
                                       (user_id, amount, type, status, date, description, reference_id, created_at) 
                                       VALUES 
                                       ($user_id, $amount, 'deposit', 'completed', NOW(), 
                                       'Manual deposit by admin: $note', 'DEP-$new_deposit_id', NOW())";
                            mysqli_query($conn, $txn_sql);
                            
                            // Log admin activity
                            logAdminActivity(
                                'Manual Deposit Added',
                                "Added manual deposit of $$amount for user $username ($email). Note: $note",
                                'Deposits',
                                $new_deposit_id,
                                'deposits'
                            );
                            
                            // NOTIFICATION: Manual Deposit Added (USER)
                            $mail_subject = "Manual Deposit Added - $" . number_format($amount, 2);
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                                
                                                <p class='message'>
                                                    💰 <strong>A manual deposit has been added to your account!</strong><br>
                                                    Your balance has been updated by our admin team.
                                                </p>

                                                <!-- Deposit Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Deposit ID:</strong> DEP-" . $new_deposit_id . "<br>
                                                        <strong>Amount:</strong> <span style='color: #28a745; font-size: 18px;'>$" . number_format($amount, 2) . "</span><br>
                                                        <strong>Transaction Hash:</strong> " . ($transaction_hash ?: 'N/A') . "<br>
                                                        <strong>Note:</strong> " . ($note ?: 'No note') . "<br>
                                                        <strong>Date Added:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Added By:</strong> Admin Team<br>
                                                        <strong>Old Balance:</strong> $" . number_format($old_fund_balance, 2) . "<br>
                                                        <strong>New Balance:</strong> <span style='color: #28a745;'>$" . number_format($new_fund_balance, 2) . "</span><br>
                                                        <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>COMPLETED</span>
                                                    </div>
                                                </div>

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

                                                <!-- Support Section -->
                                                <div class='support-section'>
                                                    <p class='support-text'>Your account has been credited successfully!</p>
                                                </div>
                                            </div>";

                            // Send user notification
                            require_once("../proccess/mail_sender.php");
                            
                            // NOTIFICATION: Manual Deposit Added (ADMIN)
                            $admin_mail_subject = "Manual Deposit Added - $" . number_format($amount, 2);
                            $admin_mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Manual Deposit Added</h2>
                                                    
                                                    <p class='message'>
                                                        A manual deposit has been added by an administrator.
                                                    </p>

                                                    <!-- Deposit Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Deposit ID:</strong> DEP-" . $new_deposit_id . "<br>
                                                            <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                            <strong>User:</strong> " . $username . " (" . $email . ")<br>
                                                            <strong>User ID:</strong> " . $user_id . "<br>
                                                            <strong>Added By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                            <strong>Note:</strong> " . $note . "<br>
                                                            <strong>Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                            <strong>Status:</strong> <span style='color: #28a745;'>Completed</span>
                                                        </div>
                                                    </div>
                                                </div>";

                            // Send admin notification
                            require_once("../proccess/admin_mailer.php");
                            
                            $success = "Manual deposit added successfully!";
                        } else {
                            $error = "Failed to add deposit.";
                        }
                    } else {
                        $error = "User not found.";
                    }
                } else {
                    $error = "Invalid user ID or amount.";
                }
                break;
        }
    }
}

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

// Build query
$sql = "SELECT d.*, u.username, u.email, u.phone, a.name as admin_name 
        FROM deposits d 
        LEFT JOIN users u ON d.user_id = u.id 
        LEFT JOIN admins a ON d.confirmed_by = a.id 
        WHERE 1=1";

$count_sql = "SELECT COUNT(*) as total FROM deposits d WHERE 1=1";

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

if ($search) {
    $sql .= " AND (u.username LIKE '%$search%' OR u.email LIKE '%$search%' OR d.transaction_hash LIKE '%$search%' OR d.note LIKE '%$search%')";
    $count_sql .= " AND EXISTS (SELECT 1 FROM users u WHERE u.id = d.user_id AND (u.username LIKE '%$search%' OR u.email LIKE '%$search%'))";
}

if ($date_from && $date_to) {
    $sql .= " AND DATE(d.created_at) BETWEEN '$date_from' AND '$date_to'";
    $count_sql .= " AND DATE(d.created_at) BETWEEN '$date_from' AND '$date_to'";
} elseif ($date_from) {
    $sql .= " AND DATE(d.created_at) >= '$date_from'";
    $count_sql .= " AND DATE(d.created_at) >= '$date_from'";
} elseif ($date_to) {
    $sql .= " AND DATE(d.created_at) <= '$date_to'";
    $count_sql .= " AND DATE(d.created_at) <= '$date_to'";
}

// Get counts for stats
$count_result = mysqli_query($conn, "SELECT status, COUNT(*) as count, COALESCE(SUM(amount), 0) as total FROM deposits GROUP BY status");
$status_counts = array(
    'pending' => array('count' => 0, 'total' => 0),
    'confirmed' => array('count' => 0, 'total' => 0),
    'rejected' => array('count' => 0, 'total' => 0),
    'all' => array('count' => 0, 'total' => 0)
);

while ($row = mysqli_fetch_assoc($count_result)) {
    $status_counts[$row['status']] = array(
        'count' => $row['count'],
        'total' => $row['total']
    );
    $status_counts['all']['count'] += $row['count'];
    $status_counts['all']['total'] += $row['total'];
}

// Add sorting
$sql .= " ORDER BY d.$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-download me-2"></i>Deposits Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addDepositModal">
												<i class="fas fa-plus-circle me-1"></i> Add Deposit
											</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['all']['count']; ?></h1>
														<p class="text-white mb-0">Total Deposits</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['all']['total'], 2); ?></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']['count']; ?></h1>
														<p class="text-white mb-0">Pending</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['pending']['total'], 2); ?></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['confirmed']['count']; ?></h1>
														<p class="text-white mb-0">Confirmed</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['confirmed']['total'], 2); ?></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']['count']; ?></h1>
														<p class="text-white mb-0">Rejected</p>
														<p class="text-white-50 mb-0">$<?php echo number_format($status_counts['rejected']['total'], 2); ?></p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row">
													<div class="col-md-2">
														<div class="form-group">
															<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="confirmed" <?php echo $filter_status == 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
																<option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<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-2">
														<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-4">
														<div class="form-group">
															<input type="text" class="form-control" name="search" placeholder="Search user, email, or hash..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-2">
														<button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Search</button>
														<?php if ($search || $filter_status || $date_from || $date_to): ?>
															<a href="deposits.php" class="btn btn-secondary mt-1">Clear</a>
														<?php endif; ?>
													</div>
												</form>
											</div>
										</div>
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Deposits Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="depositsTable">
												<thead class="bg-light">
													<tr>
														<th>ID</th>
														<th>User</th>
														<th>Amount</th>
														<th>Transaction Hash</th>
														<th>Status</th>
														<th>Date</th>
														<th>Confirmed By</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($deposit = mysqli_fetch_assoc($result)): ?>
															<?php
															$status_color = isset($status_colors[$deposit['status']]) ? $status_colors[$deposit['status']] : 'secondary';
															$created_date = date('M d, Y H:i', strtotime($deposit['created_at']));
															$confirmed_date = $deposit['confirmed_at'] ? date('M d, Y H:i', strtotime($deposit['confirmed_at'])) : 'N/A';
															?>
															<tr>
																<td><?php echo $deposit['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($deposit['username']); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($deposit['email']); ?></small>
																		</div>
																	</div>
																</td>
																<td class="fw-500">$<?php echo number_format($deposit['amount'], 2); ?></td>
																<td>
																	<?php if ($deposit['transaction_hash']): ?>
																		<code class="text-truncate d-block" style="max-width: 150px;" title="<?php echo htmlspecialchars($deposit['transaction_hash']); ?>">
																			<?php echo htmlspecialchars(substr($deposit['transaction_hash'], 0, 20) . '...'); ?>
																		</code>
																		<small class="text-mute">Click to view full</small>
																	<?php else: ?>
																		<span class="text-mute">N/A</span>
																	<?php endif; ?>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($deposit['status']); ?></span>
																	<?php if ($deposit['status'] != 'pending'): ?>
																		<br><small class="text-mute"><?php echo $confirmed_date; ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $created_date; ?></p>
																	<small class="text-mute"><?php echo time_ago($deposit['created_at']); ?> ago</small>
																</td>
																<td>
																	<?php if ($deposit['admin_name']): ?>
																		<?php echo htmlspecialchars($deposit['admin_name']); ?>
																	<?php else: ?>
																		<span class="text-mute">Pending</span>
																	<?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="#viewDepositModal" 
																			   data-deposit-id="<?php echo $deposit['id']; ?>">
																				<i class="fas fa-eye me-2"></i> View Details
																			</a>
																			
																			<?php if ($deposit['status'] == 'pending'): ?>
																				<a class="dropdown-item text-success" href="#" data-bs-toggle="modal" data-bs-target="#confirmDepositModal" 
																				   data-deposit-id="<?php echo $deposit['id']; ?>"
																				   data-amount="<?php echo $deposit['amount']; ?>"
																				   data-username="<?php echo htmlspecialchars($deposit['username']); ?>">
																					<i class="fas fa-check-circle me-2"></i> Confirm Deposit
																				</a>
																				<a class="dropdown-item text-danger" href="#" data-bs-toggle="modal" data-bs-target="#rejectDepositModal" 
																				   data-deposit-id="<?php echo $deposit['id']; ?>"
																				   data-amount="<?php echo $deposit['amount']; ?>"
																				   data-username="<?php echo htmlspecialchars($deposit['username']); ?>">
																					<i class="fas fa-times-circle me-2"></i> Reject Deposit
																				</a>
																			<?php endif; ?>
																			
																			<?php if ($deposit['receipt_path']): ?>
																				<a class="dropdown-item" href="<?php echo $deposit['receipt_path']; ?>" target="_blank">
																					<i class="fas fa-receipt me-2"></i> View Receipt
																				</a>
																			<?php endif; ?>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="8" class="text-center py-20">
																<i class="fas fa-download fa-2x text-mute mb-3"></i>
																<h5>No deposits found</h5>
																<p class="text-mute">Try adjusting your search or filters</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Export Button -->
										<div class="mt-3 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_deposits.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_deposits.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>
													<a class="dropdown-item" href="export_deposits.php?format=pdf&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-pdf"></i> PDF
													</a>
												</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 Deposit Details -->
		<div class="modal fade" id="viewDepositModal" tabindex="-1" aria-labelledby="viewDepositModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="viewDepositModalLabel">Deposit Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="depositDetails">
						<!-- Details will be loaded via JavaScript -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Confirming Deposit -->
		<div class="modal fade" id="confirmDepositModal" tabindex="-1" aria-labelledby="confirmDepositModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="confirmDepositModalLabel">Confirm Deposit</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="confirm_deposit">
							<input type="hidden" name="deposit_id" id="confirmDepositId">
							
							<div class="alert alert-info">
								<i class="fas fa-info-circle me-2"></i> 
								<span id="confirmMessage">Are you sure you want to confirm this deposit?</span>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Confirmation Reason (Optional)</label>
								<textarea class="form-control" name="reason" rows="3" placeholder="Enter any notes or reasons for confirmation..."></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-success">Confirm Deposit</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Rejecting Deposit -->
		<div class="modal fade" id="rejectDepositModal" tabindex="-1" aria-labelledby="rejectDepositModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="rejectDepositModalLabel">Reject Deposit</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="reject_deposit">
							<input type="hidden" name="deposit_id" id="rejectDepositId">
							
							<div class="alert alert-warning">
								<i class="fas fa-exclamation-triangle me-2"></i> 
								<span id="rejectMessage">Are you sure you want to reject this deposit?</span>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Rejection Reason <span class="text-danger">*</span></label>
								<textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for rejection..." required></textarea>
								<small class="text-mute">This reason will be recorded and may be shown to the user</small>
							</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-danger">Reject Deposit</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Adding Deposit -->
		<div class="modal fade" id="addDepositModal" tabindex="-1" aria-labelledby="addDepositModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="addDepositModalLabel">Add Manual Deposit</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="add_deposit">
							
							<div class="mb-3">
								<label class="form-label">Select User <span class="text-danger">*</span></label>
								<select class="form-control" name="user_id" id="userSelect" required>
									<option value="">Select a user...</option>
									<?php
									$users_sql = "SELECT id, username, email FROM users WHERE status = 'verified' ORDER BY username";
									$users_result = mysqli_query($conn, $users_sql);
									while ($user = mysqli_fetch_assoc($users_result)) {
										echo "<option value='{$user['id']}'>{$user['username']} ({$user['email']})</option>";
									}
									?>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Amount ($) <span class="text-danger">*</span></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">Transaction Hash (Optional)</label>
								<input type="text" class="form-control" name="transaction_hash" placeholder="Enter transaction hash if available">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Note (Optional)</label>
								<textarea class="form-control" name="note" rows="3" placeholder="Enter any notes about this deposit..."></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">Add Deposit</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		  
    
		
		
		  <?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
			$('#depositsTable').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"
					}
				}
			});
			
			// View Deposit Modal
			$('#viewDepositModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var depositId = button.data('deposit-id');
				var modal = $(this);
				
				// Load deposit details via AJAX
				$.ajax({
					url: 'ajax/get_deposit_details.php',
					type: 'GET',
					data: { id: depositId },
					success: function(data) {
						modal.find('#depositDetails').html(data);
					}
				});
			});
			
			// Confirm Deposit Modal
			$('#confirmDepositModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var depositId = button.data('deposit-id');
				var amount = button.data('amount');
				var username = button.data('username');
				var modal = $(this);
				
				modal.find('#confirmDepositId').val(depositId);
				modal.find('#confirmMessage').html(
					'Confirm deposit of <strong>$' + amount + '</strong> for user <strong>' + username + '</strong>?'
				);
			});
			
			// Reject Deposit Modal
			$('#rejectDepositModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var depositId = button.data('deposit-id');
				var amount = button.data('amount');
				var username = button.data('username');
				var modal = $(this);
				
				modal.find('#rejectDepositId').val(depositId);
				modal.find('#rejectMessage').html(
					'Reject deposit of <strong>$' + amount + '</strong> for user <strong>' + username + '</strong>?'
				);
			});
			
			// User search in add deposit modal
			$('#userSelect').select2({
				placeholder: "Search for a user...",
				allowClear: true,
				width: '100%'
			});
		});
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_deposit_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.all.count);
						$('.bg-gradient-primary .text-white-50').text('$' + stats.all.total);
						
						$('.bg-gradient-warning .fw-500').text(stats.pending.count);
						$('.bg-gradient-warning .text-white-50').text('$' + stats.pending.total);
						
						$('.bg-gradient-success .fw-500').text(stats.confirmed.count);
						$('.bg-gradient-success .text-white-50').text('$' + stats.confirmed.total);
						
						$('.bg-gradient-danger .fw-500').text(stats.rejected.count);
						$('.bg-gradient-danger .text-white-50').text('$' + stats.rejected.total);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Deposit Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}, 30000); // 30 seconds
		
		// Helper function to show full transaction hash
		function showFullHash(hash) {
			Swal.fire({
				title: 'Transaction Hash',
				html: '<code>' + hash + '</code>',
				icon: 'info',
				confirmButtonText: 'Copy',
				showCancelButton: true,
				cancelButtonText: 'Close',
				preConfirm: () => {
					navigator.clipboard.writeText(hash);
					return 'Copied!';
				}
			}).then((result) => {
				if (result.isConfirmed) {
					Swal.fire('Copied!', 'Transaction hash copied to clipboard', 'success');
				}
			});
		}
		
		// Show sweet alert for successful deposit confirmation
		<?php if (isset($success) && strpos($success, 'confirmed') !== false): ?>
		Swal.fire({
			icon: 'success',
			title: 'Deposit Confirmed',
			text: '<?php echo $success; ?>',
			timer: 3000,
			showConfirmButton: false
		});
		<?php endif; ?>
		
		// Show sweet alert for successful deposit rejection
		<?php if (isset($success) && strpos($success, 'rejected') !== false): ?>
		Swal.fire({
			icon: 'success',
			title: 'Deposit Rejected',
			text: '<?php echo $success; ?>',
			timer: 3000,
			showConfirmButton: false
		});
		<?php endif; ?>
		
		// Show sweet alert for successful manual deposit
		<?php if (isset($success) && strpos($success, 'manual') !== false): ?>
		Swal.fire({
			icon: 'success',
			title: 'Deposit Added',
			text: '<?php echo $success; ?>',
			timer: 3000,
			showConfirmButton: false
		});
		<?php endif; ?>
		</script>
		
		<!-- Select2 CSS -->
		<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
		<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></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);
		}
		code {
			cursor: pointer;
			background: #f8f9fa;
			padding: 2px 5px;
			border-radius: 3px;
			border: 1px solid #dee2e6;
		}
		code:hover {
			background: #e9ecef;
		}
		.select2-container--default .select2-selection--single {
			height: 38px;
			padding: 5px;
			border: 1px solid #ced4da;
			border-radius: 0.25rem;
		}
		</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";
    }
}
?>