<?php
ignore_user_abort(true);
set_time_limit(0);
// process_withdrawal.php - Handles withdrawal requests and processing
require_once 'element/connection.php';
session_start();

// Function to get user's level by traversing the tree
function getUserLevelByTraversal($conn, $user_id) {
    // First, get the user's sponsor
    $user_query = mysqli_query($conn, "SELECT sponsor_id FROM users WHERE user_id = '$user_id'");
    if (!$user_query || mysqli_num_rows($user_query) == 0) {
        return 0;
    }
    $user = mysqli_fetch_assoc($user_query);
    $sponsor_id = $user['sponsor_id'];
    
    if ($sponsor_id == 0) {
        return 0; // Root user has no level
    }
    
    // Now traverse up the tree to find the user's level
    $level = 0;
    $current_id = $sponsor_id;
    $visited = []; // Prevent infinite loops
    
    while ($current_id != 0 && !in_array($current_id, $visited)) {
        $visited[] = $current_id;
        $level++;
        
        // Get next sponsor
        $sponsor_query = mysqli_query($conn, "SELECT sponsor_id FROM users WHERE user_id = '$current_id'");
        if (!$sponsor_query || mysqli_num_rows($sponsor_query) == 0) {
            break;
        }
        $sponsor = mysqli_fetch_assoc($sponsor_query);
        $current_id = $sponsor['sponsor_id'];
    }
    
    return $level;
}

// Function to check if user meets level requirements
function checkLevelRequirements($conn, $user_id, $required_level) {
    // Get user's current level by traversal
    $user_level = getUserLevelByTraversal($conn, $user_id);
    
    if ($user_level >= $required_level) {
        return ['eligible' => true, 'level' => $user_level];
    } else {
        return ['eligible' => false, 'level' => $user_level, 'required' => $required_level];
    }
}

