<?php



class Helpers 
{       
    static function generate_captcha() {
        // Generate a random 4-digit number
        return rand(1000, 9999);
    }
     static function getuserbyusername($username)
    {
        $ci = & get_instance();
        $ci->load->model('Users');
        $username = $ci->Users->getuserbyuname($username);
        return $username;
    }
  
	static function user_id($model = false) {
		$ci =& get_instance();
		if(isset($ci->session->userdata["user"])) {
			$user = $ci->session->userdata["user"];
			return $model ? $user : $user["id"];
		}
	}
	static function date($date = false) {
		$res = false;
		if($date)
			$res =  date ('F d, Y ',strtotime($date));
		else
			$res = date('Y-m-d H:i:s');
		return $res;
	}
	static function flash($cssClass, $message, $extraClass='') {
		$res = array();
		if($cssClass && $message) {
			$res = array("class"=>$cssClass, "message"=>$message, "extraClass"=>$extraClass);
		}
		return $res;
	}

	static function showFlash($flash) {
		return "<div id='alertId' class='alert alert-".$flash['class']." ".$flash['extraClass']. "'>".$flash['message']."</div>";
	}
	
	static function getAdmin($model = false) {
		$ci =& get_instance();
		$ci->load->model('Users');
		$adminUser = $ci->Users->getAdminAccount();
		return $model ? $adminUser : $adminUser["id"];
	}

	static function userdetails($uid=false) {
		$uid = $uid ? $uid: self::user_id();
		$ci =& get_instance();
		$ci->load->model('Users');
		$user = $ci->Users->getUserById($uid);
		return $user;
	}
	static function getUserObj($uid=false) {
		$uid = $uid ? $uid: self::user_id();
		$ci =& get_instance();
		$ci->load->model('Users');
		$user = $ci->Users->getUserById($uid);
		return $user;
	}

	

	static function getPackageObj($pid) {
		$ci =& get_instance();
		$ci->load->model('Users');
		$user = $ci->Users->getPackageById($pid);
		return $user;
	}
	static function adminLink($url=false) {
		$link = '#';
		if($url) {
			$link = base_url().'admin/'.$url;
		}
		return $link;
	}

	static function generateLink($url=false) {
		$link = '#';
		if($url) {
			$link = base_url().'member/'.$url;
		}
		return $link;
	}
	static function get_user_fullname($userId = false){
		$ci =& get_instance();
		if($userId) {
			$user = self::getUserObj($userId);
		} else {
			$user = $ci->session->userdata["user"];
		}
		if($user) {
			return $user["full_name"];
		}

	}
	static function is_localhost() {
		$is_localhost = false;
		if($_SERVER['HTTP_HOST']=='localhost') {
			$is_localhost = true;

		} else if(self::is_test()) {
			$is_localhost = true;
		}
		return $is_localhost;
	}
	static function is_test() {
        if($_SERVER['SERVER_NAME'] == 'https://stablegainer.com/') {
            return true;
        }
        return false;
    }
	static function generateUniqueRefId($length = false) {
		$length = $length ? $length:6;
		$ci =& get_instance();
		$ci->load->helper('string');
		$code = random_string('alnum', $length);
		$uniqueCode = $code;
		return $uniqueCode;
	}

	static function generateUniquePin($length = false) {
		$length = $length ? $length:5;
		$ci =& get_instance();
		$ci->load->helper('string');
		$code = random_string('alnum', $length);
		$uniqueCode = self::isUniqueCode($code);
		return $uniqueCode;
	}


    // Function to check unique slug
	static function isUniqueCode($code) {
		$query = "SELECT * FROM epin";
		$ci =& get_instance();      
		$result = $ci->db->query($query);
		$row = $result->result_array();
		foreach ($row as $value) {
			$prev_code =  $value['epin'];   
			if($prev_code ==  $code){
				$code = random_string('alnum', 5);
			}
		}
		return $code;
	}
	
