<?php
ob_start();
session_start();
$db_host = "localhost";
$db_user = 'root';
$db_pass = '';
$db_name = 'mlmll';
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

// Set error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

if (isset($_REQUEST['profile_update_password'])) {
    $my_id = $_REQUEST['my_user_id'];
    $password = $_REQUEST['password'];
    $c_password = $_REQUEST['confirm_password'];
    if ($password == $c_password) {
        // Hash the password for security
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        mysqli_query($conn, "UPDATE `users` SET `password`='$hashed_password' WHERE `user_id`='$my_id'");
    }
    header("location:../profile.php");
    exit();
}

if (isset($_REQUEST['profile_update_basic'])) {
    $my_id = $_REQUEST['my_user_id'];
    $dob = $_REQUEST['dob'];
    $gender = $_REQUEST['gender'];
    $address = $_REQUEST['address'];
    $pan_no = $_REQUEST['pan_no'];
    $aadhar_no = $_REQUEST['aadhar_no'];
    $mob = $_REQUEST['mob'];
    mysqli_query($conn, "UPDATE `users` SET `mobile`='$mob',`dob`='$dob',`gender`='$gender',`address`='$address',`panno`='$pan_no',`aadharno`='$aadhar_no' WHERE `user_id`='$my_id'");
    header("Location:../profile.php");
    exit();
}

