<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch admin data from admin_table
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$admin = $result->fetch_assoc();
$stmt->close();

// Initialize variables
$message = '';
$message_type = '';
$selected_withdrawal = null;
$show_view_modal = false;

// Handle Withdrawal Actions (Approve, Reject, Update)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $withdrawal_id = intval($_POST['withdrawal_id']);
    
    // Get withdrawal details
    $query = "SELECT w.*, u.email, u.username, u.full_name, u.account_balance, 
                     p.wallet_name, p.bank_name, p.payment_type 
              FROM withdrawals w 
              JOIN users u ON w.user_id = u.id 
              LEFT JOIN payment_tb p ON w.payment_method_id = p.id 
              WHERE w.id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $withdrawal_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $message = "Withdrawal not found!";
        $message_type = "error";
    } else {
        $withdrawal = $result->fetch_assoc();
        $user_id = $withdrawal['user_id'];
        $amount = $withdrawal['amount'];
        $net_amount = $withdrawal['net_amount'];
        $fee_amount = $withdrawal['fee_amount'];
        $user_email = $withdrawal['email'];
        $user_name = $withdrawal['full_name'] ?: $withdrawal['username'];
        $transaction_id = $withdrawal['transaction_id'];
        
        switch($action) {
            case 'approve':
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Check if user has sufficient balance before deducting
                    $balance_check = $conn->prepare("SELECT account_balance FROM users WHERE id = ?");
                    $balance_check->bind_param("i", $user_id);
                    $balance_check->execute();
                    $balance_result = $balance_check->get_result();
                    $user_balance = $balance_result->fetch_assoc()['account_balance'];

                    if ($user_balance < $amount) {
                        throw new Exception("Insufficient balance. User has $" . number_format($user_balance, 2) . " but requested $" . number_format($amount, 2));
                    }
                    
                    // Update withdrawal status to completed
                    $update_query = "UPDATE withdrawals SET 
                                    status = 'completed',
                                    processed_by = ?,
                                    processed_at = NOW(),
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("ii", $admin_id, $withdrawal_id);
                    $update_stmt->execute();
                    
                    // DEDUCT AMOUNT FROM USER'S ACCOUNT BALANCE
                    $deduct_query = "UPDATE users SET 
                                    account_balance = account_balance - ?,
                                    total_withdrawals = total_withdrawals + ?,
                                    last_withdrawal = NOW(),
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $deduct_stmt = $conn->prepare($deduct_query);
                    $deduct_stmt->bind_param("ddi", $amount, $amount, $user_id);
                    $deduct_stmt->execute();
                    
                    // Create transaction record for the withdrawal
                    $table_check = $conn->query("SHOW TABLES LIKE 'transactions'");
                    if ($table_check->num_rows > 0) {
                        // Check the structure of the transactions table
                        $structure_check = $conn->query("DESCRIBE transactions");
                        $columns = [];
                        while ($row = $structure_check->fetch_assoc()) {
                            $columns[$row['Field']] = $row['Field'];
                        }
                        
                        // Insert transaction based on actual table structure
                        $reference = 'WTH' . time() . rand(1000, 9999);
                        if (isset($columns['transaction_type'])) {
                            $transaction_query = "INSERT INTO transactions 
                                                 (user_id, transaction_type, amount, description, status, reference, created_at) 
                                                 VALUES (?, 'withdrawal', ?, 'Withdrawal processed', 'completed', ?, NOW())";
                            $transaction_stmt = $conn->prepare($transaction_query);
                            $transaction_stmt->bind_param("ids", $user_id, $net_amount, $reference);
                        } else if (isset($columns['type'])) {
                            $transaction_query = "INSERT INTO transactions 
                                                 (user_id, type, amount, description, status, reference, created_at) 
                                                 VALUES (?, 'withdrawal', ?, 'Withdrawal processed', 'completed', ?, NOW())";
                            $transaction_stmt = $conn->prepare($transaction_query);
                            $transaction_stmt->bind_param("ids", $user_id, $net_amount, $reference);
                        } else {
                            $transaction_query = "INSERT INTO transactions 
                                                 (user_id, amount, description, status, reference, created_at) 
                                                 VALUES (?, ?, 'Withdrawal processed', 'completed', ?, NOW())";
                            $transaction_stmt = $conn->prepare($transaction_query);
                            $transaction_stmt->bind_param("ids", $user_id, $net_amount, $reference);
                        }
                        
                        if (isset($transaction_stmt)) {
                            $transaction_stmt->execute();
                        }
                    }
                    
                    // Create notification
                    $table_check = $conn->query("SHOW TABLES LIKE 'notifications'");
                    if ($table_check->num_rows > 0) {
                        $notification_query = "INSERT INTO notifications 
                                              (user_id, notification_type, title, message, created_at) 
                                              VALUES (?, 'transaction', 'Withdrawal Approved', ?, NOW())";
                        $notification_msg = "Your withdrawal of $" . number_format($amount, 2) . " has been approved and processed. Net amount: $" . number_format($net_amount, 2) . ($fee_amount > 0 ? " (Fee: $" . number_format($fee_amount, 2) . ")" : "");
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_msg);
                        $notification_stmt->execute();
                    }
                    
                    $conn->commit();
                    
                    // Send email notification
                    $email_sent = sendWithdrawalApprovalEmail($user_email, $user_name, $amount, $net_amount, $fee_amount, $transaction_id, $withdrawal_id);
                    
                    $message = "Withdrawal approved successfully! Amount deducted from user's account balance.";
                    if ($email_sent) {
                        $message .= " Email notification sent.";
                    } else {
                        $message .= " Email notification failed to send.";
                    }
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error approving withdrawal: " . $e->getMessage();
                    $message_type = "error";
                }
                break;
                
            case 'reject':
                $admin_notes = trim($_POST['admin_notes'] ?? '');
                
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Update withdrawal status to rejected
                    $update_query = "UPDATE withdrawals SET 
                                    status = 'rejected',
                                    admin_notes = ?,
                                    processed_by = ?,
                                    processed_at = NOW(),
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("sii", $admin_notes, $admin_id, $withdrawal_id);
                    $update_stmt->execute();
                    
                    // Refund amount back to user's account balance
                    $refund_query = "UPDATE users SET 
                                    account_balance = account_balance + ?,
                                    total_withdrawals = total_withdrawals - ?,
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $refund_stmt = $conn->prepare($refund_query);
                    $refund_stmt->bind_param("ddi", $amount, $amount, $user_id);
                    $refund_stmt->execute();
                    
                    // Create notification
                    $table_check = $conn->query("SHOW TABLES LIKE 'notifications'");
                    if ($table_check->num_rows > 0) {
                        $notification_query = "INSERT INTO notifications 
                                              (user_id, notification_type, title, message, created_at) 
                                              VALUES (?, 'transaction', 'Withdrawal Rejected', ?, NOW())";
                        $notification_msg = "Your withdrawal of $" . number_format($amount, 2) . " has been rejected and funds have been returned to your account.";
                        if (!empty($admin_notes)) {
                            $notification_msg .= " Reason: " . $admin_notes;
                        }
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_msg);
                        $notification_stmt->execute();
                    }
                    
                    $conn->commit();
                    
                    // Send email notification
                    $email_sent = sendWithdrawalRejectionEmail($user_email, $user_name, $amount, $transaction_id, $admin_notes);
                    
                    $message = "Withdrawal rejected successfully! Amount refunded to user's account.";
                    if ($email_sent) {
                        $message .= " Email notification sent.";
                    } else {
                        $message .= " Email notification failed to send.";
                    }
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error rejecting withdrawal: " . $e->getMessage();
                    $message_type = "error";
                }
                break;
                
            case 'processing':
                $update_query = "UPDATE withdrawals SET 
                                status = 'processing',
                                processed_by = ?,
                                processed_at = NOW(),
                                updated_at = NOW()
                                WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("ii", $admin_id, $withdrawal_id);
                
                if ($update_stmt->execute()) {
                    // Create notification
                    $table_check = $conn->query("SHOW TABLES LIKE 'notifications'");
                    if ($table_check->num_rows > 0) {
                        $notification_query = "INSERT INTO notifications 
                                              (user_id, notification_type, title, message, created_at) 
                                              VALUES (?, 'transaction', 'Withdrawal Processing', ?, NOW())";
                        $notification_msg = "Your withdrawal of $" . number_format($amount, 2) . " is now being processed.";
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_msg);
                        $notification_stmt->execute();
                    }
                    
                    // Send email notification
                    $email_sent = sendWithdrawalProcessingEmail($user_email, $user_name, $amount, $transaction_id);
                    
                    $message = "Withdrawal status updated to processing!";
                    if ($email_sent) {
                        $message .= " Email notification sent.";
                    } else {
                        $message .= " Email notification failed to send.";
                    }
                    $message_type = "success";
                } else {
                    $message = "Error updating withdrawal status: " . $update_stmt->error;
                    $message_type = "error";
                }
                break;
                
            case 'update_notes':
                $admin_notes = trim($_POST['admin_notes'] ?? '');
                
                $update_query = "UPDATE withdrawals SET 
                                admin_notes = ?,
                                updated_at = NOW()
                                WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("si", $admin_notes, $withdrawal_id);
                
                if ($update_stmt->execute()) {
                    $message = "Admin notes updated successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error updating notes: " . $update_stmt->error;
                    $message_type = "error";
                }
                break;
                
            case 'pending':
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // First, check if we need to refund the amount (if it was rejected)
                    $status_check = $conn->prepare("SELECT status FROM withdrawals WHERE id = ?");
                    $status_check->bind_param("i", $withdrawal_id);
                    $status_check->execute();
                    $status_result = $status_check->get_result();
                    $current_status = $status_result->fetch_assoc()['status'];
                    
                    // If status was rejected, we need to deduct the refunded amount
                    if ($current_status == 'rejected') {
                        $deduct_query = "UPDATE users SET 
                                        account_balance = account_balance - ?,
                                        total_withdrawals = total_withdrawals + ?,
                                        updated_at = NOW()
                                        WHERE id = ?";
                        $deduct_stmt = $conn->prepare($deduct_query);
                        $deduct_stmt->bind_param("ddi", $amount, $amount, $user_id);
                        $deduct_stmt->execute();
                    }
                    
                    // If status was completed, we need to refund the deducted amount
                    if ($current_status == 'completed') {
                        $refund_query = "UPDATE users SET 
                                        account_balance = account_balance + ?,
                                        total_withdrawals = total_withdrawals - ?,
                                        updated_at = NOW()
                                        WHERE id = ?";
                        $refund_stmt = $conn->prepare($refund_query);
                        $refund_stmt->bind_param("ddi", $amount, $amount, $user_id);
                        $refund_stmt->execute();
                    }
                    
                    // Set withdrawal back to pending
                    $update_query = "UPDATE withdrawals SET 
                                    status = 'pending',
                                    processed_by = NULL,
                                    processed_at = NULL,
                                    admin_notes = NULL,
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("i", $withdrawal_id);
                    $update_stmt->execute();
                    
                    $conn->commit();
                    
                    $message = "Withdrawal status reset to pending!";
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error resetting withdrawal: " . $e->getMessage();
                    $message_type = "error";
                }
                break;
        }
    }
    $stmt->close();
}

