<?php
/**
 * commission_helper.php
 * Include this file wherever tasks are completed or plans are joined.
 * Requires: $conn (mysqli) already loaded via db.php
 */

/**
 * Pay task commissions up 3 levels when a user completes a video task.
 * Call this right after inserting into task_completions.
 *
 * @param mysqli $conn
 * @param int    $earner_user_id  The user who completed the task
 * @param int    $plan_id         The plan the task belongs to
 * @param float  $earned_amount   How much the earner earned
 * @param string $video_title     Title of the video (for description)
 */
function payTaskCommissions($conn, $earner_user_id, $plan_id, $earned_amount, $video_title = '') {
    $plan = $conn->query("SELECT * FROM plans WHERE id=" . (int)$plan_id)->fetch_assoc();
    if (!$plan) return;

    $rates = [
        1 => (float)($plan['task_commission_l1'] ?? 0),
        2 => (float)($plan['task_commission_l2'] ?? 0),
        3 => (float)($plan['task_commission_l3'] ?? 0),
    ];

    $current_uid = (int)$earner_user_id;
    $vtitle      = $conn->real_escape_string($video_title);

    for ($level = 1; $level <= 3; $level++) {
        $row = $conn->query("SELECT referred_by FROM users WHERE id=$current_uid")->fetch_assoc();
        if (!$row || empty($row['referred_by'])) break;

        $upliner_id = (int)$row['referred_by'];
        $rate       = $rates[$level];

        if ($rate > 0 && $upliner_id > 0) {
            $commission = round($earned_amount * ($rate / 100), 4);
            if ($commission > 0) {
                $desc = $conn->real_escape_string(
                    "L{$level} task commission: user #{$earner_user_id}" .
                    ($video_title ? " watched '{$video_title}'" : '')
                );

                // Insert into commission_logs
                $conn->query("INSERT INTO commission_logs
                    (user_id, from_user_id, type, level, amount, description)
                    VALUES ($upliner_id, $earner_user_id, 'task', $level, $commission, '$desc')");

                // Credit upliner balance + total_earned
                $conn->query("UPDATE users
                    SET balance = balance + $commission,
                        total_earned = total_earned + $commission
                    WHERE id = $upliner_id");

                // Account log for upliner
                $conn->query("INSERT INTO account_logs
                    (user_id, type, category, amount, description)
                    VALUES ($upliner_id, 'income', 'commission', $commission, '$desc')");
            }
        }

        $current_uid = $upliner_id; // Walk one level up
    }
}

/**
 * Pay referral commissions up 3 levels when a user joins a paid plan.
 * Call this right after inserting into user_plans.
 *
 * @param mysqli $conn
 * @param int    $new_user_id  The user who just joined the plan
 * @param int    $plan_id      The plan they joined
 */
function payReferralCommissions($conn, $new_user_id, $plan_id) {
    // Only pay for paid (non-free) plans
    $plan = $conn->query("SELECT * FROM plans WHERE id=" . (int)$plan_id . " AND is_free=0")->fetch_assoc();
    if (!$plan) return;

    $plan_price = (float)$plan['price'];
    if ($plan_price <= 0) return;

    $rates = [
        1 => (float)($plan['ref_commission_l1'] ?? 0),
        2 => (float)($plan['ref_commission_l2'] ?? 0),
        3 => (float)($plan['ref_commission_l3'] ?? 0),
    ];

    $current_uid = (int)$new_user_id;
    $plan_name   = $conn->real_escape_string($plan['name']);

    for ($level = 1; $level <= 3; $level++) {
        $row = $conn->query("SELECT referred_by FROM users WHERE id=$current_uid")->fetch_assoc();
        if (!$row || empty($row['referred_by'])) break;

        $upliner_id = (int)$row['referred_by'];
        $rate       = $rates[$level];

        if ($rate > 0 && $upliner_id > 0) {
            $commission = round($plan_price * ($rate / 100), 4);
            if ($commission > 0) {
                $desc = $conn->real_escape_string(
                    "L{$level} referral commission — user #{$new_user_id} joined {$plan['name']}"
                );

                // Insert into commission_logs
                $conn->query("INSERT INTO commission_logs
                    (user_id, from_user_id, type, level, amount, description)
                    VALUES ($upliner_id, $new_user_id, 'referral', $level, $commission, '$desc')");

                // Credit upliner balance + total_earned
                $conn->query("UPDATE users
                    SET balance = balance + $commission,
                        total_earned = total_earned + $commission
                    WHERE id = $upliner_id");

                // Account log for upliner
                $conn->query("INSERT INTO account_logs
                    (user_id, type, category, amount, description)
                    VALUES ($upliner_id, 'income', 'referral', $commission, '$desc')");
            }
        }

        $current_uid = $upliner_id; // Walk one level up
    }
}