// FIXED WITHDRAWAL REQUEST HANDLER - Level 1 determined by c1_achieved_at
if (isset($_REQUEST['withdrawl_request'])) {
    $amt = $_REQUEST['amount'];
    $user_id = $_REQUEST['user_id'];
    
    // Check if user has achieved Level 1 (c1_achieved_at not null)
    $user_check = mysqli_query($conn, "SELECT c1_achieved_at FROM users WHERE user_id = '$user_id'");
    $user_data = mysqli_fetch_assoc($user_check);
    
    if (empty($user_data['c1_achieved_at'])) {
        $_SESSION['withdraw_error'] = "You need to achieve Level 1 (have 4 direct referrals) before you can withdraw.";
        header("Location: ../withdraw.php");
        exit();
    }
    
    // Get user's current level from level_rewards table (for record keeping)
    $level_query = mysqli_query($conn, "SELECT MAX(level) as current_level FROM `level_rewards` WHERE `user_id`='$user_id' AND `paid`=1");
    $level_result = mysqli_fetch_assoc($level_query);
    $current_level = $level_result['current_level'] ?? 0; // Default to 0 if no level
    
    // Just get wallet for informational purposes, but we don't deduct
    $data = mysqli_fetch_array(mysqli_query($conn, "SELECT `wallet` FROM `users` WHERE `user_id`='$user_id'"));
    
    $date = date("Y-m-d H:i:s");
    
    // Start transaction
    mysqli_begin_transaction($conn);
    
    try {
        // Get next ID for witdrawl table
        $result = mysqli_query($conn, "SELECT MAX(id) as max_id FROM `witdrawl`");
        $row = mysqli_fetch_assoc($result);
        $new_id = ($row['max_id'] + 1);
        
        // Insert into witdrawl table with current_level
        mysqli_query($conn, "INSERT INTO `witdrawl`(`id`, `user_id`, `amt`, `request_date`, `user_level`, `status`) 
                             VALUES ('$new_id', '$user_id', '$amt', '$date', '$current_level', '0')");
        
        mysqli_commit($conn);
        
        // Set success message in session
        $_SESSION['withdraw_success'] = "Withdrawal request of ₹$amt submitted successfully! (Level $current_level)";
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['withdraw_error'] = "Error processing withdrawal: " . $e->getMessage();
    }
    
    header("Location: ../withdraw.php");
    exit();
}

if (isset($_REQUEST['login'])) {
    $user_id = $_REQUEST['user_id'];
    $password = $_REQUEST['password'];
    move_to_dashboard($user_id, $password);
    exit();
}

function is_spill_income_eligible($agent_id, $sponsor) {
    global $conn;
    $agent_data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$agent_id'"));
    if ($agent_data['placement_id'] != $sponsor) {
        return true;
    }
    return false;
}

if (isset($_REQUEST['user_registration'])) {
    $s_id = $_REQUEST['sponsor_id'];
    $pin = $_REQUEST['pin'];
    $name = $_REQUEST['user_name'];
    $pos = $_REQUEST['position'];
    $mobile = $_REQUEST['user_mob'];
    $password = $_REQUEST['password'];
    if (check_pin($pin)) {
        insert_into_users($s_id, $name, $pos, $mobile, $password);
    }
    header("Location:../registration.php");
    exit();
}

function binary_count($spons, $pos) {
    global $conn;
    if ($pos == 0) {
        $pos = "left_count";
    } else {
        $pos = "right_count";
    }
    $temp_pos = $pos . '_temp';
    $spons = find_placement_id($spons);
    while ($spons != 0) {
        mysqli_query($conn, "UPDATE `users` SET `$pos`=`$pos`+1,`$temp_pos`=`$temp_pos`+1 WHERE `user_id`='$spons'");
        is_pair_generate($spons, $pos);
        $pos = find_position($spons);
        $temp_pos = $pos . '_temp';
        $spons = find_placement_id($spons);
    }
}

function is_pair_generate($spons, $pos) {
    global $conn;
    $compare_pos = ($pos == "left_count") ? "right_count" : "left_count";
    $pos = $pos . '_temp';
    $compare_pos = $compare_pos . '_temp';
    $pla_data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$spons'"));
    if (($pla_data[$pos] >= 1 && $pla_data[$compare_pos] >= 2) || ($pla_data[$pos] >= 2 && $pla_data[$compare_pos] >= 1)) {
        $left_c = 2;
        $right_c = 1;
        if (($pla_data[$pos] >= 1 && $pla_data[$compare_pos] >= 2)) {
            $left_c = 1;
            $right_c = 2;
        }
        $m = mysqli_query($conn, "UPDATE `users` SET `$pos`=`$pos`-$left_c,`$compare_pos`=`$compare_pos`-$right_c WHERE `user_id`='$spons'");
        if ($m) {
            $date = date("Y-m-d");
            $data = mysqli_query($conn, "SELECT * FROM `pair_count` WHERE `date`='$date' AND `user_id`='$spons'");
            if (mysqli_num_rows($data) == 1) {
                mysqli_query($conn, "UPDATE `pair_count` SET `no_of_pair`=`no_of_pair`+1 WHERE `date`='$date' AND `user_id`='$spons'");
            } else {
                mysqli_query($conn, "INSERT INTO `pair_count`(`user_id`, `date`, `no_of_pair`) VALUES ('$spons','$date','1')");
            }
            $j = mysqli_query($conn, "UPDATE `users` SET `total_pairs`=`total_pairs`+1,`unpaid_pairs`=`unpaid_pairs`+1 WHERE `user_id`='$spons'");
            if ($j) {
                $user_data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$spons'"));
                $unpaid_pairs = $user_data['unpaid_pairs'];
                $total_Amt = 0;
                if ($unpaid_pairs > 0) {
                    if ($user_data['paid_pairs'] >= 5) {
                        if ($unpaid_pairs >= 5) {
                            $total_Amt = $unpaid_pairs * 300;
                        }
                    } else {
                        $total_Amt = $unpaid_pairs * 300;
                    }
                    if ($total_Amt > 0 && $unpaid_pairs > 0) {
                        $jl = mysqli_query($conn, "UPDATE `users` SET `unpaid_pairs`=`unpaid_pairs`-$unpaid_pairs,`paid_pairs`=`paid_pairs`+$unpaid_pairs WHERE `user_id`='$spons'");
                        if ($jl) {
                            $wallet_update = mysqli_query($conn, "UPDATE `users` SET `wallet`=`wallet`+$total_Amt WHERE `user_id`='$spons'");
                            if ($wallet_update) {
                                mysqli_query($conn, "INSERT INTO `income_history`(`user_id`, `amount`, `description`, `credit_debit`, `admin_charges`, `tds`, `processed_at`) 
                                                     VALUES ('$spons', '$total_Amt', 'Pair Matching Income', '0', '0', '0', NOW())");
                            }
                        }
                    }
                }
                check_for_reward($spons);
            }
        }
    }
}

function check_for_reward($agent_id) {
    global $conn;
    $t = mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$agent_id'");
    if (mysqli_num_rows($t) == 1) {
        $data = mysqli_fetch_array($t);
        $total_pair = $data['total_pairs'];
        $pair_counts = [60, 300, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000];
        $reward_names = ['Led TV 21’', 'Led TV 32’', 'Mi. 10i 128 gb', 'One Plus Nord CE2 lite', 'I phone 11', 'I phone 13', 'Toyota urban cruiser Hyryder', 'Mercedes benz CLA Class', 'BMW 2 Series', 'BANGLO 1CR'];
        $rank = ['Star', '2 Star', 'Bronze', 'Silver', 'Gold', 'Platinum', 'Diamond', 'Emerald', 'Garnet', 'Ruby'];
        if ($total_pair >= 60) {
            $m = 0;
            while ($total_pair >= $pair_counts[$m] && $m <= 9) {
                if (!check_for_update_reward($agent_id, $pair_counts[$m])) {
                    $rank_name = $rank[$m];
                    $k = mysqli_query($conn, "UPDATE `users` SET `rank`='$rank_name' WHERE `user_id`='$agent_id'");
                    if ($k) {
                        $reward = $reward_names[$m];
                        $pair = $pair_counts[$m];
                        $achieve_time = date("Y-m-d H:i:s");
                        mysqli_query($conn, "INSERT INTO `reward`(`agent_id`, `pair_for_reward`, `reward_name`, `achieve_time`) VALUES ('$agent_id','$pair','$reward','$achieve_time')");
                    }
                }
                $m++;
            }
        }
    }
}

function check_for_update_reward($agent_id, $pair_count) {
    global $conn;
    $m = mysqli_query($conn, "SELECT * FROM `reward` WHERE `agent_id`='$agent_id' AND `pair_for_reward`='$pair_count'");
    if (mysqli_num_rows($m) > 0) {
        return true;
    }
    return false;
}

function check_pin($pin) {
    global $conn;
    $query = mysqli_query($conn, "SELECT * FROM `pin` WHERE `pin_value`='$pin' AND `status`='0'");
    if (mysqli_num_rows($query) == 1) {
        mysqli_query($conn, "UPDATE `pin` SET `status`='1' WHERE `pin_value`='$pin'");
        return true;
    }
    return false;
}

function insert_into_users($s_id, $name, $pos, $mobile, $password) {
    global $conn;
    $user_id = rand(11111111, 99999999);
    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    mysqli_query($conn, "INSERT INTO `users`(`user_id`, `name`, `password`, `mobile`, `position`, `sponsor_id`) VALUES ('$user_id','$name','$hashed_password','$mobile','$pos',$s_id)");

    placement_id($user_id, $s_id, $pos);
}

function placement_id($user_id, $s_id, $pos) {
    global $conn;
    $spons_data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$s_id'"));
    if ($pos == 0) {
        if ($spons_data['left_side'] == 0) {
            mysqli_query($conn, "UPDATE `users` SET `left_side`='$user_id' WHERE `user_id`='$s_id'");
            mysqli_query($conn, "UPDATE `users` SET `placement_id`='$s_id'  WHERE `user_id`='$user_id'");
            binary_count($user_id, $pos);
        } else {
            placement_id($user_id, $spons_data['left_side'], $pos);
        }
    } else {
        if ($spons_data['right_side'] == 0) {
            mysqli_query($conn, "UPDATE `users` SET `right_side`='$user_id' WHERE `user_id`='$s_id'");
            mysqli_query($conn, "UPDATE `users` SET `placement_id`='$s_id'  WHERE `user_id`='$user_id'");
            binary_count($user_id, $pos);
        } else {
            placement_id($user_id, $spons_data['right_side'], $pos);
        }
    }
    if (is_spill_income_eligible($user_id, $s_id)) {
        mysqli_query($conn, "UPDATE `users` SET `wallet`=`wallet`+50 WHERE `user_id`='$s_id'");
        mysqli_query($conn, "INSERT INTO `income_history`(`user_id`, `amount`, `description`, `credit_debit`, `admin_charges`, `tds`, `processed_at`) 
                             VALUES ('$s_id', 50, 'Spill Income', '0', '0', '0', NOW())");
    }
}

function find_sponsor_id($s_id) {
    global $conn;
    $data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$s_id'"));
    return $data['sponsor_id'];
}

function find_placement_id($s_id) {
    global $conn;
    $data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$s_id'"));
    return $data['placement_id'];
}

function find_position($s_id) {
    global $conn;
    $data = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `users` WHERE `user_id`='$s_id'"));
    $pos = $data['position'];
    if ($pos == 0) {
        $pos = "left_count";
    } else {
        $pos = "right_count";
    }
    return $pos;
}

// When logging in:
function move_to_dashboard($user_id, $pass) {
    global $conn;

    $stmt = mysqli_prepare($conn, "SELECT * FROM `users` WHERE `user_id`=?");
    mysqli_stmt_bind_param($stmt, "s", $user_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if (mysqli_num_rows($result) == 1) {
        $user = mysqli_fetch_assoc($result);

        // Verify password
        if (password_verify($pass, $user['password'])) {
            $_SESSION['session_id'] = session_id();
            $_SESSION['user_id'] = $user_id;
            header("Location:../dashboard.php");
            exit();
        }
    }

    header("Location:../index.php?error=invalid_credentials");
    exit();
}

if (isset($_POST['refresh_payout']) && isset($_SESSION['user_id'])) {
    require_once 'tree_rewards.php';
    $levelAmounts = [
        1 => 250, 2 => 350, 3 => 500, 4 => 800, 5 => 1200, 6 => 1900,
        7 => 3200, 8 => 5100, 9 => 7500, 10 => 10000, 11 => 0
    ];
    $rewards = processLevelPayments($conn, $_SESSION['user_id'], $levelAmounts);
    header("Location: ../wallet_tree.php");
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['id']) && isset($_POST['sponsor_id'])) {
    $id = $_POST['id'];
    $sponsor_id = $_POST['sponsor_id'];
    $position = $_POST['position'];

    // Add the user
    $stmt = $conn->prepare("INSERT INTO users (id, sponsor_id) VALUES (?, ?)");
    $stmt->bind_param("ii", $id, $sponsor_id);
    $stmt->execute();

    // Assign to sponsor's left or right
    if ($position == "left") {
        $conn->query("UPDATE users SET left_user = $id WHERE id = $sponsor_id");
    } else {
        $conn->query("UPDATE users SET right_user = $id WHERE id = $sponsor_id");
    }

    header("Location: load_tree.php?parent_id=$sponsor_id");
    exit;
}
ob_end_flush();
?>