// Handle Quick Actions
$actions = ['approve', 'reject', 'processing', 'view', 'delete', 'pending'];
foreach ($actions as $action) {
    if (isset($_GET[$action])) {
        $withdrawal_id = intval($_GET[$action]);
        
        if ($action == 'view') {
            $show_view_modal = true;
            $query = "SELECT w.*, u.email, u.username, u.full_name, u.phone, u.account_balance,
                             p.wallet_name, p.bank_name, p.payment_type, p.wallet_address, 
                             p.account_name, p.account_number, p.bank_name as payment_bank_name,
                             p.swift_code, p.iban, p.crypto_network,
                             a.email as processed_by_admin_email
                      FROM withdrawals w 
                      JOIN users u ON w.user_id = u.id 
                      LEFT JOIN payment_tb p ON w.payment_method_id = p.id 
                      LEFT JOIN admin_table a ON w.processed_by = a.id 
                      WHERE w.id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $withdrawal_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $selected_withdrawal = $result->fetch_assoc();
            $stmt->close();
        } elseif ($action == 'delete') {
            // Get withdrawal details first
            $check_query = "SELECT status, amount, user_id FROM withdrawals WHERE id = ?";
            $check_stmt = $conn->prepare($check_query);
            $check_stmt->bind_param("i", $withdrawal_id);
            $check_stmt->execute();
            $check_result = $check_stmt->get_result();
            
            if ($check_result->num_rows > 0) {
                $withdrawal_data = $check_result->fetch_assoc();
                
                // If withdrawal is pending or processing, we need to refund the amount
                if (in_array($withdrawal_data['status'], ['pending', 'processing'])) {
                    // Refund amount to user
                    $refund_query = "UPDATE users SET 
                                    account_balance = account_balance + ?,
                                    total_withdrawals = total_withdrawals - ?,
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $refund_stmt = $conn->prepare($refund_query);
                    $refund_stmt->bind_param("ddi", $withdrawal_data['amount'], $withdrawal_data['amount'], $withdrawal_data['user_id']);
                    $refund_stmt->execute();
                }
                
                // If withdrawal is completed, refund the deducted amount
                if ($withdrawal_data['status'] == 'completed') {
                    $refund_query = "UPDATE users SET 
                                    account_balance = account_balance + ?,
                                    total_withdrawals = total_withdrawals - ?,
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $refund_stmt = $conn->prepare($refund_query);
                    $refund_stmt->bind_param("ddi", $withdrawal_data['amount'], $withdrawal_data['amount'], $withdrawal_data['user_id']);
                    $refund_stmt->execute();
                }
                
                // Delete the withdrawal
                $delete_query = "DELETE FROM withdrawals WHERE id = ?";
                $delete_stmt = $conn->prepare($delete_query);
                $delete_stmt->bind_param("i", $withdrawal_id);
                
                if ($delete_stmt->execute()) {
                    $message = "Withdrawal deleted successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error deleting withdrawal: " . $delete_stmt->error;
                    $message_type = "error";
                }
                $delete_stmt->close();
            }
        } else {
            // Handle quick approve/reject/processing/pending
            $action_map = [
                'approve' => 'completed',
                'reject' => 'rejected',
                'processing' => 'processing',
                'pending' => 'pending'
            ];
            
            if (isset($action_map[$action])) {
                $new_status = $action_map[$action];
                
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Get withdrawal details first
                    $check_query = "SELECT amount, user_id, status FROM withdrawals WHERE id = ?";
                    $check_stmt = $conn->prepare($check_query);
                    $check_stmt->bind_param("i", $withdrawal_id);
                    $check_stmt->execute();
                    $check_result = $check_stmt->get_result();
                    
                    if ($check_result->num_rows > 0) {
                        $withdrawal_data = $check_result->fetch_assoc();
                        $old_status = $withdrawal_data['status'];
                        
                        // If changing from rejected to another status, deduct the refunded amount
                        if ($old_status == 'rejected' && $new_status != 'rejected') {
                            $deduct_query = "UPDATE users SET 
                                            account_balance = account_balance - ?,
                                            total_withdrawals = total_withdrawals + ?,
                                            updated_at = NOW()
                                            WHERE id = ?";
                            $deduct_stmt = $conn->prepare($deduct_query);
                            $deduct_stmt->bind_param("ddi", $withdrawal_data['amount'], $withdrawal_data['amount'], $withdrawal_data['user_id']);
                            $deduct_stmt->execute();
                        }
                        
                        // If changing to rejected from another status, refund the amount
                        if ($new_status == 'rejected' && $old_status != 'rejected') {
                            $refund_query = "UPDATE users SET 
                                            account_balance = account_balance + ?,
                                            total_withdrawals = total_withdrawals - ?,
                                            updated_at = NOW()
                                            WHERE id = ?";
                            $refund_stmt = $conn->prepare($refund_query);
                            $refund_stmt->bind_param("ddi", $withdrawal_data['amount'], $withdrawal_data['amount'], $withdrawal_data['user_id']);
                            $refund_stmt->execute();
                        }
                        
                        // If changing to completed from another status, deduct the amount
                        if ($new_status == 'completed' && $old_status != 'completed') {
                            // Check balance before deducting
                            $balance_check = $conn->prepare("SELECT account_balance FROM users WHERE id = ?");
                            $balance_check->bind_param("i", $withdrawal_data['user_id']);
                            $balance_check->execute();
                            $balance_result = $balance_check->get_result();
                            $user_balance = $balance_result->fetch_assoc()['account_balance'];

                            if ($user_balance < $withdrawal_data['amount']) {
                                throw new Exception("Insufficient balance. User has $" . number_format($user_balance, 2) . " but requested $" . number_format($withdrawal_data['amount'], 2));
                            }
                            
                            $deduct_query = "UPDATE users SET 
                                            account_balance = account_balance - ?,
                                            total_withdrawals = total_withdrawals + ?,
                                            last_withdrawal = NOW(),
                                            updated_at = NOW()
                                            WHERE id = ?";
                            $deduct_stmt = $conn->prepare($deduct_query);
                            $deduct_stmt->bind_param("ddi", $withdrawal_data['amount'], $withdrawal_data['amount'], $withdrawal_data['user_id']);
                            $deduct_stmt->execute();
                        }
                        
                        // If changing from completed to another status, add the amount back
                        if ($old_status == 'completed' && $new_status != 'completed') {
                            $refund_query = "UPDATE users SET 
                                            account_balance = account_balance + ?,
                                            total_withdrawals = total_withdrawals - ?,
                                            updated_at = NOW()
                                            WHERE id = ?";
                            $refund_stmt = $conn->prepare($refund_query);
                            $refund_stmt->bind_param("ddi", $withdrawal_data['amount'], $withdrawal_data['amount'], $withdrawal_data['user_id']);
                            $refund_stmt->execute();
                        }
                    }
                    
                    // Update withdrawal status
                    $update_query = "UPDATE withdrawals SET 
                                    status = ?,
                                    processed_by = ?,
                                    processed_at = NOW(),
                                    updated_at = NOW()
                                    WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("sii", $new_status, $admin_id, $withdrawal_id);
                    $update_stmt->execute();
                    
                    $conn->commit();
                    
                    $message = "Withdrawal status updated to " . $new_status . "!";
                    $message_type = "success";
                    
                } catch (Exception $e) {
                    $conn->rollback();
                    $message = "Error updating withdrawal: " . $e->getMessage();
                    $message_type = "error";
                }
            }
        }
    }
}

