<?php
@session_start();
include "control/activity.php";
$dd = new activity();

$table = "userdetails";
$condition = " where status='ACTIVE'";
$fetctUserdetails = $dd->fetch_multi($table,$condition);
foreach($fetctUserdetails as $key){
    $plan_key = $key->plan_key;
    $user_key = $key->user_key;

    getcredittoCommission($user_key,$plan_key,$dd);
}


function getcredittoCommission($user_key,$plan_key,$dd)
{
     $table = "create_package";
     $condition = " where package_iid='$plan_key'";
     $getPlanDetails = $dd->single($table,$condition);
     $margin = $getPlanDetails['commission'];
     $planAmount = $getPlanDetails['package_amount'];
     $commission = $planAmount/100*$margin;
     
     $table = "userdetails";
     $value = "main_wallet=main_wallet+$commission";
     $condition = " user_key='$user_key'";
     $result = $dd->updateData($table,$value,$condition);
     if($result){
        $txn = mt_rand(1111111111,9999999999);
        $date = date("h:i d/m/Y");
        $table = "account_details";
        $value = "(`username_key`, `action_date`, `txn_number`, `amount`, `avl_balance`, `status`, `remark`) 
        SELECT '$user_key','$date','$txn','$commission',main_wallet,'SUCCESS','Credit Daily Commission' FROM userdetails where user_key='$user_key'";
        $result = $dd->insertData($table,$value);
        if($result){
            calculatecommissiontoUpper($dd,$user_key,$planAmount);
        }
     }

}




function calculatecommissiontoUpper($dd,$user_key,$planAmount)
{
    $table = "level_incentive";
    $condition = null;
    $getLevel = $dd->fetch_multi($table,$condition);
    foreach($getLevel as $key){
       @$i++;
       $profit = $planAmount/100*$key->profit;
       gotoCreditAmount($dd,$user_key,$i,$profit);
    }
}



function gotoCreditAmount($dd,$user_key,$i,$profit)
{
   $tab1 = "level_$i";
   $table = "userdetails";
   $condition = " where user_key='$user_key'";
   $getLevel = $dd->single($table,$condition);
   $levelUser = $getLevel[$tab1];
   $memberUsername = $getLevel['username'];

   $condition = " where username='$levelUser'";
   $getLevelMember = $dd->check($table,$condition);
   if($getLevelMember['status'] == "success")
   {
       $table = "userdetails";
       $value = "main_wallet=main_wallet+$profit";
       $condition = " username='$levelUser'";
       $result = $dd->updateData($table,$value,$condition);
       if($result)
       {

        $txn = mt_rand(1111111111,9999999999);
        $date = date("h:i d/m/Y");
        $table = "account_details";
        $value = "(`username_key`, `action_date`, `txn_number`, `amount`, `avl_balance`, `status`, `remark`) 
        SELECT '$user_key','$date','$txn','$profit',main_wallet,'SUCCESS','Level Commision From $memberUsername' FROM userdetails where username='$levelUser'";
        $result = $dd->insertData($table,$value);


       }
   }

}
?>