<?php
//if ( ! defined('BASEPATH')) exit('No direct script access allowed');
namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use App\Models\userdash_model;
use App\Helpers\site_helper;
use App\Libraries\MyEncrypt;
use App\Libraries\WalletCoreAPI;
use App\Models\Commissions;
use App\Models\Rank_update;
error_reporting(0);

class Activation extends BaseController
{
    public function __construct()
    {
        helper("site_helper");
        $this->db = db_connect();
        $myencrypt = new MyEncrypt(true);
        $this->common_model = model("CommonModel");
        $session = \Config\Services::session();
        $validation = \Config\Services::validation();
        $uri = service("uri");
        if (!$session->get("user_login")) {
            return redirect()->to("login");
        }
        $status = site_info("site_status");
        if ($status != "on") {
            return redirect()->to("offline");
        }
        // user login only
        if ($session->get("user_login")) {
            // form validation library
            // $this->load->library('form_validation');
            // $this->load->model('userdash_model');
            // $this->load->model('finance_model');
            $this->finance_model = model("finance_model");
            $this->userdash_model = model("userdash_model");
        } else {
            throw new \CodeIgniter\Router\Exceptions\RedirectException("login");
        }
    }

    public function index()
    {
        $this->session = session();
        $uusersid = $this->session->get("uusersid");
        if ($this->request->getPost()) {
            $country = $this->request->getPost("country");
            $amt = $this->db
                ->query("SELECT * FROM  adminsettings WHERE id=1 ")
                ->getResult();
            $amnt = $amt[0];
            $amount = $amnt->activation_cost;
            $uusersid = $uusersid;

            $qry = $this->db
                ->query(
                    "SELECT * FROM  payment_controls WHERE payment_name='bitcoin' && payment_key='btc_address' "
                )
                ->getResult();
            $res = $qry[0];
            $btc = $res->payment_value;
            $pay_nme = $res->payment_name;
            $this->dta["amount"] = $amount;

            $usrdta = [
                "country" => $country,
            ];
            $this->db = db_connect();
            $query_status = $this->db
                ->table("uusers")
                ->where("uusersid", $uusersid)
                ->update($usrdta);

            $coin_name = "BTC";
            $condition = "payment_name ='" . $pay_nme . "'";
            $cointable = $this->common_model->GetRow(
                "payment_controls",
                $condition
            );
            $qry1 = $this->db
                ->query(
                    "SELECT * FROM  payment_controls WHERE payment_name='bitcoin' && payment_key='api_key' "
                )
                ->getResult();
            $res1 = $qry1[0];
            foreach ($cointable as $row) {
                $form_data[$row->payment_key] = $row->payment_value;
            }
            $apikey = $res1->payment_value;

            $condition = "payment_name ='" . $pay_nme . "' ";
            $getaddress = $this->common_model->GetRow(
                "payment_controls",
                $condition
            );

            $main_url = "https://api.blockcypher.com/";
            $path = "v1/btc/main/addrs?token=" . $apikey;
            $headers = ["Content-Type: application/x-www-form-urlencoded"];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $main_url . $path);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Ignore Verify SSL Certificate
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => $headers,
            ]);
            $output = curl_exec($ch);
            curl_close($ch);
            $result = json_decode($output, true);
            //echo $apikey;
            //exit();
            $getaddress1 = $result["address"];
            $private = $result["private"];
            $public = $result["public"];

            $confirm = $this->db
                ->query("SELECT * FROM  key_tab WHERE  uusersid=$uusersid ")
                ->getResult();
            $conf = $confirm[0];
            if ($conf->btc_address != "") {
            } else {
                $query_status = $this->db->query(
                    "INSERT INTO key_tab(uusersid,amount,type,depositid,private_key,public_key,btc_address,activation)VALUES('$uusersid','$amount','activation','0','$private','$public','$getaddress1','0')"
                );
            }

            return redirect()->to("user/activation/activate");
        }
        
       

        echo view("user/activation");
    }

    public function activate()
    {
        
        
        $session = \Config\Services::session();
        $id = "NyYmemh5aXA=";
        $myencrypt = new MyEncrypt();
        $coinid = $myencrypt->decode($id);
        $buy_bal = curbalance($session->get("uusersid"), $coinid);
        $curbalance = str_replace(",", "", $buy_bal);
        $this->common_model = model("CommonModel");
        $this->db = db_connect();
        $amt = $this->db
            ->query("SELECT * FROM  adminsettings WHERE id=1")
            ->getResult();
        $amnt = $amt[0];
        $activation_cost = $amnt->activation_cost;
        $uusersid = $session->get("uusersid");
        //$curbalance = '18';

        if ($uusersid && $curbalance >= $activation_cost) {
            // String of all alphanumeric character
            $str_result ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

            // Shuffle the $str_result and returns substring
            // of specified length
            $tnxid = substr(str_shuffle($str_result), 0, 10);

            $str_result ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

            // Shuffle the $str_result and returns substring
            // of specified length
            $address = "0x" . substr(str_shuffle($str_result), 0, 30);

            $tradSets = $this->common_model->GetResults("adminsettings", "");
            
            $subs_type=$tradSets[0]->subs_type;
            if($subs_type=='yearly')
            {
                $days='365 days';
            }
            else
            {
                $days='30 days';
            }
            
            $get_response=$this->db->table('history')->where('uusersid',$uusersid)->where('type','Activation')->where('status','1')->get()->getRow();
            if($get_response)
            {
                $exp_date=date("Y-m-d h:i:s",strtotime($get_response->expiry_date . "+ ".$days));
                $reference_id=$get_response->historyid;
            }
            else
            {
                $exp_date=date("Y-m-d h:i:s",strtotime($date . "+ ".$days));
                $reference_id='0';
            }

            $userinfo=$this->db->query("select * from uusers where uusersid='".$uusersid."'")->getRow();
            
            $transactionid = "ACT-" . $tnxid;
            if (!$get_status) {
                $historydata = [
                    "uusersid" => $uusersid,
                    "amount" => $tradSets[0]->activation_cost,
                    "btc_amount" => $tradSets[0]->activation_cost,
                    "type" => "Activation",
                    "payment_id" => 0,
                    "description" => "Member pay for activation",
                    "date" => date("Y-m-d h:i:s"),
                    "expiry_date" => $exp_date,
                    "receiver_id" => $reference_id,
                    "transactionid" => $transactionid,
                    "address" => $address,
                    "user_group"    => $userinfo->new_entry,
                    "status" => 1,
                ];


                $db = \Config\Database::connect();
                $history = $db->table("history");
                $update_status = $history->insert($historydata);

               

                if ($update_status) {
                    $notification = [
                        "uusersid" => $uusersid,
                        "message" => "Account activation succeeded",
                        "created_date" => date("Y-m-d H:i:s"),
                    ];
                    $this->db
                        ->table("notification_table")
                        ->insert($notification);
                    $session->setFlashData(
                        "success_message",
                        "Bot activated successfully"
                    );
                    return redirect()->to("activate/account");
                } else {
                    $session->setFlashData(
                        "error_message",
                        "Bot activation failed"
                    );
                    return redirect()->to("activate/account");
                }
               
            }
        } else {
            $session->setFlashData(
                "error_message",
                "Bot activated failed.Please recharge your asset and try again"
            );
            return redirect()->to("activate/account");
        }
    }

    public function fuel()
    {
        $this->db = db_connect();
        $this->session = session();
        $uusersid = $this->session->get("uusersid");
        $deposit_data["amount"] = $this->request->getPost("fuel");
        $deposit_data["payment_id"] = 9;
        $payment_id = 9;

        $payment_data = $this->common_model->GetPayment($payment_id);
        foreach ($payment_data as $row) {
            $form_data[$row->payment_key] = $row->payment_value;
            $form_data[$row->payment_key] = $row->payment_value;
        }

        $payment_name = $payment_data[0]->payment_name;
        $payment_id = $payment_data[0]->payment_id;

        $form_data["payment_name"] = $payment_name;
        $form_data["payment_id"] = $payment_id;

        $this->data["form_deposit"] = $deposit_data;
        $this->data["form_payment"] = $form_data;

        if ($deposit_data["amount"] != 0) {
            $datas = [
                "uusersid" => $uusersid,
                "amount" => $deposit_data["amount"],
                "payment_id" => $deposit_data["payment_id"],
                "status" => 0,
            ];

            $bulider = $this->db->table("uusers_fuel");
            $bulider->insert($datas);

            $datas = [
                "uusersid" => $uusersid,
                "amount" => $deposit_data["amount"],
                "type" => "fuel",
                "payment_id" => $deposit_data["payment_id"],
                "depositid" => 0,
                "status" => 1,
            ];

            $bulider = $this->db->table("history");
            $bulider->insert($datas);
            $this->data["deposit_id"] = $this->db->insertID();
        }

        echo view("user/active_fuel", $this->data);
    }

    public function deposit()
    {
        $this->db = db_connect();
        $this->session = session();
        $uusersid = $this->session->get("uusersid");
        if (!$this->session->get("uusersid")) {
            throw new \CodeIgniter\Router\Exceptions\RedirectException("login");
        }
        $deposit_data["amount"] = $this->request->getPost("fuel");
        $deposit_data["payment_id"] = 9;
        $payment_id = 9;

        $payment_data = $this->common_model->GetPayment($payment_id);
        foreach ($payment_data as $row) {
            $form_data[$row->payment_key] = $row->payment_value;
            $form_data[$row->payment_key] = $row->payment_value;
        }

        $payment_name = $payment_data[0]->payment_name;
        $payment_id = $payment_data[0]->payment_id;

        $form_data["payment_name"] = $payment_name;
        $form_data["payment_id"] = $payment_id;

        $this->data["form_deposit"] = $deposit_data;
        $this->data["form_payment"] = $form_data;

        echo view("user/user_deposit", $this->data);
    }

    public function address()
    {
        $this->db = db_connect();
        $this->session = session();
        $uusersid = $this->session->get("uusersid");
        if (!$this->session->get("uusersid")) {
            throw new \CodeIgniter\Router\Exceptions\RedirectException("login");
        }

        $amount = $this->request->getPost("amount");

        $get_payment = $this->db
            ->query(
                "select * from payment_controls where payment_key='api_key' and payment_id='16'"
            )
            ->getRow();
        if ($get_payment) {
            $apiKey = $get_payment->payment_value;
            $endpoint = "https://api.nowpayments.io/v1/payment";
            $data = [
                "price_amount" => $amount,
                "price_currency" => "usdttrc20",
                "pay_currency" => "usdttrc20",
                "ipn_callback_url" =>
                    "https://aiquantification.com/user/login/success",
                "order_id" => strtotime(date("Y-m-d H:i:s")) . "&&" . $uusersid,
                "order_description" => "Trading Bot user Deposit",
            ];
            $curl = curl_init($endpoint);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER, [
                "x-api-key: " . $apiKey,
                "Content-Type: application/json",
            ]);
            $response = curl_exec($curl);

            if ($response === false) {
                $result = "cURL error: " . curl_error($curl);
                $msg = "error";
                $msg .= "###";
                $msg .= $result;
            } else {
                $responseData = json_decode($response, true);
                if (isset($responseData["error"])) {
                    $result = "Error: " . $responseData["error"];
                    $msg = "error";
                    $msg .= "###";
                    $msg .= $result;
                } else {
                    $paymentAddress = $responseData["pay_address"];
                    $payment_id = $responseData["payment_id"];
                    $msg = "success";
                    $msg .= "###";
                    $msg .= $paymentAddress;

                    $address_data = [
                        "uusersid" => $uusersid,
                        "payment_address" => $paymentAddress,
                        "payment_id" => $payment_id,
                        "requested_amount" => $amount,
                        "paid_amount" => "0",
                        "created_date" => date("Y-m-d h:i:s"),
                        "status" => "1",
                    ];
                    $this->db
                        ->table("nowpayment_address")
                        ->insert($address_data);
                }
            }
        } else {
            $msg = "error";
            $msg .= "###";
            $msg .= "No Payment details provided";
        }

        echo $msg;
    }

    public function address_validate()
    {
        $get_payment = $this->db
            ->query(
                "select * from payment_controls where payment_key='api_key' and payment_id='16'"
            )
            ->getRow();
        $get_password = $this->db
            ->query(
                "select * from payment_controls where payment_key='merchant_email' and payment_id='16'"
            )
            ->getRow();
        $get_email = $this->db
            ->query(
                "select * from payment_controls where payment_key='merchant_email' and payment_id='16'"
            )
            ->getRow();

        $auth_url = "https://api.nowpayments.io/v1/auth";
        $params1 = [
            "email" => "drtajmuhammadmarri@gmail.com", // Example amount in USD
            "password" => "TajalimuradDuralimurad@786",
        ];

        $curl = curl_init($auth_url);

        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params1));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Content-Type: application/json",
        ]);

        $response1 = curl_exec($curl);
        $response1 = json_decode($response1, true);
        $jwtToken = $response1["token"];

        $apikey = "RC00797-F85MEED-Q0KF38Y-CB9GXTS";

        $endpoint =
            "https://api.nowpayments.io/v1/payment/?limit=100&page=0&sortBy=created_at&orderBy=asc";

        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer " . $jwtToken,
            "Content-Type: application/json",
            "x-api-key: " . $apiKey,
        ]); // Initialize cURL session
        $curl = curl_init($endpoint);
        // Set cURL options for the POST request
        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer " . $jwtToken,
            "Content-Type: application/json",
            "x-api-key: " . $apiKey,
        ]);

        $response = curl_exec($curl);
        $responseData = json_decode($response, true);

        echo "<pre>";
        print_r($responseData);
        echo "</pre>";
    }

    public function deposit_verify()
    {
        $session = session();
        $this->db = db_connect();
        $userinfo = "uusersid = '" . $session->get("uusersid") . "'";
    }

    public function network()
    {
        $CommonModel = model("CommonModel");
        $session = session();
        if (!$session->get("uusersid")) {
            throw new \CodeIgniter\Router\Exceptions\RedirectException("login");
        }
        $this->userdash_model = model("userdash_model");
        $this->db = db_connect();
        $reff_condition = "referral_id = '" . $session->get("uusersid") . "'";
        $direct_sponsors = $CommonModel->GetResults("uusers", $reff_condition);
        $active_direct = 0;
        $inactive_direct = 0;
        $active_indirect = 0;
        $inactive_indirect = 0;
        $i = 0;
        $j = 0;
        $k = 0;
        $exchange=$session->get("exchange");
       
        if ($direct_sponsors) {
            foreach ($direct_sponsors as $key => $value) {
                $direct_referrals[$k] = $value;
                $direct_mem[$i] = $value->uusersid;
                $check = $this->db
                    ->query(
                        "select * from history where type = 'activation' and status = 1 and uusersid='" .
                            $value->uusersid .
                            "'"
                    )
                    ->getRow();
                $reff_condition1 = "referral_id = '" . $value->uusersid . "'";
                $mysponsorscount = $this->db
                    ->query(
                        "select * from uusers where referral_id='" .
                            $value->uusersid .
                            "'"
                    )
                    ->getNumRows();
                $direct_referrals[$k]->team_members = $mysponsorscount;
                $uusers_matrix = $this->db
                    ->query(
                        "Select * from uusers_matrix where uusersid = '" .
                            $value->uusersid .
                            "'"
                    )
                    ->getRow();
                $direct_referrals[$k]->rank = $uusers_matrix->rankid;
                if (!empty($check)) {
                    $active_direct = $active_direct + 1;
                    $direct_referrals[$k]->activation_date = $check->date;
                    $direct_referrals[$k]->activation_status = $check->status;
                } else {
                    $inactive_direct = $inactive_direct + 1;
                    $direct_referrals[$k]->activation_date = $value->createdate;
                    $direct_referrals[$k]->activation_status = 0;
                }
                $i++;
                $k++;
            }
            $indirect_pre = $this->db
                ->query(
                    "Select * from uusers_matrix where uusersid = '" .
                        $session->get("uusersid") .
                        "'"
                )
                ->getRow();
            $members_cnt = explode(",", $indirect_pre->members_cnt);
            foreach ($members_cnt as $key => $value1) {
                if (!in_array($value1, $direct_mem)) {
                    $indirect_mem[$j] = $value1;
                    $j++;
                }
            }
            foreach ($indirect_mem as $key => $value3) {
                $check1 = $this->db
                    ->query(
                        "select * from history where type = 'activation' and status = 1 and uusersid='" .
                            $value3 .
                            "'"
                    )
                    ->getRow();
                if (!empty($check1)) {
                    $active_indirect = $active_indirect + 1;
                } else {
                    $inactive_indirect = $inactive_indirect + 1;
                }

                // $condition = "status = '1' ";
                // $rank_details = $CommonModel->GetResults("rewardsettings",$condition);

              
                // $max_rank_id = 0;
                // foreach ($rank_details as $row) {
                //     if ($row->id > $max_rank_id) {
                //         $max_rank_id = $row->id;
                //     }
                // }
                
                // // Initialize the rank counts array dynamically based on the maximum rank ID
                // $rank_counts = array_fill(1, $max_rank_id, 0);
                
                // $rank = $this->db->query("SELECT * FROM uusers WHERE uusersid='" . $value3 . "'")->getRow();
                
                // foreach ($rank_details as $row) {
                //     // Check if the rank ID exists in our array range
                //     if (isset($rank_counts[$rank->rankid]) && $rank->rankid == $row->id) {
                //         $rank_counts[$rank->rankid]++; // Increment the specific rank count
                //     }
                // }
            }
        }

     
        $this->data["active_indirect"] = $active_indirect;
        $this->data["inactive_indirect"] = $inactive_indirect;
        $this->data["active_direct"] = $active_direct;
        $this->data["inactive_direct"] = $inactive_direct;
        $this->data["direct_referrals"] = $direct_referrals;
        //$this->data['ranks'] = $rank_counts;
        
        $this->data["today_profit"] = $CommonModel->today_profit(
            $session->get("uusersid"),$session->get("exchange")
        );
        $this->data["total_profit"] = $CommonModel->total_profit(
            $session->get("uusersid"),$session->get("exchange")
        );
        echo view("user/network", $this->data);
    }

    function checkuserbalance($id)
    {
        $sender_id = $this->request->getPost("id");

        $buy_bal = curbalance($this->request->getPost("id"));
        $balance = str_replace(",", "", $buy_bal);

        if ($balance > 0) {
            // if(service('request')->getPost('payment')){
            //  $json['valid'] = true;
            // } else {
            echo number_format($balance, 2, ".", "");
            //}
        } else {
            // if(service('request')->getPost('payment')){
            //  $json['valid'] = false;
            //  $json['message'] = "The selected gateway have Insufficient balance";
            // } else {
            echo number_format(0, 2, ".", "");
            //}
        }
        if (isset($json)) {
            echo json_encode($json);
        }
    }

    public function activate_account()
    {
        echo view("user/activate_account");
    }

    public function activation_history()
    {
        $this->common_model = model('CommonModel');
        $session = \Config\Services::session();

        $uusersid = $this->request->getPost('uusersid');
        $page = $this->request->getPost('page');
        $itemsPerPage = $this->request->getPost('itemsPerPage');
        $offset = ($page - 1) * $itemsPerPage;

        $totalItems = $this->db->query("select * from `history` WHERE uusersid = '".$uusersid."' AND type='activation'  ORDER BY `historyid` DESC ")->getNumRows();
        $get_records = $this->db->query("select * from `history` WHERE uusersid = '".$uusersid."' AND type='activation' ORDER BY `historyid` DESC limit $offset,$itemsPerPage")->getResult();

        $totalPages = ceil($totalItems / $itemsPerPage);
		$items = array();

        if($get_records)
		{
			foreach($get_records as $row)
			{
				
          
                $amount='<label class="btn btn-success">'.number_format($row->amount,4).' USDT</label>';
                $description=$row->description;

                $datee = date('d M Y H:m:s',strtotime($result->expiry_date));

                if($row->status == '1')
                {
                    $active = 'Active';
                }
                else if($row->status == '0')
                {
                    $active = 'InActive';
                }
               
                $items[] = [
                    'amount' =>  $amount,
                    'date' => $datee,
                    'trans_id' => $row->transactionid,
                    'status' =>$active
                ];

		    }
	    }

        echo json_encode([
            'items' => $items,
            'hasPrev' => $page > 1,
            'hasNext' => $page < $totalPages,
            'totalPages' => $totalPages,
            'totalitems' => $totalItems
        ]);


    }
}