	static function sendEmail($emailTitle,$userEmail, $viewMessage){

		$ci =& get_instance();

		$ci->load->library('email');
		$config['protocol'] = 'sendmail';
		$config['mailpath'] = '/usr/sbin/sendmail';
		$config['charset'] = 'iso-8859-1';
		$config['wordwrap'] = TRUE;
		$ci->email->initialize($config);
		$ci->email->set_mailtype("html");
		$ci->email->set_newline("\r\n");
		$ci->email->to($userEmail);
		$ci->email->from('noreply@Solenders.com','Solenders');
		$ci->email->subject($emailTitle);
		$ci->email->message($viewMessage);
		$ci->email->send();
	
	}
	
	  static function sendEmailNew($emailTitle, $userEmail, $viewMessage)
    {
        $ci = &get_instance();
        $ci->load->library('email');

            $config = array(
                        'protocol' => 'smtp',
                        'smtp_host' => 'smtp-relay.brevo.com',
                        'smtp_port' => 587,
                        'smtp_user' => '91d30e002@smtp-brevo.com',
                        'smtp_pass' => 'gbyXTzmdrHBJ7fCR',
                        'mailtype'  => 'html',
                        'charset'   => 'iso-8859-1',
                        'smtp_crypto' => 'tls',
                         'wordwrap'     => TRUE
                        );

        $config['wordwrap'] = TRUE;

        $ci->email->initialize($config);

        $ci->email->set_newline("\r\n");
        
        $ci->email->to($userEmail);

        $ci->email->from('noreply@Solenders.com', 'Solenders');
        $ci->email->subject($emailTitle);
        $ci->email->message($viewMessage);
        if (!$ci->email->send()) {
        // 👇 Print the full error details
        echo "<pre>Email Send Error:\n";
        print_r($ci->email->print_debugger(['headers']));
        echo "</pre>";
    } else {
        echo "✅ Email sent successfully to $userEmail";
    }
  
    }
	



	static function checkstatus($uid=false)
	{
		$uid = $uid ? $uid: self::user_id();
		$ci =& get_instance();		
		$user = $ci->Members->checkstatus($uid);
		return $user ? 'Active' : 'Not Active';
	}
	static function checkRank($uid=false)
	{
		$uid = $uid ? $uid: self::user_id();
		$ci =& get_instance();		
		$user = $ci->Members->checkRank($uid);
		return $user ? $user['rank'] : 'No Rank';
	}

	static function daysDifferencesign($startDate,$finalDate) {
        $daysDiff=date_diff(date_create($startDate),date_create($finalDate))->format("%R%a");
        return $daysDiff;
    }

      static function totalusers()
    {
        $ci = & get_instance();
        $ci->load->model('Members');
        $totalusers = $ci->Members->gettotalusers();
        return $totalusers ? $totalusers : 0;
    }

     static function totalpaidusers()
    {
        $ci = & get_instance();
        $ci->load->model('Members');
        $totalpaidusers = $ci->Members->gettotalpaidusers();
        return $totalpaidusers ? $totalpaidusers : 0;
    }
    static function totalpackagesold()
    {
        $ci = & get_instance();
        $ci->load->model('Members');
        $totalpackagesold = $ci->Members->gettotalpackagesold();
        return $totalpackagesold ? $totalpackagesold : 0;
    }
    static function totalamountearned()
    {
        $ci = & get_instance();
        $ci->load->model('Members');
        $totalamountearned = $ci->Members->gettotalamountearned();
        return $totalamountearned ? $totalamountearned : 0;
    }

    static function getuserreferrals($uid)
    {
        // $uid = Helpers::user_id();
        $ci = & get_instance();
        $ci->load->model('Members');
        $query = $ci->Members->getreferrals($uid);
        return $query;
    }

static function getPageName() {

    $ci =& get_instance();

    $segment = $ci->uri->segment(1);

    return ucwords(str_replace("_", " ", $segment));

}

static function showPercentage($percentage){

        $num  = substr($percentage, 0, 2);
    if($num == 0.){

      return  $percentage*100;

    }else{

        return $percentage;

    }

}
   
	

}