// Handle withdrawal request submission
if (isset($_REQUEST['withdrawl_request'])) {
    $amt = floatval($_REQUEST['amount']);
    $user_id = mysqli_real_escape_string($conn, $_REQUEST['user_id']);
    
    // Validate amount
    if ($amt <= 0) {
        $_SESSION['withdraw_error'] = "Invalid amount!";
        header("Location: withdraw.php");
        exit();
    }
    
    // Get user's level by traversing the tree
    $user_level = getUserLevelByTraversal($conn, $user_id);
    
    // Define level requirements (customize these based on your business rules)
    $level_requirements = [
        1 => ['min_withdrawal' => 100, 'max_withdrawal' => 1000],
        2 => ['min_withdrawal' => 500, 'max_withdrawal' => 5000],
        3 => ['min_withdrawal' => 1000, 'max_withdrawal' => 10000],
        4 => ['min_withdrawal' => 5000, 'max_withdrawal' => 50000],
        5 => ['min_withdrawal' => 10000, 'max_withdrawal' => 100000],
        6 => ['min_withdrawal' => 50000, 'max_withdrawal' => 500000],
        7 => ['min_withdrawal' => 100000, 'max_withdrawal' => 1000000]
    ];
    
    // Check if user meets level requirements for this amount
    $required_level = 1;
    foreach ($level_requirements as $level => $limits) {
        if ($amt >= $limits['min_withdrawal'] && $amt <= $limits['max_withdrawal']) {
            $required_level = $level;
            break;
        }
    }
    
    $level_check = checkLevelRequirements($conn, $user_id, $required_level);
    
    if (!$level_check['eligible']) {
        $_SESSION['withdraw_error'] = "You need to be at least Level $required_level to withdraw ₹$amt. Your current level: Level " . $level_check['level'];
        header("Location: withdraw.php");
        exit();
    }
    
    $date = date("Y-m-d H:i:s");
    
    // Start transaction
    mysqli_begin_transaction($conn);
    
    try {
        // Insert into witdrawl table with user_level
        $insert_query = "INSERT INTO `witdrawl`(`user_id`, `amt`, `request_date`, `user_level`, `status`) 
                         VALUES ('$user_id', '$amt', '$date', '$user_level', '0')";
        
        if (!mysqli_query($conn, $insert_query)) {
            throw new Exception("Failed to insert withdrawal request: " . mysqli_error($conn));
        }
        
        $withdrawal_id = mysqli_insert_id($conn);
        
        // Optional: Log to income_history
        mysqli_query($conn, "INSERT INTO `income_history`(`user_id`, `amount`, `description`, `credit_debit`, `admin_charges`, `tds`, `processed_at`) 
                             VALUES ('$user_id', '$amt', 'Withdrawal Request Submitted', '0', '0', '0', '$date')");
        
        mysqli_commit($conn);
        
        $_SESSION['withdraw_success'] = "Withdrawal request of ₹$amt submitted successfully! (Your Level: $user_level)";
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['withdraw_error'] = "Error submitting withdrawal: " . $e->getMessage();
    }
    
    header("Location: withdraw.php");
    exit();
}

// Handle EPIN purchase (keep your existing code)
if (isset($_REQUEST['send_epin'])) {
    $amt = floatval($_REQUEST['amount']);
    $user_id = mysqli_real_escape_string($conn, $_REQUEST['user_id']);
    
    $data = mysqli_fetch_array(mysqli_query($conn, "SELECT `wallet` FROM `users` WHERE `user_id`='$user_id'"));
    
    if ($amt <= $data['wallet']) {
        $date = date("Y-m-d H:i:s");
        
        mysqli_begin_transaction($conn);
        
        try {
            // Deduct from wallet
            mysqli_query($conn, "UPDATE `users` SET `wallet`=`wallet`-$amt WHERE `user_id`='$user_id'");
            
            // Log to income_history
            mysqli_query($conn, "INSERT INTO `income_history`(`user_id`, `amount`, `description`, `credit_debit`, `admin_charges`, `tds`, `processed_at`) 
                                 VALUES ('$user_id', '$amt', 'EPIN Purchase', '1', '0', '0', '$date')");
            
            // Get user's current level
            $user_level = getUserLevelByTraversal($conn, $user_id);
            
            // Insert into witdrawl table
            mysqli_query($conn, "INSERT INTO `witdrawl`(`user_id`, `amt`, `request_date`, `user_level`, `status`) 
                                 VALUES ('$user_id', '$amt', '$date', '$user_level', '1')");
            
            mysqli_commit($conn);
            
            $_SESSION['epin_success'] = "EPIN purchased successfully!";
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $_SESSION['epin_error'] = "Error purchasing EPIN: " . $e->getMessage();
        }
    } else {
        $_SESSION['epin_error'] = "Insufficient balance!";
    }
    
    header("Location: withdraw.php");
    exit();
}

// Handle withdrawal processing (for admin/cron job)
if (isset($_REQUEST['process_withdrawals']) && $_REQUEST['process_withdrawals'] == 'admin') {
    // This part is for admin to process pending withdrawals
    // You can also run this as a cron job
    
    $batch_size = isset($_REQUEST['batch_size']) ? intval($_REQUEST['batch_size']) : 10;
    
    // Get pending withdrawals
    $pending_query = mysqli_query($conn, "SELECT * FROM `witdrawl` WHERE `status` = '0' ORDER BY `id` ASC LIMIT $batch_size");
    
    $processed = 0;
    $failed = 0;
    
    while ($withdrawal = mysqli_fetch_assoc($pending_query)) {
        $withdrawal_id = $withdrawal['id'];
        $user_id = $withdrawal['user_id'];
        $amount = $withdrawal['amt'];
        $request_level = $withdrawal['user_level'];
        
        // Start transaction for each withdrawal
        mysqli_begin_transaction($conn);
        
        try {
            // Verify user still meets level requirements
            $current_level = getUserLevelByTraversal($conn, $user_id);
            
            if ($current_level < $request_level) {
                // User's level decreased, reject the withdrawal
                mysqli_query($conn, "UPDATE `witdrawl` SET `status` = '2', `error_message` = 'User level decreased from $request_level to $current_level', `processed_at` = NOW() WHERE `id` = '$withdrawal_id'");
                $failed++;
            } else {
                // Process withdrawal (transfer money, etc.)
                // Add your payment processing logic here
                
                // Update status to processed
                mysqli_query($conn, "UPDATE `witdrawl` SET `status` = '1', `processed_at` = NOW(), `processed_by` = 'system' WHERE `id` = '$withdrawal_id'");
                
                // Log to income_history
                mysqli_query($conn, "INSERT INTO `income_history`(`user_id`, `amount`, `description`, `credit_debit`, `admin_charges`, `tds`, `processed_at`) 
                                     VALUES ('$user_id', '$amount', 'Withdrawal Processed', '1', '0', '0', NOW())");
                
                $processed++;
            }
            
            mysqli_commit($conn);
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            
            // Update attempt count and error
            $attempts = $withdrawal['attempts'] + 1;
            mysqli_query($conn, "UPDATE `witdrawl` SET `attempts` = '$attempts', `last_attempt` = NOW(), `error_message` = '" . mysqli_real_escape_string($conn, $e->getMessage()) . "' WHERE `id` = '$withdrawal_id'");
            
            $failed++;
        }
    }
    
    // Return JSON response if called via AJAX
    if (isset($_REQUEST['ajax'])) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'processed' => $processed,
            'failed' => $failed,
            'message' => "Processed $processed withdrawals, $failed failed"
        ]);
        exit();
    } else {
        $_SESSION['process_result'] = "Processed $processed withdrawals, $failed failed";
        header("Location: admin/withdrawals.php");
        exit();
    }
}

// Cron job handler (runs automatically even if browser closed)
if (isset($_REQUEST['cron']) && $_REQUEST['cron'] == 'process_withdrawals') {
    // This can be called from a cron job
    // It will run in the background and not depend on browser
    
    // Set time limit to unlimited
    set_time_limit(0);
    
    // Log the start
    error_log("[" . date('Y-m-d H:i:s') . "] Cron: Starting withdrawal processing");
    
    $batch_size = 20;
    $max_iterations = 10; // Process up to 200 withdrawals (20 * 10)
    $iteration = 0;
    $total_processed = 0;
    $total_failed = 0;
    
    while ($iteration < $max_iterations) {
        // Get pending withdrawals
        $pending_query = mysqli_query($conn, "SELECT * FROM `witdrawl` WHERE `status` = '0' ORDER BY `id` ASC LIMIT $batch_size");
        
        if (mysqli_num_rows($pending_query) == 0) {
            break; // No more pending withdrawals
        }
        
        $batch_processed = 0;
        $batch_failed = 0;
        
        while ($withdrawal = mysqli_fetch_assoc($pending_query)) {
            $withdrawal_id = $withdrawal['id'];
            $user_id = $withdrawal['user_id'];
            $amount = $withdrawal['amt'];
            $request_level = $withdrawal['user_level'];
            
            mysqli_begin_transaction($conn);
            
            try {
                // Verify user still meets level requirements by traversing
                $current_level = getUserLevelByTraversal($conn, $user_id);
                
                if ($current_level < $request_level) {
                    mysqli_query($conn, "UPDATE `witdrawl` SET `status` = '2', `error_message` = 'User level decreased from $request_level to $current_level', `processed_at` = NOW() WHERE `id` = '$withdrawal_id'");
                    $batch_failed++;
                } else {
                    // Process withdrawal
                    // Add your actual payment processing here
                    
                    mysqli_query($conn, "UPDATE `witdrawl` SET `status` = '1', `processed_at` = NOW(), `processed_by` = 'cron' WHERE `id` = '$withdrawal_id'");
                    
                    $batch_processed++;
                }
                
                mysqli_commit($conn);
                
            } catch (Exception $e) {
                mysqli_rollback($conn);
                
                $attempts = $withdrawal['attempts'] + 1;
                mysqli_query($conn, "UPDATE `witdrawl` SET `attempts` = '$attempts', `last_attempt` = NOW(), `error_message` = '" . mysqli_real_escape_string($conn, $e->getMessage()) . "' WHERE `id` = '$withdrawal_id'");
                
                $batch_failed++;
            }
        }
        
        $total_processed += $batch_processed;
        $total_failed += $batch_failed;
        $iteration++;
        
        // Small pause to prevent database overload
        usleep(500000); // 0.5 seconds
    }
    
    // Log completion
    error_log("[" . date('Y-m-d H:i:s') . "] Cron: Completed processing. Processed: $total_processed, Failed: $total_failed");
    
    // If called directly, return response
    if (isset($_REQUEST['direct'])) {
        echo "Cron job completed. Processed: $total_processed, Failed: $total_failed";
    }
    exit();
}
?>