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


startCalculation($dd);
updateDayonAdmin($dd);
updateAdminTrxReset($dd);

function startCalculation($dd)
{
    $getAdminDetails = $dd->single("admin_calculation"," where adminKey='1'");
    for($i=1; $i < 5; $i++){
        $getRunningGame = $dd->single("trx_runnning"," where game_name='$i'");
        if($getRunningGame['duration'] <= 1){
           
            $clm = "trx_".$i;
            if($getAdminDetails[$clm] != ""){
                    $openingNumber = $getAdminDetails[$clm];
                    ///////////////////-------------------------Excute next task-------------///////
                    proccessedNextActivity($dd,$openingNumber,$i);
                    finalproccessdActivity($dd,$openingNumber,$i);
                    finalCloseGameLossuser($dd,$openingNumber,$i);
                    closedGame($dd,$openingNumber,$i);
            }else{
                if($getAdminDetails['trxResult_type'] == "randum"){
                    $openingNumber = rand(0, 9);
                    ///////////////////-------------------------Excute next task-------------///////
                    proccessedNextActivity($dd,$openingNumber,$i);
                    finalproccessdActivity($dd,$openingNumber,$i);
                    finalCloseGameLossuser($dd,$openingNumber,$i);
                    closedGame($dd,$openingNumber,$i);
                }else{
                    getToexcuteMinimum($dd,$i);
                } 
            }
           
           
            updateAdminResetData($dd,$i);
        }else{
            $update = $dd->updateData("trx_runnning","duration=duration-1"," game_name='$i'");
        }
    }
}









function updateDayonAdmin($dd)
{
    $getAdminDetails = $dd->single("admin_calculation"," where adminKey='1'");
    $day = date("D");
    if($getAdminDetails['trx_last_update'] != $day){
        $update = $dd->updateData("admin_calculation","trx_last_update='$day'"," adminKey='1'");
    }
}





function getToexcuteMinimum($dd,$gamenumber){
$table = "account_history";
$condition = " where gameNumber='$gamenumber' AND status='pending' AND game_name='TRX'";
$getHistory = $dd->fetch_multi($table,$condition);
$secondArray  = array();
foreach($getHistory as $key){
    $secondArray[] = array("bet_amount" => $key->bet_amount,"amount" => $key->amount,"lossorprofit" => $key->lossorprofit,"selected_number" => $key->selected_number);
}






$firstArray  = array();
for($i=0; $i < 10; $i++){
    $firstArray[] = array("bet_amount" =>0,"amount" => 0,"lossorprofit" => 0, "selected_number" => $i);
}



foreach ($secondArray as $entry) {
    foreach ($firstArray as &$item) {
        if ($item["selected_number"] == $entry["selected_number"]) {
            $item["bet_amount"] += $entry["bet_amount"];
            $item["amount"] += $entry["amount"];
            $item["lossorprofit"] += $entry["lossorprofit"];
        }
    }
}






/////////////////////////////---------------------------Get randum roes--------------////
$minLossOrProfit = min(array_column($firstArray, 'lossorprofit'));

// Filter rows where lossorprofit equals the minimum value
$minRows = array_filter($firstArray, function ($row) use ($minLossOrProfit) {
    return $row['lossorprofit'] == $minLossOrProfit;
});

// Randomly select one row from the filtered rows
if (!empty($minRows)) {
    $randomRow = $minRows[array_rand($minRows)];
    $openingNumber = $randomRow['selected_number'];
}


///////////////////-------------------------Excute next task-------------///////
proccessedNextActivity($dd,$openingNumber,$gamenumber);
finalproccessdActivity($dd,$openingNumber,$gamenumber);
finalCloseGameLossuser($dd,$openingNumber,$gamenumber);
closedGame($dd,$openingNumber,$gamenumber);
}








