<?php



namespace App\Controllers;

use App\Models\User_model;

use App\Models\Dashboard_model;

use App\Models\Common_model;

use App\Models\Member_credits_model;

use App\Models\Packages_and_pricing_model;

use App\Models\Credits_usage_tracking_model;

use App\Models\Email_template_model;

use App\Models\Variable_model;

use App\Models\Rule_model;

use App\Models\Cart_token_model;

use App\Models\Zipcode_model;

use App\Models\Transaction_model;

use App\Models\Country_model;
use App\Models\Member_model;
use DateTime;


class Admin_controller extends BaseController

{

	public $session;

	public function __construct()

	{

		$this->session = session();

		$this->UserModel = new User_model();

		$this->dModel = new Dashboard_model();

		$this->cModel = new Common_model();

		$this->creditsModel = new Member_credits_model();

		$this->PackagesModel = new Packages_and_pricing_model();

		$this->CreditsUsageTrackingModel = new Credits_usage_tracking_model();

		$this->MailModel = new Email_template_model();

		$this->VariableModel = new Variable_model();

		$this->RuleModel = new Rule_model();

		$this->Cart_token_model = new Cart_token_model();

		$this->ZipcodeModel = new Zipcode_model();

		$this->TransactionModel = new Transaction_model();

		$this->CountryModel = new Country_model();

		$this->MemberModel = new Member_model();

		helper(['form', 'url']);

	}

    public function index()

    {

		$data=[];

		//$database = \Config\Database::connect();

		if($this->request->getmethod() == 'post')

		{

			$email = $this->request->getVar('email');
			//echo $email; die();
			$password = $this->request->getVar('password');
			$userdata = $this->UserModel->verifyEmail($email);
			//print_r($userdata); die();

			if($userdata)

			{
				if($userdata['is_active'] == 0)
				{
					$this->session->setTempdata('error','User id or password is invalid',3);
					$this->session->setTempdata('A_email',$this->request->getVar('email'),3);
					$this->session->setTempdata('A_password',$this->request->getVar('password'),3);
					return redirect()->to(base_url()."admin");	
				}

				if (password_verify($password, $userdata['password'])) 

				{

					

					$this->session->set('logged_admin_user',$userdata['id']);

					return redirect()->to(base_url().'admin_home');

				}

				else{

					$this->session->setTempdata('error','User id or password is invalid',3);
					$this->session->setTempdata('A_email',$this->request->getVar('email'),3);
					$this->session->setTempdata('A_password',$this->request->getVar('password'),3);
					return redirect()->to(base_url()."admin");

				}

			}else

			{

			  $this->session->setTempdata('error','User id or password is invalid',3);
			  $this->session->setTempdata('A_email',$this->request->getVar('email'),3);
			  $this->session->setTempdata('A_password',$this->request->getVar('password'),3);
			  return redirect()->to(base_url()."admin");				  

			}

		}

		return view('admin_login');

    }





	



	

	public function admin_logout()

	{

		session()->remove('logged_admin_user');
        if(!session()->get('logged_user'))
		{
			session()->destroy();
		}
		return redirect()->to(base_url()."admin");

	}



	public function users_list()

	{

		

		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		$data['userList'] =  $this->UserModel->where('users.id != ',session()->get('logged_admin_user') )->findAll();

		echo view('layout/header',$userdata);

		echo view('users_list',$data);

		echo view('layout/footer');

	}





	public function user_edit($user_id = null , $check = null)