class MemberHelper {
	private $globalUserId;
	static function getUserFromRefCode($code) {
		$ci =& get_instance();
		$ci->load->model('Users');
		$user = $ci->Users->getUserByRefCode($code);
		return $user ? $user : false;
	}
	static function get_user_earnings($id = false) {
		$ci =& get_instance();
		$response = array();
		$id = $id ? $id : helpers::user_id();
		$ci->load->model('Members');
		$allEarnings = $ci->Members->get_user_earning($id);
		$response = $allEarnings ? round($allEarnings['amount'],2): 0;
		return $response;

	}
	static function total_invest($id = false) {
		$ci =& get_instance();
		$response = array();
		$id = $id ? $id : helpers::user_id();
		$ci->load->model('Members');
		$allEarnings = $ci->Members->get_investment($id);
		$response = $allEarnings ? round($allEarnings['amount'],2): 0;
		return $response;
	}
	static function user_wallet($id = false, $type = 'dollar') {
		$ci =& get_instance();
		$id = $id ? $id : helpers::user_id();
		$ci->load->model('Members');
		$amount = $ci->Members->get_user_wallet($id);

		$walletAmount = $amount ? round($amount['wallet_amount'],2): 0;
		return $walletAmount ? round($walletAmount, 2):0;
	}
	static function user_daily_earnings($id = false, $type = 'dollar') {
		$ci =& get_instance();
		$id = $id ? $id : helpers::user_id();
		$ci->load->model('Members');
		$amount = $ci->Members->get_user_daily_earnings($id);

		$walletAmount = $amount ? round($amount['amount'],2): 0;
		return $walletAmount ? round($walletAmount, 2):0;
	}


	static function get_user_business($id = false) {
		$ci =& get_instance();
		$id = $id ? $id : helpers::user_id();
		$ci->load->model('Members');
		$amount = $ci->Members->get_user_total_earning($id);

		return $amount;
	}
	static function user_daily_earnings_with_balance($id = false, $type = 'dollar') {
		$ci =& get_instance();
		$id = $id ? $id : helpers::user_id();
		$ci->load->model('Members');
		$amount = $ci->Members->get_user_daily_earnings($id);

		$walletAmount = $amount ? round($amount['after_amount'],2): 0;
		return $walletAmount ? round($walletAmount, 2):0;
	}
	static function generateReferralLink() {
		$ci =& get_instance();
		$user = $ci->session->userdata["user"];
		return base_url() . 'register?ref=' . rawurlencode($user['referral_id']);
	}
	static function getMyParent($id = false) {
		$id = $id ? $id: Helpers::user_id();
		$ci =& get_instance();
		$ci->load->model('Members');
		$user =  $ci->Members->getParentByUserId($id);
		return $user;
	}
	static function getAllActiveUsersOfMember() {
		$user_id = Helpers::user_id();
		$ci =& get_instance();
		$ci->load->model('Members');
		$users = $ci->Members->getAllUsersOfMember($user_id);
		return $users;
	}
	static function getUnpaidUsersOfMember() {
		$user_id = Helpers::user_id();
		$ci =& get_instance();
		$ci->load->model('Members');
		$users = $ci->Members->getMyTeam($user_id);
		if($users) {
			$ids = implode(",",array_map(function($a) { return $a["user_id"]; }, $users));
			$paidUsers = $ci->Members->getPaidUsersOfMember($ids);
			$Unpaid = count($users) - $paidUsers;
			return $Unpaid;
		}
		return 0;
	}
	static function getAllPackages() {
		$ci =& get_instance();
		$ci->load->model('Adm');
		$packages = $ci->Adm->get_all_packages();
		return $packages;
	}

	static function user_earning() {
		$ci =& get_instance();
		$response = array();
		$id =  helpers::user_id();
		$ci->load->model('Members');
		$amount = $ci->Members->get_user_earning($id);
		$walletAmount = $amount ? $amount['amount']: 0;
		return $walletAmount ? round($walletAmount, 2):0;
		
	}

	static function check_max_commission($userId) {
		$ci =& get_instance();
		$ci->load->model('Members');
		$invest = $ci->Members->getTotalInvest($userId);
		$investAmt = isset($invest) ? $invest['amount'] : 0;
		$multiplyInvest = $investAmt * 2;
		$roi = $ci->Members->getTotalRoi($userId);	
		$roiAmt = isset($roi) ? $roi['amount'] : 0;		
		$commission = $ci->Members->getTotalCommission($userId);
		$commissionAmt = isset($commission) ? $commission['amount'] : 0;	
		$total = $roiAmt + $commissionAmt;
	
		if($multiplyInvest > $total){ // 40 < 80
			return true;
		}
		return false;
	}