function proccessedNextActivity($dd,$openingNumber,$gamenumber){
    if($openingNumber == "0"){
       $condition = " where gameNumber='$gamenumber' AND status='pending' AND game_name='TRX' AND selected_number='red' OR selected_number='violet'";
        $getAccount = $dd->fetch_multi("account_history",$condition);
        foreach($getAccount as $key){
            if($key->selected_number == "red"){
                $multiple = 1.5;
            }else if($key->selected_number == "violet"){
                $multiple = 4.5;
            }else if($key->selected_number == "green"){
                $multiple = 1.5;
            }
            
            $userKey = $key->userKey;
            $accountKey = $key->accountKey;
            $profitAmount = $key->bet_amount*$multiple;
            getToProccessdBalanceDeposit($dd,$openingNumber,$profitAmount,$userKey,$accountKey,$gamenumber);
        }
    }else if($openingNumber == "5"){
         $condition = " where gameNumber='$gamenumber' AND status='pending' AND game_name='TRX' AND selected_number='green' OR selected_number='violet'";
         $getAccount = $dd->fetch_multi("account_history",$condition);
         foreach($getAccount as $key){
            if($key->selected_number == "red"){
                $multiple = 1.5;
            }else if($key->selected_number == "violet"){
                $multiple = 4.5;
            }else if($key->selected_number == "green"){
                $multiple = 1.5;
            }
            
            $userKey = $key->userKey;
            $accountKey = $key->accountKey;
            $profitAmount = $key->bet_amount*$multiple;
            getToProccessdBalanceDeposit($dd,$openingNumber,$profitAmount,$userKey,$accountKey,$gamenumber);
        }
    }
}















function finalproccessdActivity($dd,$openingNumber,$gamenumber){
    $getOrder = $dd->fetch_multi("account_history"," where selected_number='$openingNumber' AND gameNumber='$gamenumber' AND status='pending' AND game_name='TRX'");
    foreach($getOrder as $key){
        $profitAmount = $key->lossorprofit;
        $userKey = $key->userKey;
        $accountKey = $key->accountKey;
        getToProccessdBalanceDeposit($dd,$openingNumber,$profitAmount,$userKey,$accountKey,$gamenumber);
    }
}






function getToProccessdBalanceDeposit($dd,$openingNumber,$profitAmount,$userKey,$accountKey,$gamenumber)
{
    $result = $dd->updateData("userdetails","wallet=wallet+$profitAmount,winamount=winamount+$profitAmount"," userKey='$userKey'");
    if($result){
        addaccountHistory($dd,$openingNumber,$profitAmount,$userKey,$accountKey,$gamenumber);
    }
}





function addaccountHistory($dd,$openingNumber,$profitAmount,$userKey,$accountKey,$gamenumber)
{
    
    if($openingNumber == "0"){
        $clr = "red,violet";
        $bigsmall = "small";
    }else if($openingNumber == "1"){
        $clr = "green";
        $bigsmall = "small";
    }else if($openingNumber == "2"){
        $clr = "red";
        $bigsmall = "small";
        
    }else if($openingNumber == "3"){
        $clr = "green";
        $bigsmall = "small";
        
    }else if($openingNumber == "4"){
        $clr = "red";
        $bigsmall = "small";
        
    }else if($openingNumber == "5"){
        $clr = "violet,green";
        $bigsmall = "big";
        
    }else if($openingNumber == "6"){
        $clr = "red";
        $bigsmall = "big";
        
    }else if($openingNumber == "7"){
        $clr = "green";
        $bigsmall = "big";
        
    }else if($openingNumber == "8"){
        $clr = "red";
        $bigsmall = "big";
        
    }else if($openingNumber == "9"){
        $clr = "green";
        $bigsmall = "big";
        
    }
    
    
    $date = date("H:i:s d/m/Y");
    $update = $dd->updateData("account_history","lossorprofit='+$profitAmount',result_number='$openingNumber',status='success',time_calculation='$date',color='$clr',bigsmall='$bigsmall'"," accountKey='$accountKey'");

    
}