	{



		if($this->request->getmethod() == 'post')

		{

				//update user details
				if($this->request->getVar('country') == 'Canada'){ $state = $this->request->getVar('state_canada'); }else{ $state = $this->request->getVar('state');}
				$UserData = $this->request->getVar();
				unset($UserData['state']);
				unset($UserData['state_canada']);
				$UserData['state'] = $state;
				

				$user_id =  $this->request->getVar('id');

				$this->UserModel->where('id', $user_id )->set($UserData)->update();

				if ($this->request->getVar('profile_check') == 'profile_edit') {

					return redirect()->to(base_url()."admin_profile/".md5($user_id));

				}

				return redirect()->to(base_url()."users_list");

			

		}

		

		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		$zip = $this->ZipcodeModel->findAll();

		$output = '<option value="">Select Zipcode</option>';

		foreach($zip as $row)

		{

		$output .= '<option value="'.$row['id'].'">'.$row['code'].'</option>';

		}

		$data['zipcode'] = $output;

		$data['userList'] =  $this->UserModel ->select('users.* , zipcode.code as zipcode')

											->join('zipcode', 'users.pincode = zipcode.id', 'left')

											->where('md5(users.id)', $user_id )

											->find();



											

		if ($check != null) {

			$data['check'] = 'profile_edit';

		}else{

		$data['check'] = '';

		}

		$data['country'] = $this->CountryModel->findAll();
		//print_r($data);die();

		echo view('layout/header',$userdata);

		echo view('user_form',$data);

		echo view('layout/footer');

		

	}



	public function user_add()