	static function packageNameFromId($package_id = 26, $model = false) {
        $ci =& get_instance();      
        $ci->load->model('Members');
        $data = $ci->Members->getPackageFromId($package_id);
        if($model) {
            return $data ? $data : '';
        } 
        return $data ? $data["name"] : '';

    }

    

    static function isMember() {
    	$res = false;
    	$user = Helpers::getUserObj();
    	if($user)
    		$res = $user['role'] == 2 ? true: false;
    	return $res;
    }

    static function isBrandPartner() {
    	$res = false;
    	$user = Helpers::getUserObj();
    	if($user)
    		$res = $user['role'] == 3 ? true: false;
    	return $res;
    }

    static function isLeader() {
    	$res = false;
    	$user = Helpers::getUserObj();
    	if($user)
    		$res = $user['role'] == 4 ? true: false;
    	return $res;
    }

    static function getParents($userId = false) {
    	$ci =& get_instance(); 
    	$leaderId = $brandPartner = false;     
        $ci->load->model('Members');
        $leader = self::getMyParent($userId);
        if($leader) {
        	$leaderId = $leader['id'];
        	$brandPartner = self::getMyParent($leaderId);
        	if($brandPartner) {
        		$brandPartnerId = $brandPartner['id'];
        	}
        }
        return ['leader_id' => $leaderId, 'brand_partner_id' => $brandPartnerId];
    }
    
      static function message_seen($uid)
{
    $ci = &get_instance();
    $ci->load->model('Members');
    $lastReq = $ci->Members->get_last_support_req($uid);
    return $lastReq ? $lastReq : '';
}

    static function checkSubscription($id = false) {
		$id = $id ? $id : helpers::user_id();
        $subscription = false;
    	$ci =& get_instance(); 
		$ci->load->model('Members');
		$latestPackage = $ci->Members->get_members_higher_package($id);
		if($latestPackage) {
			$today = Helpers::date();
			$date = new DateTime($latestPackage['purchase_date']);
          	$date->modify('+1 month');

			$daysDiff = Helpers::daysDifferencesign($today, $date->format('Y-m-d H:i:s'));
        	if($daysDiff > 0) {
        		$subscription = true;
        	}
		}
		return $subscription;

    }
    static function get_all_buy_packages($userid){
    	$ci =& get_instance(); 

    	$ci->load->model('Members');
		$getAllPackages = $ci->Members->get_user_all_packages($userid);
		if($getAllPackages){
			return $getAllPackages;
		}else{
			return false;
		}
    }
    static function check_booktiming($user_id,$package_id){
    	$ci =& get_instance(); 
    	$ci->load->model('Members');
    	$res = $ci->Members->check_status($user_id,$package_id);
		return $res;

    }

	static function setPercenatgeByNumber($value){
		if($value == 0.01){
		    $percenatge = 1;
		    
		    }elseif($value == 0.02){
			$percenatge = 2;
		}
		    elseif($value == 0.03){
			$percenatge = 3;
		}
		elseif($value == 0.04){
			$percenatge = 4;
		}
		elseif($value == 0.05){
			$percenatge = 5;
		}
		elseif($value == 0.06){
			$percenatge = 6;
		}
		elseif($value == 0.07){
			$percenatge = 7;
		}
		elseif($value == 0.08){
			$percenatge = 8;
		}
		elseif($value == 0.09){
			$percenatge = 9;
		}
		
		elseif($value == 0.1){
			$percenatge = 10;
		}elseif($value == 0.2){
	$percenatge = 20;
		}elseif($value == 0.3){
	$percenatge = 30;
		}elseif($value == 0.4){
	$percenatge = 40;
		}elseif($value == 0.5){
	$percenatge = 50;
		}elseif($value == 0.6){
	$percenatge = 60;
		}elseif($value == 0.7){
	$percenatge = 70;
		}elseif($value == 0.8){
	$percenatge = 80;
		}elseif($value == 0.9){
	$percenatge = 90;
		}elseif($value == 1){
	$percenatge = 100;
		}else{
		$percenatge = substr($value, 2);
		}
		return $percenatge;
	}
}


