<?php

namespace App\Controllers\User;
use App\Views;
use App\Helpers\site_helper;
use App\Libraries\MyEncrypt;

class Profile extends BaseController
{
    public function __construct()
    {
        helper("site_helper");
        $this->db = db_connect();
        $myencrypt = new MyEncrypt(true);

        $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")) {
            $this->common_model = model("CommonModel");
        } else {
            throw new \CodeIgniter\Router\Exceptions\RedirectException("login");
        }
    }

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

    public function asset()
    {
        $this->session = session();
        $this->db = \Config\Database::connect();
        $uusersid = $this->session->get("uusersid");

        $this->data['history'] = $this->db->query("SELECT * FROM history WHERE uusersid = '".$uusersid."' and type not in('fuel','deducted_gaswallet') ORDER BY `date` DESC LIMIT 10")->getResult();

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

    public function invite()
    {
        $this->session = session();
        $this->db = \Config\Database::connect();
        $uusersid = $this->session->get("uusersid");

        $this->data["user_details"] = $this->db
            ->query("SELECT * FROM uusers WHERE uusersid = '" . $uusersid . "'")
            ->getrow();

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

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

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

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

    public function profile_update()
    {
        $this->db = db_connect();

        $this->common_model = model("CommonModel");
        $session = \Config\Services::session();
        $validation = \Config\Services::validation();

        $uusersid = $session->get("uusersid");

        $image = $_FILES["image"]["name"];

        if ($image != "") {
            $path = "assets/images/profile/";
            $file = $this->request->getFile("image");
            $upload_file = $this->uploadFile($path, $file);

            $profile_img = [
                "profile" => $upload_file,
            ];
            // $profile_img = implode(',', $profile_img);
            // $data["profile_img"] = $profile_img;
            $query_status = $this->db
                ->table("uusers")
                ->where("uusersid", $uusersid)
                ->update($profile_img);

            if ($query_status) {
                echo "1";
            } else {
                echo "0";
            }
        } else {
            echo "2";
        }
    }

    public function change_pass()
    {
        $this->session = \Config\Services::session();
        $this->db = db_connect();
        $uusersid = $this->request->getPost("userid");

        $user_details = $this->db
            ->query("SELECT * FROM uusers WHERE uusersid = '" . $uusersid . "'")
            ->getrow();
        $old_password = $this->request->getPost("old_password");
        $new_password = $this->request->getPost("new_password");

        if (md5($old_password) == $user_details->password) {
            $data = ["password" => md5($new_password)];
            $this->db
                ->table("uusers")
                ->where("uusersid", $user_details->uusersid)
                ->update($data);
            echo "success";
        } else {
            echo "error";
        }
    }
    
    public function deposit_req()
    {

        $this->session = session();
        $this->db = \Config\Database::connect();
        $uusersid = $this->session->get("uusersid");
        $amount = $this->request->getPost("amount");
        $image = $_FILES["attachment"]["name"];
        if($image=='')
        {
            $this->session->setFlashData("error_message","Proof not uploaded.. Please upload and confirm");
            return redirect()->back();

        }
        else
        {
            if($this->isValidImageExtension($image))
            {

                $str_result ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

                // Shuffle the $str_result and returns substring
                // of specified length
                $tnxid = substr(str_shuffle($str_result), 0, 10);
    
                $transactionid = "DEP-" . $tnxid;
                $address='TNMfzPRXi9z31nVXeyZRNcFNPhyMiw16Pq';

                $path = "../assets/images/profile/";
                $file = $this->request->getFile("attachment");
                $upload_file = $this->uploadFile($path, $file);
             
                $deposit_data = array(           // fuel fee deduction
                    'uusersid' => $uusersid,
                    'amount'  => $amount,
                    'type'  => 'deposit_req', 
                    'description'  => 'Deposit Requested',
                    'date'  => date('Y-m-d H:i:s'),
                    'currency' => 1,
                    'transactionid' => $transactionid,
                    'address' => $address,
                    'attachment' => $upload_file
                    );
                    $this->db->table('history')->insert($deposit_data); 

                    $this->session->setFlashData("success_message","Deposit Successfully Requested. wait for admin confirmation...");
                    return redirect()->back();
               
            }
            else
            {

                $this->session->setFlashData("error_message","Proof not accepted. Only JPG,PNG allowed");
                return redirect()->back();

            }

        }
        

    }

    function getFileExtension($filename) {
        return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    }
    
    // Function to validate the file extension
    function isValidImageExtension($filename) {
        $allowedExtensions = ['jpg', 'jpeg', 'png'];
        $extension = $this->getFileExtension($filename);
        
        return in_array($extension, $allowedExtensions);
    }

    public function change_security()
    {
        $this->session = \Config\Services::session();
        $this->db = db_connect();
        $uusersid = $this->request->getPost("userid");

        $user_details = $this->db
            ->query("SELECT * FROM uusers WHERE uusersid = '" . $uusersid . "'")
            ->getrow();
        $old_password = $this->request->getPost("old_password");
        $new_password = $this->request->getPost("new_password");

        if (md5($old_password) == $user_details->trans_password) {
            $data = ["trans_password" => md5($new_password)];
            $this->db
                ->table("uusers")
                ->where("uusersid", $user_details->uusersid)
                ->update($data);
            echo "success";
        } else {
            echo "error";
        }
    }

    public function uploadFile($path, $image)
    {
        if ($image->isValid() && !$image->hasMoved()) {
            $newName = $image->getRandomName();
            $image->move($path, $newName);
            return $image->getName();
        }
        return "";
    }

    public function rank()
    {
        $this->db = db_connect();
        $this->common_model = model("CommonModel");
        $condition = "status = '1' ";
        $this->data["rank_data"] = $this->common_model->GetResults(
            "rewardsettings",
            $condition
        );

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

    public function activate_rank($id)
    {
        $this->db = db_connect();
        $this->session = session();
        $this->common_model = model("CommonModel");
        $user = $this->session->get("uusersid");

        $condition = [
            "uusersid" => $user,
            "type" => "activation",
            "status" => "1",
        ];

        $result = $this->db->table("history")->where($condition)->get()->getRow();
        //$result = 1;

        if ($result) {
            $flag = 0;

            $con = "id = '" . $id . "'";
            $rank = $this->common_model->GetRow("rewardsettings", $con);

            $con = "referral_id= '" . $user . "'";

            $user_count = $this->db->query('select count("id") as user_cnt from uusers where referral_id = "' .$user .'"')->getRow();

            $uuser_count = $user_count->user_cnt;

            $direct_sponsor = $this->common_model->GetResults("uusers",$con);

            $balance = 0;

            if($direct_sponsor != '')
            {

            foreach ($direct_sponsor as $row) {
                $ucon = "uusersid = '" . $row->uusersid . "'";
                $uuser = $this->common_model->GetRow("uusers", $ucon);

                if ($uuser->rankid == $rank->sponsor_elg_rank) {
                    $flag++;
                }

                $buy_bal = curbalance($row->uusersid, 1);
                $curbalance = str_replace(",", "", $buy_bal);

                $balance = $balance + $curbalance;
            }
        }
        
         
        
            $con1 = "id = '" . $rank->sponsor_elg_rank . "'";
            $r_name = $this->common_model->GetRow("rewardsettings", $con1);
            
         

            if ($rank->sponsor_elg_rank != "") {
                if ($uuser_count < $rank->direct_spon_count) {
                    $this->session->setFlashdata("error_message","You must have " .$rank->direct_spon_count ." direct sponsors to activate the " .$rank->rank_name ." rank");
                    return redirect()->to("rank");
                } elseif ($flag < $rank->sponsor_elg_count) {
                    $this->session->setFlashdata("error_message","Your " .$rank->sponsor_elg_count ." direct sponsor must have " .$r_name->rank_name ." rank");
                    return redirect()->to("rank");
                } elseif ($balance < $rank->group_sales) {
                    $this->session->setFlashdata("error_message","Your group sales balance must be greater than " .number_format($rank->group_sales) ." USDT for " .$rank->rank_name ." rank");
                    return redirect()->to("rank");
                } else {
                    $this->data["rank_id"] = $id;

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

            $this->data["rank_id"] = $id;

            //echo view("user/activate_account", $this->data);
        } else {
            $this->session->setFlashData("error_message","Activate the bot first");
            return redirect()->to("rank");
        }
    }

    public function rank_update()
    {
        $rank_id = $this->request->getPost("rank_id");

        $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();

        $rewardsettings = $this->db->table("rewardsettings");
        $rewardsettings = $rewardsettings->where("id", $rank_id)->get()->getRow();
        $amount = $rewardsettings->amount;

        $uusersid = $session->get("uusersid");
        //$curbalance = '1800';

        if ($uusersid && $curbalance >= $amount) {
            // 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);

            $transactionid = "ACT-" . $tnxid;
            $address = "0x" . substr(str_shuffle($str_result), 0, 30);

            $rank_id = $rewardsettings->id;

            $rank_data = [
                "rankid" => $rank_id,
            ];

            // $uusers = $this->db->table('uusers_matrix');
            // $uusers = $uusers->where('uusersid',$uusersid)->update($rank_data);

            $uusers = $this->db->table("uusers");
            $uusers = $uusers->where("uusersid", $uusersid)->update($rank_data);
            
            $user_info = $this->db->table("uusers")->where('uusersid',$uusersid)->get()->getRow();
      

            $historydata1 = [
                "uusersid" => $uusersid,
                "amount" => $amount,
                "btc_amount" => $amount,
                "type" => "rank_activation",
                "description" => "Member pay for rank activation",
                "date" => date("Y-m-d h:i:s", time()),
                "receiver_id" => $rank_id,
                "transactionid" => $transactionid,
                "address" => $address,
                "status" => 1,
            ];

           $team_amount= $amount * $rewardsettings->team_reward/100;
           
          
           

           if($user_info->referral_id > 0)
           {
               
              
            $historydata2 = [
                "uusersid" => $user_info->referral_id,
               "amount" => $team_amount,
                 "btc_amount" => $team_amount,
                 "type" => "commissions",
                 "description" => "Rank Activation Team Reward Earned From -".$user_info->username,
                 "date" => date("Y-m-d h:i:s", time()),
                 "receiver_id" => $rank_id,
                 "transactionid" => $transactionid,
                 "address" => $address,
                 "status" => 1,
             ];
             
                $history = $this->db->table("history");
                $update_status1 = $history->insert($historydata2);
                

           }

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