	{

		if($this->request->getmethod() == 'post')

		{
			$check_if_email_exist =  $this->UserModel->where('email',$this->request->getVar('email'))->find();
			if($check_if_email_exist)
			{
				return redirect()->to(base_url()."users_list");

			}else{

			$password = '';

			$characters = array_merge(range('A','Z'), range('a','z'), range('0','9'), array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '='));

			for($i = 0; $i < 8; $i++) {

			$password .= $characters[array_rand($characters)];

			}

				//insert member details

				if($this->request->getVar('country') == 'Canada'){ $state = $this->request->getVar('state_canada'); }else{ $state = $this->request->getVar('state');}
				$UserData = $this->request->getVar();
				unset($UserData['state']);
				unset($UserData['state_canada']);
				$UserData['state'] = $state;

				$UserData['password'] = $password; 

				$userdata = $this->UserModel->save($UserData);

				if ($userdata) 

				{

					$sendmail_controller = new Sendmail_controller();

					$get_data = $sendmail_controller->index($this->request->getVar('email') , $password , 3 );
 

					return redirect()->to(base_url()."users_list"); 

				}

		}

		}else{

		



		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		$zip = $this->ZipcodeModel->findAll();

		$output = '<option value="">Select Zipcode</option>';

		foreach($zip as $row)

		{

		$output .= '<option value="'.$row['id'].'">'.$row['code'].'</option>';

		}

		$data['zipcode'] = $output;

		$data['check']= null;

		$data['country'] = $this->CountryModel->findAll();

		echo view('layout/header',$userdata);

		echo view('user_form',$data);

		echo view('layout/footer');

		}

		

		

		

	}



	public function user_deactivate($id = null)

	{

		$this->UserModel->where('md5(id)', $id )->set(array( 'is_active' => 0))->update();

		return redirect()->to(base_url()."users_list");

	}	



	public function user_activate($id = null)

	{

		$this->UserModel->where('md5(id)', $id )->set(array( 'is_active' => 1))->update();

		return redirect()->to(base_url()."users_list");

	}





	public function admin_profile($user_id = null)

	{

		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		

		$data['userList'] =  $this->UserModel->select('users.* , zipcode.code as zipcode')

		                                      ->join('zipcode', 'users.pincode = zipcode.id', 'left')

											 ->where('md5(users.id)', $user_id )

											 ->find();

		

		// print_r($data);die();

		echo view('layout/header',$userdata);

		echo view('profile',$data);

		echo view('layout/footer');

		

	}



	public function profilepic_insert()

	{

        

		if($this->request->getmethod() == 'post')

		{

			$path = ROOTPATH ."/public/assets/images/users";

			if($this->request->getFile('profile'))

			{

				$img = $this->request->getFile('profile');

				if ($img->isValid()  && ! $img->hasMoved())

				{    

					//$newName = $img->getRandomName();

					$f_type=$_FILES['profile']['name'];

					$data['profile'] = $f_type;

					$this->UserModel->where('id', $this->request->getVar('id') )->set($data)->update();

					$img->move($path, $f_type);

					return redirect()->to(base_url()."admin_profile/".md5($this->request->getVar('id')));

				}

				else

				{

					return redirect()->to(base_url()."admin_profile/".md5($this->request->getVar('id')));

				}

			}

			else

			{

				return redirect()->to(base_url()."admin_profile/".md5($this->request->getVar('id')));

			}

		}

		

	}



	public function get_pack_list()
	{
		if($this->request->getmethod() == 'get')
		{
			$data['data'] =  $this->PackagesModel->findAll();
			$data['OnePackValue'] = $this->RuleModel->where('rule_key',14)->find();
			echo json_encode($data);
		}
		else
		{
			$data['data'] = $this->PackagesModel->where('id',$this->request->getVar('id'))->find();
			$data['OnePackValue'] = $this->RuleModel->where('rule_key',14)->find();
			echo json_encode($data);
		}
	}





	public function credits_pack_list()

	{

		

		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		$data['PackageData'] =  $this->PackagesModel->findAll();

		echo view('layout/header',$userdata);

		echo view('credits_pack_list',$data);

		echo view('layout/footer');

	}





	public function credits_pack_edit($pack_id = null)

	{



		if($this->request->getmethod() == 'post')

		{

				//update member details

				

				$PackData = $this->request->getVar();

				$pack_id =  $this->request->getVar('id');

				$this->PackagesModel->where('id', $pack_id )->set($PackData)->update();

				return redirect()->to(base_url()."credits_pack_list");

			

		}



		

		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		

		$data['PackageData'] =  $this->PackagesModel->where('md5(id)', $pack_id )->find();

		

		//print_r($data);die();

		echo view('layout/header',$userdata);

		echo view('credits_pack_form',$data);

		echo view('layout/footer');

		

	}



	public function credits_pack_add()

	{



		if($this->request->getmethod() == 'post')

		{
				//insert member details

				$PackData = $this->request->getVar();

				$this->PackagesModel->save($PackData);

				return redirect()->to(base_url()."credits_pack_list");

			

		}

		

		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		echo view('layout/header',$userdata);

		echo view('credits_pack_form');

		echo view('layout/footer');

		

	}



	public function user_password_change()

	{



		if($this->request->getmethod() == 'post')

		{

				//insert member details

				$UserData = $this->request->getVar();

				$old_password = $this->request->getVar('old_password');

				$data = $this->UserModel->where('id', $this->request->getVar('id') )->find();

				if (password_verify($old_password ,$data[0]['password'])) 

				{

					$user_data = $this->UserModel->where('id', $this->request->getVar('id') )->set($UserData)->update();

					if ($user_data) 

					{

						$sendmail_controller = new Sendmail_controller();

						$get_data = $sendmail_controller->index($this->request->getVar('email') , null , 4 );

						$this->session->setTempdata('mail_success',"Password changed successfully",3);

						return redirect()->to(base_url()."admin");

					}

					else

					{

						$this->session->setTempdata('error',"Entered wrong old password",3);

						return redirect()->to(base_url()."user_password_change");

					}

				} 

				else 

				{

					$this->session->setTempdata('error',"Entered wrong old password",3);

					return redirect()->to(base_url()."user_password_change");

				}			

		}

		

		$userdata['userdata']=$this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

		echo view('layout/header',$userdata);

		echo view('users_password',$userdata);

		echo view('layout/footer');

		

	}





	public function transactions_list($member_id =null)
	{
		if($member_id == null)
		{
			$userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));
			
			$data['creditsData'] =   $this->TransactionModel->select('transactions.* , member.name as member_name ')
													   ->join('member', 'transactions.member_id = member.id', 'left')
													   ->orderBy('transactions.created_at' , 'desc')
													   ->findAll();
		  // echo '<pre>';   echo print_r($data['creditsData']); '</pre>'; die;
			echo view('layout/header',$userdata);
			echo view('transactions_list',$data);
			echo view('layout/footer');
		
		}else{
		
			// $userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));
			
			$creditsData =   $this->TransactionModel->select('transactions.* , member.name as member_name ')
												->join('member', 'transactions.member_id = member.id', 'left')
												->orderBy('transactions.created_at' , 'desc')
			                                    ->where('md5(transactions.member_id)', $member_id )
			                                    ->findAll();
			
			$output = '<div class="table-responsive"><table class="table mb-0"><thead class="thead-light"><tr> <th>Order Id</th><th>Order Date</th><th>Transaction Id</th><th>Cost</th><th>Purchased by</th><th>Status</th></tr></thead><tbody>';
			foreach ($creditsData as $row) { 
			$date = new DateTime($row['created_at']);   
			 if($row['status'] == 'Success'){
				$style = 'style="color:green;"';
				$cost =  json_decode($row['transaction'] , true)['payment']['amount_money']['amount'] / 100;
				$cost = number_format($cost, 2, '.', '');
			  }else{$cost=''; $style = 'style="color:red;"';}
             $output .='<tr><td>'.$row['order_id'].'</td><td>'.$date->format('M d , Y').'</td><td>'.$row['transaction_id'].'</td><td>'.$cost.'</td></td><td>'.$row['member_name'].'</td></td><td '.$style.'>'.$row['status'].'</td></tr>';
			}  
		    echo  $output .= '</tbody></table></div> ';
		}

	}


	public function order_details()
	{
		
		$member_id = $this->request->getVar('member_id');
		$order_id = $this->request->getVar('order_id');
			$creditsData =   $this->creditsModel->select('member_credits.* , member.name as member_name ')
												->join('member', 'member_credits.member_id = member.id', 'left')
												->orderBy('member_credits.created_at' , 'desc')
			                                    ->where('member_credits.member_id', $member_id )
												->where('member_credits.order_id', $order_id )
			                                    ->findAll();
		 // echo 'member_id ='.$member_id; echo 'order_id ='.$order_id; echo '<pre>';   echo print_r($creditsData); '</pre>'; die();
			$output = '<div class="table-responsive"><table class="table mb-0"><thead class="thead-light"><tr> <th>Order Id</th><th>Package Name</th><th>Cost</th><th>Total Amount</th><th>Credits</th><th>Payment Status</th></tr></thead><tbody>';
			foreach ($creditsData as $row) { 
			if($row['is_active'] == 1 ){ $status = 'Success';}else{ $status = 'Failed';}
			$cost = number_format($row['cost'], 2, '.', '');
			$cost_with_tax = number_format($row['cost_with_tax'], 2, '.', '');
             $output .='<tr><td>'.$row['order_id'].'</td><td>'.$row['package_name'].'</td><td>'.$cost.'</td></td><td>'.$cost_with_tax.'</td></td><td>'.$row['credit_points'].'</td><td>'.$status.'</td></tr>';
			}  
		    echo  $output .= '</tbody></table></div> ';
	

	}



	public function user_forgot_password()

    {

      if($this->request->getmethod() == 'get')

      {

		$this->session->setTempdata('user',"user",3);

         return view('forgot_password.php');

      }

      else if($this->request->getmethod() == 'post')

      {         

  

        $email = $this->request->getVar('email');

        $user_data = $this->UserModel->where('email', $email)->find();

        if ($user_data) 

        {

          $otp = rand(1000 , 9999);

		  $sendmail_controller = new Sendmail_controller();

          $sendmail_controller->index($this->request->getVar('email') , $otp , 2 ); 

          $data['status'] = 'success';

          $data['otp'] = $otp;

          echo json_encode($data);

        } 

        else 

        {

          $data['status'] = 'failed';

          echo json_encode($data);

        }

         

      }

    }



	public function template_list()

    {

		if($this->request->getmethod() == 'get')

		{

			$userdata['template_data'] = $this->MailModel->findAll();

			$userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

			echo view('layout/header',$userdata);

			echo view('email_template_list.php');

			echo view('layout/footer');

		}

	}



	public function email_temp()

    {

		if($this->request->getmethod() == 'get')

		{

			echo view('email.template.php');

		}

		else if($this->request->getmethod() == 'post')

		{      

		  $data['name'] = $this->request->getVar('name');

		  $data['to'] = $this->request->getVar('to');

		  $data['subject'] = $this->request->getVar('subject');

		  $data['html'] = $this->request->getVar('code');

		  $data['text'] = $this->request->getVar('text');

		//   $data['type'] = 1;

		  $mail_temp = $this->MailModel->save($data);

		  if ($mail_temp) 

		  echo true;

		  else

		  echo false;

		}

	}



	public function edit_email_temp($temp_id = null)

    {

		if($this->request->getmethod() == 'get')

		{      

		  $temp_data = $this->MailModel->where('md5(id)' , $temp_id)->find();

		  if ($temp_data) 

				{

					$data['dropdownData'] = $this->VariableModel->where('type' , $temp_data[0]['type'])->findAll();

					$data['id'] = $temp_data[0]['id'];

					$data['code'] = $temp_data[0]['html'];

					$data['name'] = $temp_data[0]['name'];

					$data['subject'] = $temp_data[0]['subject'];

					$data['to'] = $temp_data[0]['to'];

					$userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

					echo view('layout/header',$userdata);

					echo view("email.template.php" , $data);

					echo view('layout/footer');

				}

		}

		else if($this->request->getmethod() == 'post')

		{

			$data['name'] = $this->request->getVar('name');

		    $data['to'] = $this->request->getVar('to');

		    $data['subject'] = $this->request->getVar('subject');

		    $data['html'] = $this->request->getVar('code');

		    $data['text'] = $this->request->getVar('text');

			$mail_temp = $this->MailModel->where('id', $this->request->getVar('id') )->set($data)->update();

		    if ($mail_temp) 

		    echo true;

		    else

		    echo false;

		}	

	}



	public function mail_temp_deactivate($id = null)

	{

		$this->MailModel->where('md5(id)', $id )->set(array( 'is_active' => 0))->update();

		return redirect()->to(base_url()."template_list");

	}	



	public function mail_temp_activate($id = null)

	{

		$this->MailModel->where('md5(id)', $id )->set(array( 'is_active' => 1))->update();

		return redirect()->to(base_url()."template_list");

	}



	public function rule()

    {

		if($this->request->getmethod() == 'get')

		{			

			$userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

			$ruledata['rule_data'] = $this->RuleModel->findAll();

			echo view('layout/header',$userdata);

			echo view('rule.php',$ruledata);

			echo view('layout/footer');

		}

		else if($this->request->getmethod() == 'post')

		{      

			$id = $this->request->getVar('id');

			$data['data'] = $this->request->getVar('rule_name');

			$data['value'] = $this->request->getVar('value');

			$updatedata = $this->RuleModel->where('id', $id )->set($data)->update();

			if($updatedata)

			echo true;

			else

			echo false;

		}

	}



	public function booked_slot()

    {

		if($this->request->getmethod() == 'get')

		{			

			$userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

			// $ruledata['rule_data'] = $this->RuleModel->findAll();

			echo view('layout/header',$userdata);

			echo view('booked_slot.php');

			echo view('layout/footer');

		}

		else if($this->request->getmethod() == 'post')

		{  

			echo 'hi';

		}

	}



	public function manage_availability()

    {

		if($this->request->getmethod() == 'get')

		{			

			$userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));

			// $ruledata['rule_data'] = $this->RuleModel->findAll();

			echo view('layout/header',$userdata);

			echo view('manage_availability.php');

			echo view('layout/footer');

		}

		else if($this->request->getmethod() == 'post')

		{  

			echo 'hi';

		}

	}

	public function update_creditsModel($con)
	{
		$data['total'] = $this->request->getVar('total');
		$reason = $this->request->getVar('reason');
		$id = $this->request->getVar('id');
		if($con == 'del')
		$upt_data = $this->creditsModel->where('id', $id )->set(array( 'is_active' => 0, 'reason'=> $reason ))->update();
		else
		$upt_data = $this->creditsModel->where('id', $id )->set(array( 'is_active' => 1, 'reason'=> $reason ))->update();
		echo $upt_data ? true : false;
	}

	public function add_creditsModel()
	{
		$requet_data = $this->request->getVar();
		//print_r($requet_data);die;
		$temp_data = $this->PackagesModel->where('id' , $requet_data['package_name'])->find();
		$credit_pack_expiry_duration = $this->RuleModel->select('value')->where('rule_key', 1 )->get()->getRow()->value;
		$today = date("Y-m-d");
		$days = "+".$credit_pack_expiry_duration." days";
		$count = $this->request->getVar('count');

		if(isset($count))
		 {
			  if($requet_data['add_or_sub'] == 'sub')
			    { 
			    $data['order_id'] =  'EGF'.rand(10,100).rand(10,100).rand(10,100) . 'R';
				}else{
				$data['order_id'] =  'EGF'.rand(10,100).rand(10,100).rand(10,100) . 'A';
				}

            for ($i=0; $i < $count ; $i++) 
				{ 
					
					$data['updated_by'] = session()->get('logged_admin_user');
					$data['credit_points'] = $temp_data[0]['credit'];
					$data['package_name'] = $temp_data[0]['package_name'];
					$data['package_type'] = $temp_data[0]['package_type'];
					$data['expiring_date'] = date('Y-m-d', strtotime($days, strtotime($today)));
					$data['cost'] = $temp_data[0]['cost'];
					$data['member_id'] = $requet_data['member_id'];
					$data['method'] = $requet_data['method'];
					$data['remark'] = $requet_data['remarks'];
					if($requet_data['add_or_sub'] == 'sub')
					{  
						$data['running_balance'] = 0;
						$reduse_points = $this->RedusePoints($requet_data['member_id'],$temp_data[0]['credit']);
						if($reduse_points)
						{
							$this->creditsModel->save($data);
						}
					}else{
						$data['running_balance'] = $temp_data[0]['credit'];
						$this->creditsModel->save($data);
					}
					
				}
                
		 }
		 else
		 {
					//$data2 = $this->request->getVar();
					if($requet_data['add_or_sub'] == 'sub')
					{ 
					$data2['order_id'] =  'EGF'.rand(10,100).rand(10,100).rand(10,100) . 'R';
					}else{
					$data2['order_id'] =  'EGF'.rand(10,100).rand(10,100).rand(10,100) . 'A';
					}
					$data2['expiring_date'] = date('Y-m-d', strtotime($days, strtotime($today)));
					$data2['member_id'] = $requet_data['member_id'];
					$data2['method'] = $requet_data['method'];
					$data2['remark'] = $requet_data['remarks'];
					$data2['credit_points'] = $requet_data['credit_points'];
					$data2['cost'] = $requet_data['cost'];
					$data2['package_name'] = $requet_data['package_name'];
					$data2['updated_by'] = session()->get('logged_admin_user');
					if($requet_data['add_or_sub'] == 'sub')
					{  
						
						$data2['running_balance'] = 0;
						$reduse_points = $this->RedusePoints($requet_data['member_id'],$requet_data['credit_points']);
						if($reduse_points)
						{
							$this->creditsModel->save($data2);
						}
					}else{
						$data2['running_balance'] = $requet_data['credit_points'];
						$this->creditsModel->save($data2);
					}
					
		 	     
		 }	

	
		
		return redirect()->to(base_url()."view_credit_details/".md5((int)$requet_data['member_id']));
	}


	 function RedusePoints($member_id,$needed_points) 
	{
   
		
		$CreditBalanceSum = $this->creditsModel->selectSum('running_balance')
									->where('member_id',$member_id)
									->where('is_active',1)
									->get()->getRow()->running_balance;
		
		if($CreditBalanceSum > $needed_points)
		{
	
			$creditsData = $this->creditsModel->where('member_id',$member_id)->where('is_active',1)->findAll();
			
			foreach ($creditsData as $creditsDataindex => $creditsDataValue) {
	
				if($creditsDataValue['expiring_date'] > date("Y-m-d"))
				{
					$temp_needed_points = $needed_points;
					if($creditsDataValue['running_balance'] != 0 && $needed_points > 0)
					{

						$needed_points = ($needed_points - $creditsDataValue['running_balance']);
						if($needed_points < 0 ){ 
	
							$running_balance =    $creditsDataValue['running_balance'] - $temp_needed_points;
							$this->update_credit_package_data($creditsDataValue['id'] ,  array( 'running_balance'=>$running_balance , 'used_points'=> $creditsDataValue['used_points'] + $creditsDataValue['running_balance'] - $running_balance));
	
						 }else { $running_balance = 0; 
	
							$this->update_credit_package_data($creditsDataValue['id'] ,  array( 'running_balance'=>$running_balance , 'used_points'=> $creditsDataValue['used_points'] + $creditsDataValue['running_balance'] - $running_balance));

						}
					
					}else{
					}
				}else{
				}
			}
			
			return true;
	
		}else{
			return false;
		}
	}

	 function update_credit_package_data($id , $array)
	{
		$this->creditsModel->where('id', $id )->set($array)->update();
	}