// Function to send withdrawal approval email
function sendWithdrawalApprovalEmail($user_email, $user_name, $amount, $net_amount, $fee_amount, $transaction_id, $withdrawal_id) {
    $site_name = "Alpha Capitals";
    $site_email = "info@alphacapitalsinc.cc";
    $admin_email = "admin@alphacapitalsinc.cc";
    
    $subject = "Withdrawal Approved - Transaction #$transaction_id";
    
    $message = "<!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>Withdrawal Approved</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #4CAF50; color: white; padding: 20px; text-align: center; }
            .content { background: #f9f9f9; padding: 30px; border-radius: 5px; }
            .footer { margin-top: 20px; text-align: center; color: #666; font-size: 12px; }
            .amount { font-size: 24px; font-weight: bold; color: #4CAF50; }
            .transaction-id { background: #e8f5e9; padding: 10px; border-radius: 3px; font-family: monospace; }
            .fee { color: #f44336; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>Withdrawal Approved</h1>
            </div>
            <div class='content'>
                <h2>Hello $user_name,</h2>
                <p>We are pleased to inform you that your withdrawal request has been approved and processed.</p>
                
                <p><strong>Transaction Details:</strong></p>
                <ul>
                    <li>Requested Amount: <span class='amount'>$" . number_format($amount, 2) . "</span></li>";
    
    if ($fee_amount > 0) {
        $message .= "<li>Processing Fee: <span class='fee'>$" . number_format($fee_amount, 2) . "</span></li>";
    }
    
    $message .= "<li>Net Amount Sent: <span class='amount'>$" . number_format($net_amount, 2) . "</span></li>
                    <li>Transaction ID: <div class='transaction-id'>$transaction_id</div></li>
                    <li>Withdrawal ID: $withdrawal_id</li>
                    <li>Status: <span style='color: #4CAF50; font-weight: bold;'>Completed</span></li>
                    <li>Processed Date: " . date('F d, Y h:i A') . "</li>
                </ul>
                
                <p>The funds have been sent to your selected payment method. Please allow some time for the transfer to complete depending on your payment method.</p>
                
                <p><strong>Payment Method:</strong> The funds were sent according to your withdrawal request details.</p>
                
                <p>If you have not received the funds within the expected timeframe, or if you have any questions, please contact our support team at <a href='mailto:$admin_email'>$admin_email</a>.</p>
                
                <p>Thank you for using our services!</p>
                <p>The $site_name Team</p>
            </div>
            <div class='footer'>
                <p>This is an automated message, please do not reply to this email.</p>
                <p>&copy; " . date('Y') . " $site_name. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: $site_name <$site_email>" . "\r\n";
    $headers .= "Reply-To: $admin_email" . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    return mail($user_email, $subject, $message, $headers);
}

// Function to send withdrawal rejection email
function sendWithdrawalRejectionEmail($user_email, $user_name, $amount, $transaction_id, $reason = '') {
    $site_name = "Alpha Capitals";
    $site_email = "info@alphacapitalsinc.cc";
    $admin_email = "admin@alphacapitalsinc.cc";
    
    $subject = "Withdrawal Rejected - Transaction #$transaction_id";
    
    $message = "<!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>Withdrawal Rejected</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #f44336; color: white; padding: 20px; text-align: center; }
            .content { background: #f9f9f9; padding: 30px; border-radius: 5px; }
            .footer { margin-top: 20px; text-align: center; color: #666; font-size: 12px; }
            .amount { font-size: 24px; font-weight: bold; color: #f44336; }
            .transaction-id { background: #ffebee; padding: 10px; border-radius: 3px; font-family: monospace; }
            .reason-box { background: #fff3e0; padding: 15px; border-left: 4px solid #ff9800; margin: 15px 0; }
            .refund-notice { background: #e8f5e9; padding: 15px; border-radius: 5px; margin: 15px 0; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>Withdrawal Rejected</h1>
            </div>
            <div class='content'>
                <h2>Hello $user_name,</h2>
                <p>We regret to inform you that your withdrawal request has been rejected.</p>
                
                <div class='refund-notice'>
                    <p><strong>Important:</strong> The amount of <span class='amount'>$" . number_format($amount, 2) . "</span> has been refunded to your account balance.</p>
                </div>
                
                <p><strong>Transaction Details:</strong></p>
                <ul>
                    <li>Amount: <span class='amount'>$" . number_format($amount, 2) . "</span></li>
                    <li>Transaction ID: <div class='transaction-id'>$transaction_id</div></li>
                    <li>Status: <span style='color: #f44336; font-weight: bold;'>Rejected</span></li>
                    <li>Date: " . date('F d, Y h:i A') . "</li>
                </ul>";
    
    if (!empty($reason)) {
        $message .= "<div class='reason-box'>
                        <p><strong>Reason for rejection:</strong></p>
                        <p>$reason</p>
                    </div>";
    }
    
    $message .= "<p>You can submit a new withdrawal request after reviewing the reason above.</p>
                
                <p>If you believe this is an error, or if you need further clarification, please contact our support team at <a href='mailto:$admin_email'>$admin_email</a>.</p>
                
                <p>Thank you for your understanding.</p>
                <p>The $site_name Team</p>
            </div>
            <div class='footer'>
                <p>This is an automated message, please do not reply to this email.</p>
                <p>&copy; " . date('Y') . " $site_name. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: $site_name <$site_email>" . "\r\n";
    $headers .= "Reply-To: $admin_email" . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    return mail($user_email, $subject, $message, $headers);
}

// Function to send withdrawal processing email
function sendWithdrawalProcessingEmail($user_email, $user_name, $amount, $transaction_id) {
    $site_name = "Alpha Capitals";
    $site_email = "info@alphacapitalsinc.cc";
    $admin_email = "admin@alphacapitalsinc.cc";
    
    $subject = "Withdrawal Processing - Transaction #$transaction_id";
    
    $message = "<!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <title>Withdrawal Processing</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #2196F3; color: white; padding: 20px; text-align: center; }
            .content { background: #f9f9f9; padding: 30px; border-radius: 5px; }
            .footer { margin-top: 20px; text-align: center; color: #666; font-size: 12px; }
            .amount { font-size: 24px; font-weight: bold; color: #2196F3; }
            .transaction-id { background: #e3f2fd; padding: 10px; border-radius: 3px; font-family: monospace; }
            .processing-notice { background: #fff3e0; padding: 15px; border-radius: 5px; margin: 15px 0; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h1>Withdrawal Processing</h1>
            </div>
            <div class='content'>
                <h2>Hello $user_name,</h2>
                <p>Your withdrawal request is now being processed.</p>
                
                <div class='processing-notice'>
                    <p><strong>Processing Information:</strong> Your withdrawal is currently being processed by our finance team. This usually takes 1-24 hours for cryptocurrency withdrawals and 1-5 business days for bank transfers.</p>
                </div>
                
                <p><strong>Transaction Details:</strong></p>
                <ul>
                    <li>Amount: <span class='amount'>$" . number_format($amount, 2) . "</span></li>
                    <li>Transaction ID: <div class='transaction-id'>$transaction_id</div></li>
                    <li>Status: <span style='color: #2196F3; font-weight: bold;'>Processing</span></li>
                    <li>Processing Started: " . date('F d, Y h:i A') . "</li>
                </ul>
                
                <p>You will receive another notification once the withdrawal has been completed.</p>
                
                <p>If you have any questions or need to update your payment details, please contact our support team at <a href='mailto:$admin_email'>$admin_email</a>.</p>
                
                <p>Thank you for your patience!</p>
                <p>The $site_name Team</p>
            </div>
            <div class='footer'>
                <p>This is an automated message, please do not reply to this email.</p>
                <p>&copy; " . date('Y') . " $site_name. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: $site_name <$site_email>" . "\r\n";
    $headers .= "Reply-To: $admin_email" . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    return mail($user_email, $subject, $message, $headers);
}

// Handle search and filters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'pending';
$payment_type_filter = isset($_GET['payment_type']) ? $_GET['payment_type'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build the query with filters
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($search)) {
    $where_conditions[] = "(w.transaction_id LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR u.full_name LIKE ? OR w.wallet_address LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term, $search_term]);
    $param_types .= 'sssss';
}

if (!empty($status_filter) && $status_filter != 'all') {
    $where_conditions[] = "w.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($payment_type_filter) && $payment_type_filter != 'all') {
    $where_conditions[] = "w.payment_type = ?";
    $params[] = $payment_type_filter;
    $param_types .= 's';
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(w.created_at) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(w.created_at) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Get total withdrawals count for pagination
$count_query = "SELECT COUNT(*) as total FROM withdrawals w 
                JOIN users u ON w.user_id = u.id 
                $where_clause";
if (!empty($params)) {
    $stmt = $conn->prepare($count_query);
    $stmt->bind_param($param_types, ...$params);
    $stmt->execute();
    $count_result = $stmt->get_result();
    $total_withdrawals = $count_result->fetch_assoc()['total'];
    $stmt->close();
} else {
    $result = $conn->query($count_query);
    $total_withdrawals = $result->fetch_assoc()['total'];
}

// Pagination
$per_page = 20;
$total_pages = ceil($total_withdrawals / $per_page);
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Get withdrawals with pagination and filters
$query = "SELECT w.*, u.username, u.email, u.full_name, u.phone,
                 p.wallet_name, p.bank_name, p.payment_type,
                 a.email as processed_by_admin_email
          FROM withdrawals w 
          JOIN users u ON w.user_id = u.id 
          LEFT JOIN payment_tb p ON w.payment_method_id = p.id 
          LEFT JOIN admin_table a ON w.processed_by = a.id 
          $where_clause 
          ORDER BY w.created_at DESC 
          LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$withdrawals_result = $stmt->get_result();
$withdrawals = [];
while ($row = $withdrawals_result->fetch_assoc()) {
    $withdrawals[] = $row;
}
$stmt->close();

// Get stats for dashboard
$stats_query = "SELECT 
    COUNT(*) as total_withdrawals,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_withdrawals,
    SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END) as processing_withdrawals,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_withdrawals,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_withdrawals,
    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_withdrawals,
    SUM(CASE WHEN status IN ('completed', 'processing') THEN amount ELSE 0 END) as total_processing_amount,
    SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount,
    SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as total_completed_amount,
    SUM(fee_amount) as total_fees_collected
    FROM withdrawals";
$stats_result = $conn->query($stats_query);
$stats = $stats_result->fetch_assoc();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Withdrawals - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        .sidebar.collapsed {
            width: 70px;
        }
        
        .sidebar.collapsed .sidebar-text {
            display: none;
        }
        
        .sidebar.collapsed .logo-text {
            display: none;
        }
        
        .main-content {
            transition: all 0.3s ease;
        }
        
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .status-pending {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.2);
        }
        
        .status-processing {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.2);
        }
        
        .status-completed {
            background: rgba(72, 187, 120, 0.1);
            color: #48bb78;
            border: 1px solid rgba(72, 187, 120, 0.2);
        }
        
        .status-rejected {
            background: rgba(245, 101, 101, 0.1);
            color: #f56565;
            border: 1px solid rgba(245, 101, 101, 0.2);
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">
    
    <?php include("nav.php"); ?>

    <!-- Main Content -->
    <div class="main-content ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">Manage Withdrawals</h2>
                    <p class="text-gray-600">Total Withdrawals: <?php echo number_format($total_withdrawals); ?></p>
                </div>
                
                <!-- Quick Stats -->
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-600">
                        <span class="font-medium">Pending: </span>
                        <span class="text-yellow-600"><?php echo number_format($stats['pending_withdrawals']); ?></span>
                    </div>
                    <div class="text-sm text-gray-600">
                        <span class="font-medium">Processing: </span>
                        <span class="text-blue-600"><?php echo number_format($stats['processing_withdrawals']); ?></span>
                    </div>
                    <div class="text-sm text-gray-600">
                        <span class="font-medium">Today: </span>
                        <span class="text-green-600"><?php echo number_format($stats['today_withdrawals']); ?></span>
                    </div>
                </div>
            </div>
        </header>

        <!-- Message Alert -->
        <?php if (!empty($message)): ?>
        <div class="mx-8 mt-6">
            <div class="p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                        <span><?php echo $message; ?></span>
                    </div>
                    <button onclick="this.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- View Withdrawal Modal -->
        <?php if ($show_view_modal && $selected_withdrawal): ?>
        <div id="viewModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-xl font-bold text-gray-800">
                            Withdrawal Details - <?php echo htmlspecialchars($selected_withdrawal['transaction_id']); ?>
                        </h3>
                        <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <!-- Withdrawal Information -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                        <!-- User Information -->
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                                <i class="fas fa-user mr-2 text-blue-500"></i> User Information
                            </h4>
                            <div class="space-y-2">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Username:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_withdrawal['username']); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Full Name:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_withdrawal['full_name'] ?: 'N/A'); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Email:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_withdrawal['email']); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Phone:</span>
                                    <span class="font-medium"><?php echo htmlspecialchars($selected_withdrawal['phone'] ?: 'N/A'); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Account Balance:</span>
                                    <span class="font-bold text-green-600">$<?php echo number_format($selected_withdrawal['account_balance'], 2); ?></span>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Withdrawal Information -->
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                                <i class="fas fa-money-bill-wave mr-2 text-green-500"></i> Withdrawal Information
                            </h4>
                            <div class="space-y-2">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Requested Amount:</span>
                                    <span class="font-bold text-lg">$<?php echo number_format($selected_withdrawal['amount'], 2); ?></span>
                                </div>
                                <?php if ($selected_withdrawal['fee_amount'] > 0): ?>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Fee:</span>
                                    <span class="text-red-600">-$<?php echo number_format($selected_withdrawal['fee_amount'], 2); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Net Amount:</span>
                                    <span class="font-bold text-green-600">$<?php echo number_format($selected_withdrawal['net_amount'], 2); ?></span>
                                </div>
                                <?php endif; ?>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Transaction ID:</span>
                                    <span class="font-mono font-medium"><?php echo htmlspecialchars($selected_withdrawal['transaction_id']); ?></span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Payment Type:</span>
                                    <span class="font-medium">
                                        <?php 
                                        if ($selected_withdrawal['payment_type'] == 'crypto') {
                                            echo 'Cryptocurrency';
                                        } else {
                                            echo 'Bank Transfer';
                                        }
                                        ?>
                                    </span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Status:</span>
                                    <span class="status-badge <?php echo 'status-' . $selected_withdrawal['status']; ?>">
                                        <?php echo ucfirst($selected_withdrawal['status']); ?>
                                    </span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Date:</span>
                                    <span><?php echo date('M d, Y h:i A', strtotime($selected_withdrawal['created_at'])); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment Details -->
                    <div class="mb-8">
                        <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                            <i class="fas fa-credit-card mr-2 text-purple-500"></i> Payment Details
                        </h4>
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <?php if ($selected_withdrawal['payment_type'] == 'crypto'): ?>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <span class="text-gray-600">Wallet Name:</span>
                                        <p class="font-medium"><?php echo htmlspecialchars($selected_withdrawal['wallet_name'] ?: 'N/A'); ?></p>
                                    </div>
                                    <div>
                                        <span class="text-gray-600">Network:</span>
                                        <p class="font-medium"><?php echo htmlspecialchars($selected_withdrawal['crypto_network'] ?: 'N/A'); ?></p>
                                    </div>
                                    <div class="md:col-span-2">
                                        <span class="text-gray-600">Wallet Address:</span>
                                        <p class="font-mono bg-gray-100 p-2 rounded mt-1"><?php echo htmlspecialchars($selected_withdrawal['wallet_address'] ?: 'N/A'); ?></p>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="md:col-span-2">
                                    <span class="text-gray-600">Bank Details:</span>
                                    <div class="bg-gray-100 p-3 rounded mt-1">
                                        <?php echo nl2br(htmlspecialchars($selected_withdrawal['bank_details'] ?: 'N/A')); ?>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- Admin Information -->
                    <?php if ($selected_withdrawal['processed_by']): ?>
                    <div class="mb-8">
                        <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                            <i class="fas fa-user-shield mr-2 text-yellow-500"></i> Processing Information
                        </h4>
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <span class="text-gray-600">Processed By:</span>
                                    <p class="font-medium"><?php echo htmlspecialchars($selected_withdrawal['processed_by_admin_email'] ?: 'Admin'); ?></p>
                                </div>
                                <div>
                                    <span class="text-gray-600">Processed At:</span>
                                    <p><?php echo date('M d, Y h:i A', strtotime($selected_withdrawal['processed_at'])); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Admin Notes -->
                    <?php if ($selected_withdrawal['admin_notes']): ?>
                    <div class="mb-8">
                        <h4 class="font-bold text-gray-700 mb-3 flex items-center">
                            <i class="fas fa-sticky-note mr-2 text-red-500"></i> Admin Notes
                        </h4>
                        <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                            <?php echo nl2br(htmlspecialchars($selected_withdrawal['admin_notes'])); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Action Buttons -->
                    <div class="border-t border-gray-200 pt-6">
                        <div class="flex flex-wrap gap-3 justify-end">
                            <?php if ($selected_withdrawal['status'] == 'pending'): ?>
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Mark this withdrawal as processing?')">
                                    <input type="hidden" name="action" value="processing">
                                    <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                                        <i class="fas fa-cog mr-2"></i> Mark as Processing
                                    </button>
                                </form>
                                
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Are you sure you want to approve this withdrawal? The amount will be deducted from user\'s account balance.')">
                                    <input type="hidden" name="action" value="approve">
                                    <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                                        <i class="fas fa-check mr-2"></i> Approve Withdrawal
                                    </button>
                                </form>
                                
                                <button onclick="showRejectForm()" class="flex items-center px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                                    <i class="fas fa-times mr-2"></i> Reject Withdrawal
                                </button>
                                
                            <?php elseif ($selected_withdrawal['status'] == 'processing'): ?>
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Approve this withdrawal? The amount will be deducted from user\'s account balance.')">
                                    <input type="hidden" name="action" value="approve">
                                    <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                                        <i class="fas fa-check mr-2"></i> Approve
                                    </button>
                                </form>
                                
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Reset this withdrawal to pending?')">
                                    <input type="hidden" name="action" value="pending">
                                    <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 transition">
                                        <i class="fas fa-undo mr-2"></i> Back to Pending
                                    </button>
                                </form>
                                
                            <?php elseif ($selected_withdrawal['status'] == 'completed'): ?>
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Reset this withdrawal to pending? The deducted amount will be refunded to user\'s account.')">
                                    <input type="hidden" name="action" value="pending">
                                    <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 transition">
                                        <i class="fas fa-undo mr-2"></i> Reset to Pending
                                    </button>
                                </form>
                                
                            <?php elseif ($selected_withdrawal['status'] == 'rejected'): ?>
                                <form method="POST" action="" class="inline" onsubmit="return confirm('Reset this withdrawal to pending? The refunded amount will be deducted from user\'s account.')">
                                    <input type="hidden" name="action" value="pending">
                                    <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                    <button type="submit" class="flex items-center px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 transition">
                                        <i class="fas fa-undo mr-2"></i> Back to Pending
                                    </button>
                                </form>
                            <?php endif; ?>
                            
                            <!-- Admin Notes Form -->
                            <form method="POST" action="" class="inline" onsubmit="return confirm('Update admin notes?')">
                                <input type="hidden" name="action" value="update_notes">
                                <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                <div class="flex items-center space-x-2">
                                    <input type="text" name="admin_notes" 
                                           placeholder="Add admin notes..." 
                                           value="<?php echo htmlspecialchars($selected_withdrawal['admin_notes'] ?? ''); ?>"
                                           class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                                        <i class="fas fa-save"></i>
                                    </button>
                                </div>
                            </form>
                            
                            <a href="?delete=<?php echo $selected_withdrawal['id']; ?>" 
                               onclick="return confirm('Are you sure you want to delete this withdrawal? This action cannot be undone.')"
                               class="flex items-center px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition">
                                <i class="fas fa-trash mr-2"></i> Delete
                            </a>
                            
                            <button onclick="closeModal()" class="flex items-center px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                                <i class="fas fa-times mr-2"></i> Close
                            </button>
                        </div>
                        
                        <!-- Reject Form (Initially Hidden) -->
                        <div id="rejectForm" class="hidden mt-4 p-4 bg-red-50 border border-red-200 rounded-lg">
                            <form method="POST" action="" onsubmit="return confirm('Are you sure you want to reject this withdrawal? The amount will be refunded to user\'s account.')">
                                <input type="hidden" name="action" value="reject">
                                <input type="hidden" name="withdrawal_id" value="<?php echo $selected_withdrawal['id']; ?>">
                                
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    Reason for Rejection
                                </label>
                                <textarea name="admin_notes" rows="3" 
                                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                          placeholder="Provide reason for rejection (optional)"></textarea>
                                
                                <div class="mt-3 flex justify-end space-x-3">
                                    <button type="button" onclick="hideRejectForm()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">
                                        Cancel
                                    </button>
                                    <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                                        Confirm Reject
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Filters and Search -->
        <div class="bg-white mx-8 mt-6 rounded-lg shadow-sm border border-gray-200 p-6">
            <form method="GET" action="" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <!-- Search -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Search</label>
                        <div class="relative">
                            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                                   placeholder="Search by TX ID, username, email, wallet..." 
                                   class="w-full px-4 py-2 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                        </div>
                    </div>
                    
                    <!-- Status Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>All Status</option>
                            <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="processing" <?php echo $status_filter == 'processing' ? 'selected' : ''; ?>>Processing</option>
                            <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="rejected" <?php echo $status_filter == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        </select>
                    </div>
                    
                    <!-- Payment Type Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Payment Type</label>
                        <select name="payment_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $payment_type_filter == 'all' ? 'selected' : ''; ?>>All Types</option>
                            <option value="crypto" <?php echo $payment_type_filter == 'crypto' ? 'selected' : ''; ?>>Cryptocurrency</option>
                            <option value="bank" <?php echo $payment_type_filter == 'bank' ? 'selected' : ''; ?>>Bank Transfer</option>
                        </select>
                    </div>
                    
                    <!-- Date Range -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Date Range</label>
                        <div class="grid grid-cols-2 gap-2">
                            <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>"
                                   class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm">
                            <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>"
                                   class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent text-sm">
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-between items-center">
                    <div>
                        <button type="submit" class="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition">
                            <i class="fas fa-filter mr-2"></i>Apply Filters
                        </button>
                        <a href="manage-withdrawals.php" class="ml-2 px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition">
                            <i class="fas fa-times mr-2"></i>Clear
                        </a>
                    </div>
                    
                    <!-- Results Count -->
                    <div class="text-sm text-gray-600">
                        Showing <?php echo min($per_page, count($withdrawals)); ?> of <?php echo number_format($total_withdrawals); ?> withdrawals
                    </div>
                </div>
            </form>
        </div>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mx-8 mt-6">
            <!-- Total Withdrawals -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Withdrawals</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['total_withdrawals']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-money-bill-wave text-blue-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <i class="fas fa-calendar-day mr-1"></i>
                    <?php echo $stats['today_withdrawals']; ?> today
                </div>
            </div>

            <!-- Pending Withdrawals -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Pending Withdrawals</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['pending_withdrawals']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-clock text-yellow-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <span class="text-yellow-600 font-medium">$<?php echo number_format($stats['pending_amount'], 2); ?></span> pending
                </div>
            </div>

            <!-- Processing Withdrawals -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Processing</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['processing_withdrawals']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-cog text-blue-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <span class="text-blue-600 font-medium">$<?php echo number_format($stats['total_processing_amount'], 2); ?></span> processing
                </div>
            </div>

            <!-- Completed Withdrawals -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Completed</p>
                        <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['completed_withdrawals']); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-check-circle text-green-600 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-sm text-gray-500">
                    <span class="text-green-600 font-medium">$<?php echo number_format($stats['total_completed_amount'], 2); ?></span> completed
                </div>
            </div>
        </div>

        <!-- Withdrawals Table -->
        <div class="bg-white mx-8 my-6 rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr class="text-left text-sm text-gray-500 border-b border-gray-200">
                            <th class="py-3 px-6 font-medium">Transaction</th>
                            <th class="py-3 px-6 font-medium">User</th>
                            <th class="py-3 px-6 font-medium">Amount</th>
                            <th class="py-3 px-6 font-medium">Payment Method</th>
                            <th class="py-3 px-6 font-medium">Status</th>
                            <th class="py-3 px-6 font-medium">Date</th>
                            <th class="py-3 px-6 font-medium">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php if (empty($withdrawals)): ?>
                        <tr>
                            <td colspan="7" class="py-8 text-center text-gray-500">
                                <i class="fas fa-money-bill-wave text-3xl mb-2 block"></i>
                                No withdrawals found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($withdrawals as $withdrawal): ?>
                        <tr class="hover:bg-gray-50 transition">
                            <!-- Transaction Info -->
                            <td class="py-4 px-6">
                                <p class="font-medium text-gray-800">
                                    <?php echo htmlspecialchars($withdrawal['transaction_id']); ?>
                                </p>
                                <?php if ($withdrawal['fee_amount'] > 0): ?>
                                <p class="text-xs text-gray-500">
                                    Net: $<?php echo number_format($withdrawal['net_amount'], 2); ?>
                                    <span class="text-red-500">(Fee: $<?php echo number_format($withdrawal['fee_amount'], 2); ?>)</span>
                                </p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- User Info -->
                            <td class="py-4 px-6">
                                <p class="font-medium text-gray-800">
                                    <?php echo htmlspecialchars($withdrawal['username']); ?>
                                </p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($withdrawal['email']); ?></p>
                                <?php if ($withdrawal['full_name']): ?>
                                <p class="text-xs text-gray-400"><?php echo htmlspecialchars($withdrawal['full_name']); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Amount -->
                            <td class="py-4 px-6">
                                <p class="text-lg font-bold text-gray-800">$<?php echo number_format($withdrawal['amount'], 2); ?></p>
                                <?php if ($withdrawal['fee_amount'] > 0): ?>
                                <p class="text-sm text-green-600">Net: $<?php echo number_format($withdrawal['net_amount'], 2); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Payment Method -->
                            <td class="py-4 px-6">
                                <div class="flex items-center">
                                    <?php if ($withdrawal['payment_type'] == 'crypto'): ?>
                                    <i class="fab fa-bitcoin text-yellow-500 mr-2"></i>
                                    <div>
                                        <p class="text-sm font-medium"><?php echo htmlspecialchars($withdrawal['wallet_name'] ?: 'Crypto'); ?></p>
                                        <p class="text-xs text-gray-500">Cryptocurrency</p>
                                    </div>
                                    <?php else: ?>
                                    <i class="fas fa-university text-blue-500 mr-2"></i>
                                    <div>
                                        <p class="text-sm font-medium"><?php echo htmlspecialchars($withdrawal['bank_name'] ?: 'Bank'); ?></p>
                                        <p class="text-xs text-gray-500">Bank Transfer</p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            
                            <!-- Status -->
                            <td class="py-4 px-6">
                                <span class="status-badge <?php echo 'status-' . $withdrawal['status']; ?>">
                                    <?php echo ucfirst($withdrawal['status']); ?>
                                </span>
                                <?php if ($withdrawal['admin_notes']): ?>
                                <div class="text-xs text-gray-500 mt-1 truncate max-w-xs" title="<?php echo htmlspecialchars($withdrawal['admin_notes']); ?>">
                                    <?php echo substr(htmlspecialchars($withdrawal['admin_notes']), 0, 30); ?>...
                                </div>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Date -->
                            <td class="py-4 px-6">
                                <p class="text-sm text-gray-600">
                                    <?php echo date('M d, Y', strtotime($withdrawal['created_at'])); ?>
                                </p>
                                <p class="text-xs text-gray-400">
                                    <?php echo date('h:i A', strtotime($withdrawal['created_at'])); ?>
                                </p>
                            </td>
                            
                            <!-- Actions -->
                            <td class="py-4 px-6">
                                <div class="flex flex-wrap gap-2">
                                    <!-- View Details -->
                                    <a href="?view=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['view' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition text-sm"
                                       title="View Details">
                                        <i class="fas fa-eye mr-1 text-xs"></i> View
                                    </a>
                                    
                                    <!-- Quick Actions -->
                                    <?php if ($withdrawal['status'] == 'pending'): ?>
                                    <a href="?processing=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['processing' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition text-sm"
                                       title="Mark as Processing"
                                       onclick="return confirm('Mark this withdrawal as processing?')">
                                        <i class="fas fa-cog mr-1 text-xs"></i> Processing
                                    </a>
                                    
                                    <a href="?approve=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['approve' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition text-sm"
                                       title="Approve"
                                       onclick="return confirm('Approve this withdrawal? Amount will be deducted from user\'s account.')">
                                        <i class="fas fa-check mr-1 text-xs"></i> Approve
                                    </a>
                                    
                                    <a href="?reject=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['reject' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition text-sm"
                                       title="Reject"
                                       onclick="return confirm('Reject this withdrawal? Amount will be refunded.')">
                                        <i class="fas fa-times mr-1 text-xs"></i> Reject
                                    </a>
                                    
                                    <?php elseif ($withdrawal['status'] == 'processing'): ?>
                                    <a href="?approve=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['approve' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition text-sm"
                                       title="Approve"
                                       onclick="return confirm('Approve this withdrawal? Amount will be deducted from user\'s account.')">
                                        <i class="fas fa-check mr-1 text-xs"></i> Approve
                                    </a>
                                    
                                    <a href="?pending=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['pending' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-yellow-100 text-yellow-700 rounded-lg hover:bg-yellow-200 transition text-sm"
                                       title="Back to Pending"
                                       onclick="return confirm('Reset to pending?')">
                                        <i class="fas fa-undo mr-1 text-xs"></i> Reset
                                    </a>
                                    
                                    <?php elseif (in_array($withdrawal['status'], ['completed', 'rejected'])): ?>
                                    <a href="?pending=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['pending' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-yellow-100 text-yellow-700 rounded-lg hover:bg-yellow-200 transition text-sm"
                                       title="Back to Pending"
                                       onclick="return confirm('Reset to pending?')">
                                        <i class="fas fa-undo mr-1 text-xs"></i> Reset
                                    </a>
                                    <?php endif; ?>
                                    
                                    <!-- Delete -->
                                    <a href="?delete=<?php echo $withdrawal['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['delete' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-3 py-1 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition text-sm"
                                       title="Delete"
                                       onclick="return confirm('Delete this withdrawal?')">
                                        <i class="fas fa-trash mr-1 text-xs"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="px-6 py-4 border-t border-gray-200">
                <div class="flex items-center justify-between">
                    <div class="text-sm text-gray-600">
                        Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
                    </div>
                    <div class="flex space-x-2">
                        <?php if ($current_page > 1): ?>
                        <a href="?page=<?php echo $current_page - 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                            <i class="fas fa-chevron-left mr-1"></i> Previous
                        </a>
                        <?php endif; ?>
                        
                        <?php 
                        $start_page = max(1, $current_page - 2);
                        $end_page = min($total_pages, $current_page + 2);
                        
                        for ($page = $start_page; $page <= $end_page; $page++): 
                        ?>
                        <a href="?page=<?php echo $page; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border rounded-lg transition <?php echo $page == $current_page ? 'bg-primary-600 text-white border-primary-600' : 'border-gray-300 text-gray-700 hover:bg-gray-50'; ?>">
                            <?php echo $page; ?>
                        </a>
                        <?php endfor; ?>
                        
                        <?php if ($current_page < $total_pages): ?>
                        <a href="?page=<?php echo $current_page + 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
                            Next <i class="fas fa-chevron-right ml-1"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // Modal functions
        function closeModal() {
            const modal = document.getElementById('viewModal');
            if (modal) {
                modal.remove();
                // Remove from URL
                const url = new URL(window.location);
                url.searchParams.delete('view');
                window.history.replaceState({}, '', url);
            }
        }

        function showRejectForm() {
            document.getElementById('rejectForm').classList.remove('hidden');
        }

        function hideRejectForm() {
            document.getElementById('rejectForm').classList.add('hidden');
        }

        // Close modal on escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeModal();
            }
        });

        // Close modal when clicking outside
        document.addEventListener('click', function(event) {
            const modal = document.getElementById('viewModal');
            if (modal && event.target === modal) {
                closeModal();
            }
        });

        // Auto-focus search input on page load
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.querySelector('input[name="search"]');
            if (searchInput) {
                searchInput.focus();
            }
            
            // Show modal if view parameter exists
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('view')) {
                const modal = document.getElementById('viewModal');
                if (modal) {
                    modal.scrollIntoView({ behavior: 'smooth' });
                }
            }
        });
    </script>
</body>
</html>