//////////////////////---------------LOSS USER
function finalCloseGameLossuser($dd,$openingNumber,$gamenumber)
{
    
    if($openingNumber == "0"){
        $clr = "red,violet";
        $bigsmall = "small";
    }else if($openingNumber == "1"){
        $clr = "green";
        $bigsmall = "small";
    }else if($openingNumber == "2"){
        $clr = "red";
        $bigsmall = "small";
        
    }else if($openingNumber == "3"){
        $clr = "green";
        $bigsmall = "small";
        
    }else if($openingNumber == "4"){
        $clr = "red";
        $bigsmall = "small";
        
    }else if($openingNumber == "5"){
        $clr = "violet,green";
        $bigsmall = "big";
        
    }else if($openingNumber == "6"){
        $clr = "red";
        $bigsmall = "big";
        
    }else if($openingNumber == "7"){
        $clr = "green";
        $bigsmall = "big";
        
    }else if($openingNumber == "8"){
        $clr = "red";
        $bigsmall = "big";
        
    }else if($openingNumber == "9"){
        $clr = "green";
        $bigsmall = "big";
        
    }
    
     $date = date("H:i:s d/m/Y");
     $update = $dd->updateData("account_history","lossorprofit=-bet_amount,result_number='$openingNumber',status='success',time_calculation='$date',color='$clr',bigsmall='$bigsmall'"," gameNumber='$gamenumber' AND game_name='TRX' AND status='pending'"); 
}








////////////////////////-----------------------------------------------------Game closed-------
function closedGame($dd,$openingNumber,$gamenumber)
{
    if($gamenumber == 1){
        $newUpdae = "1";
    }else if($gamenumber == 2){
        $newUpdae = "3";
    }else if($gamenumber == 3){
        $newUpdae = "5";
    }else if($gamenumber == 4){
        $newUpdae = "10";
    }
    
    
    
    $date = date("i");
    $day = date("D");
    $getLastUpdate = $dd->single("trx_runnning"," where game_name='$gamenumber'");
    $lastupdate = $getLastUpdate['lastupdate'];
    $duration = $getLastUpdate['duration'];
    $getAdminDetails = $dd->single("admin_calculation"," where adminKey='1'");
    if($getAdminDetails['trx_last_update'] != $day){
        $periods = date("Ymd")."000";
        $update = $dd->updateData("trx_runnning","periods='$periods',duration='$newUpdae'"," game_name='$gamenumber'");
        insertExistingResult($dd,$openingNumber,$gamenumber,$periods);
    }else{
        $periods = $getLastUpdate['periods']+1;
        $update = $dd->updateData("trx_runnning","periods='$periods',duration='$newUpdae'"," game_name='$gamenumber'");
        insertExistingResult($dd,$openingNumber,$gamenumber,$periods);
    }
  
}





//////////////////////////////------------------Existing Result--------
function insertExistingResult($dd,$openingNumber,$gamenumber,$periods)
{
    $blockHeight = date("His").mt_rand(111,999);
    $hashValue = md5($blockHeight).$openingNumber;
    if($openingNumber < 5){
        $bigsmall = "s";
    }else{
        $bigsmall = "b";
    }
    
    $date = date("H:i:s d/m/Y");
    $table = "trx_existing_result";
    $value = "(`action_date`, `periods`, `hase_key`, `resultNumber`, `small_big`, `game_number`, `status`) 
    VALUES ('$date','$periods','$hashValue','$openingNumber','$bigsmall','$gamenumber','success')";
    $result = $dd->insertData($table,$value);
}








////////////////////////----------------Reset Admin
function updateAdminResetData($dd,$gameNumber)
{
    $clm = "trx_".$gameNumber;
    $update = $dd->updateData("admin_calculation","$clm=''"," adminKey='1'");
}



?>