public function view_credit_details($member_id)
	{
		$userdata['userdata'] = $this->dModel->getLoggedInUserData(session()->get('logged_admin_user'));
		$fname = $this->MemberModel->select('name')->where('md5(id)', $member_id )->get()->getRow()->name;
		$lname = $this->MemberModel->select('last_name')->where('md5(id)', $member_id )->get()->getRow()->last_name;
		$id = $this->MemberModel->select('id')->where('md5(id)', $member_id )->get()->getRow()->id;
		$creditsData = $this->creditsModel->where('md5(member_id)',$member_id)->orderBy('id' , 'ASC')->findAll();
		$data['id'] = $id;
		$data['fname'] = $fname;
		$data['lname'] = $lname;
		$data['credit_data'] = [];
		$data['avaiable_credit'] = 0;
		
	    foreach ($creditsData as $creditsDataindex => $creditsDataValue) 
		{
            if($creditsDataValue['running_balance'] + $creditsDataValue['used_points'] == 0)
			{
				$data['avaiable_credit'] = $data['avaiable_credit'] - $creditsDataValue['credit_points'];
				$creditsDataValue['avaiable_credit'] = $data['avaiable_credit'];
				array_push($data['credit_data'] , $creditsDataValue);
			}
			else
			{
				$data['avaiable_credit'] = $data['avaiable_credit'] + $creditsDataValue['credit_points'];
				$creditsDataValue['avaiable_credit'] = $data['avaiable_credit'];
				array_push($data['credit_data'] , $creditsDataValue);
			}
	    }
		// echo '<pre>';
		// print_r($data);
		// echo '</pre>';die;
		    echo view('layout/header',$userdata);
			echo view('credit_points_list.php',$data);
			echo view('layout/footer');
	}


	// public function continue_shopping($param)

    // {  

	// 	$token_exist  =  $this->Wp_php_token_model->where('token', $param )->find();

	// 	if ($token_exist) 

	// 	  return $token_exist[0]['token'];

	// 	else

	// 	  return false;

	// }



	// -----------------------------------------------

}

