<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Profile_Controller extends MY_Controller
{
	Public function __construct(){
		parent::__construct();
		$this->load->model("profile_model","profile");
		$this->profileid = $this->session->userdata('profileid');
		$this->ud = $this->common->getsData("user",array("profileid"=>$this->profileid));
		$this->is_logged_in();
	}

	function is_logged_in()
	{
		//echo "<pre>"; print_r($this->session->all_userdata());die;
		$is_user_logged_in = $this->session->userdata('is_user_logged_in');
		//echo $is_user_logged_in;
		if(!isset($is_user_logged_in) || $is_user_logged_in != true)
		{
			//$this->session->set_userdata(array("current"=>uri_string()));
			redirect(base_url("user-login"));
		}else{
			if($this->session->userdata("user_login_type")=="guest_user"){
				redirect(base_url("user-login"));
			}
		}
	}
	public function compressImage($source, $destination, $quality) { 
	    // Get image info 
	    $imgInfo = getimagesize($source); 
	    $mime = $imgInfo['mime']; 
	     
	    // Create a new image from file 
	    switch($mime){ 
	        case 'image/jpeg': 
	            $image = imagecreatefromjpeg($source); 
	            break; 
	        case 'image/png': 
	            $image = imagecreatefrompng($source); 
	            break; 
	        case 'image/gif': 
	            $image = imagecreatefromgif($source); 
	            break; 
	        case 'image/webp': 
	            $image = 0; 
	            break; 
	        case 'image/svg': 
	            $image = 0; 
	            break; 
	        default: 
	            $image = imagecreatefromjpeg($source); 
	    } 
	     
	    if($image==0){
	    	return 0;
	    }else{
		    // Save image 
		    imagejpeg($image, $destination, $quality); 
		     
		    // Return compressed image 
		    return $destination; 
		}
	}
	public function do_upload($file_name, $path)

    {

        $config['upload_path']   = $path;

        $config['allowed_types'] = 'jpeg|jpg|png|JPEG|JPG|PNG|gif|GIF|webp|WEBP';

        $config['encrypt_name']  = true;



        $this->load->library('upload', $config);



        if ( ! $this->upload->do_upload($file_name))

        {

                $error = array('error' => $this->upload->display_errors());

                return $error;

                //$this->load->view('upload_form', $error);

        }

        else

        {

                $data = array('upload_data' => $this->upload->data());



                return $data;

        }

    }

	public function updateAccontInformation()
	{
		// $_POST['plain_password'] = $_POST['password'];
		// $_POST['password'] = md5($_POST['password']);
		if(isset($_POST['newsletter']) && $_POST['newsletter']==1){
			$_POST['newsletter'] = 1;
		}else{
			$_POST['newsletter'] = 0;
		}
		$userdata = $this->common->getField("user",$_POST);
		//echo "<pre>";print_r($userdata);die;
		$res = $this->common->updateData("user",$userdata,array("profileid"=>$this->profileid));
		if($res){
			$this->session->set_flashdata("message","Profile updated successfully");
		}else{
			$this->session->set_flashdata("emessage","Profile Updated Faild");
		}
		redirect(base_url("user-profile"));
	}
	public function updateProfilePhoto($value='')
	{
		if(isset($_FILES['user_photo']['name']) && $_FILES['user_photo']['name'] != ""){
			$imagename = rand().'-'.str_replace(" ","-",$_FILES['user_photo']['name']);
			$imagetmpname = $_FILES['user_photo']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['user_photo'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['user_photo'] = $uploadpath;
				}
			}
           	if(isset($_POST['user_photo']) && $_POST['user_photo']!=''){ 
	    		$res = $this->common->updateData("user",array('user_photo'=>$_POST['user_photo']),array("profileid"=>$this->profileid));
				$this->session->set_flashdata("message","Profile photo updated successfully");
            }
        }
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function addBillingInformation()
	{
		if(isset($_POST['isDefault']) && $_POST['isDefault']==1){
			$this->common->updateData("user_address",array('isDefault'=>0),array("profileid"=>$this->profileid));
			$_POST['isDefault'] = 1;
		}else{
			$_POST['isDefault'] = 0;
		}
		$useraddress = $this->common->getData('user_address',array('profileid'=>$this->profileid));
        if(isset($useraddress) && $useraddress){
        }else{
            $_POST['isDefault'] = 1;
        }
		$_POST['profileid'] = $this->profileid;
		$addressdata = $this->common->getField("user_address",$_POST);
		$res = $this->common->insertData("user_address",$addressdata);
		if($res){
			$this->session->set_flashdata("message","Address Added Successfully");
		}else{
			$this->session->set_flashdata("emessage","Address Added Faild");

		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function updateBillingInformation()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		if(isset($_POST['isDefault']) && $_POST['isDefault']==1){
			$this->common->updateData("user_address",array('isDefault'=>0),array("profileid"=>$this->profileid));
			$_POST['isDefault'] = 1;
		}else{
			$_POST['isDefault'] = 0;
		}
		$addressdata = $this->common->getField("user_address",$_POST);
		$this->common->updateData("user_address",$addressdata,array("profileid"=>$this->profileid,'id'=>$id));
		if($this->db->affected_rows()){
			$this->session->set_flashdata("message","Address Updated Successfully");
		}else{
			$this->session->set_flashdata("emessage","Address Update Faild");

		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function deleteAddress()
	{
		$res = $this->common->deleteData('user_address',array('id'=>$_GET['id']));
		redirect($_SERVER['HTTP_REFERER']);
	}

    public function addProductInWishlist()
    {
        $yes = $this->common->getsData('wishlist',array('profileid'=>$this->profileid,'productid'=>$_POST['productid']));
        if($yes){

        }else{
        	$this->common->insertData('wishlist',array('profileid'=>$this->profileid,'productid'=>$_POST['productid']));
        }
        $total = $this->common->getData('wishlist',array('profileid'=>$this->profileid));
        if($total){
        	echo $this->common->jsonEncode(array('count'=>count($total)));
        }else{
        	echo $this->common->jsonEncode(array('count'=>0));
        }
    }

    public function deleteProductFromWishlist()
    {
        $yes = $this->common->getsData('wishlist',array('profileid'=>$this->profileid,'productid'=>$_POST['productid']));
        if($yes){
        	$this->common->deleteData('wishlist',array('profileid'=>$this->profileid,'productid'=>$_POST['productid']));
        }
        $total = $this->common->getData('wishlist',array('profileid'=>$this->profileid));
        if($total){
        	echo $this->common->jsonEncode(array('count'=>count($total)));
        }else{
        	echo $this->common->jsonEncode(array('count'=>0));
        }
    }

    public function userReorder($value='')
    {
    	$this->load->model("cart/cart_model","kart");
    	$cart = $this->common->getData("cart_mapping",array("orderid"=>$_GET['orderid']),array(),array(),array("field"=>"cmid","by"=>"asc"));
    	if($cart){
    		foreach ($cart as $key => $value) {
    			$item['productid'] = $value['productid'];
    			$item['qty'] = $value['qty'];
    			$item['size'] = $value['size'];
    			$item['color'] = $value['color'];
    			$item['type'] = $value['product_type'];
    			$data = $this->kart->addProductInCart($item);
    			// if($data['found']==1){
    				
    			// 	redirect($_SERVER['HTTP_REFERER']);
    			// }
    		}
    	}
    	redirect(base_url('shopping-cart'));
    }

    public function redeemPointsAsCoupon()
    {
    	$user = $this->common->getsData("user",array("profileid"=>$this->profileid));
    	if($user['verify']==1){
	    	if(isset($_POST['reward']) && $_POST['reward']!=''){
	    		$reward = $this->common->getsData('reward_point',array('id'=>$_POST['reward']));
	    		if($reward){
	    			if($user['remain_point']>=$reward['point']){
		    			$post['profileid'] = $this->profileid;
		    			$post['email'] = $user['email'];
		    			$post['coupon_code'] = time().strtoupper($this->getRandomString(2));
		    			$post['coupon_type'] = 1;
		    			$post['coupon_amount'] = $reward['percent'];
		    			$post['coupon_quantity'] = 1;
		    			$post['cart_amount'] = 100;
		    			$post['coupon_current_date'] = date('Y-m-d H:i:s');
		    			$post['coupon_expiry_date'] = date('Y-m-d H:i:s',strtotime($post['coupon_current_date'].' +'.$reward['expire_days'].' days'));
		    			$res = $this->common->insertData('coupon',$post);
		    			if($res){
		    				$query = ('UPDATE  user SET `remain_point` =  remain_point-'.$reward['point'].', `withdraw_point` =  withdraw_point+'.$reward['point'].' WHERE `profileid` ="'.$this->profileid.'"');
			                $this->db->query($query);
			                $reason = "Redeem points";
			                $this->common->insertData('point_history',array('orderid'=>$_POST['reward'],'point'=>$reward['point'],'profileid'=>$this->profileid,'type'=>1,'reason'=>$reason,'date'=>date('Y-m-d H:i:s')));
			                $this->session->set_flashdata("message","Coupon successfully redeemed!");
		    			}else{
		    				$this->session->set_flashdata("emessage","Something went wrong.");
		    			}
		    		}else{
		    			$this->session->set_flashdata("emessage","Insufficient reward points.");
		    		}
	    		}else{
		    		$this->session->set_flashdata("emessage","Please select atleast one reedem plan");
		    	}
	    	}else{
	    		$this->session->set_flashdata("emessage","Please select atleast one reedem plan");
	    	}
	    }else{
    		$this->session->set_flashdata("emessage","Reward points will only be accumulated after you complete your email verification.");
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    function getRandomString($digits) { 
        $total_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
        $randomString = ''; 
            for ($i = 0; $i < $digits; $i++) { 
                $index = rand(0, strlen($total_characters) - 1); 
                $randomString .= $total_characters[$index]; 
            }
        return $randomString; 
    }

    public function buyUserPackage()
    {
    	$package_orderid = "BSI".strtotime(date('Y-m-d H:i:s'));
    	$this->session->set_userdata(array("package_orderid"=>$package_orderid));
    	if(isset($_POST['package']) && $_POST['package']==2){
    		$package = 2;
    		$amount = 500;
    		if($this->user_order_amount<500){
    			$amount = 500-$this->user_order_amount;
    		}else{
    			$this->session->set_flashdata("emessage","Gold Package Already Activated");
    			redirect(base_url('fast-track'));
    		}
    	}else{
    		$package = 1;
    		$amount = 200;
    		if($this->user_order_amount<200){
    			$amount = 200-$this->user_order_amount;
    		}else{
    			$this->session->set_flashdata("emessage","Silver Package Already Activated");
    			redirect(base_url('fast-track'));
    		}
    	}
    	$this->session->set_userdata(array("package"=>$package));
    	$this->session->set_userdata(array("amount"=>$amount));

    	$curlpost = 'email='.$this->ud['email'].'&name='.$this->ud['name'].'&redirect_url='.base_url('profile/hitPaySuccess').'&webhook='.base_url('common/hitPayWebhookPackage').'&amount='.$amount.'&currency=SGD&reference_number='.$package_orderid.'&send_email=true';
    	$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"https://api.hit-pay.com/v1/payment-requests");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$curlpost);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Requested-With: XMLHttpRequest','Content-Type: application/x-www-form-urlencoded','X-BUSINESS-API-KEY: '.hitpay_apikey));
        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $server_output = curl_exec ($ch);
        curl_close ($ch);
        $payres = json_decode($server_output,true);
        // echo "<pre>";
        // print_r ($payres);
        // echo "</pre>"; die;
        $this->session->set_userdata('paymentid',$payres['id']);
        redirect($payres['url']);
    }

    public function hitPaySuccess()
    {
        if(isset($_GET['status']) && $_GET['status']=='failed'){
            $this->session->set_flashdata('emessage',"Sorry your payment is unsuccessful. Please try again.");
            redirect(base_url('fast-track'));
        }else if(isset($_GET['status']) && $_GET['status']=='expired'){
            $this->session->set_flashdata('emessage',"Sorry your payment is unsuccessful. Please try again.");
            redirect(base_url('fast-track'));
        }else if(isset($_GET['status']) && $_GET['status']=='canceled'){
            $this->session->set_flashdata('emessage',"Sorry your payment is canceled. Please try again.");
            redirect(base_url('fast-track'));
        }else if(isset($_GET['reference']) && $_GET['reference']!=''){
            if($_GET['status']=='completed'){
                $status = "Complete";
            }else{
                $status = "Pending";
            }
            $this->paymentDone($_GET['reference'],$status);
        }else{
            $this->session->set_flashdata('emessage',"Sorry your payment is unsuccessful. Please try again.");
            redirect(base_url('fast-track'));
        }
    }

    public function paymentDone($txnid='',$pstatus='Pending')
    {
    	$order['package']= $this->session->userdata('package');
    	$order['orderid']= $this->session->userdata('package_orderid');
    	$order['amount']= $this->session->userdata('amount');
        $order['payment_status'] = $pstatus;
        $order['txn_id'] = $txnid;
        $order['payment_id'] = '';
        $order['profileid'] = $this->profileid;
        $res = $this->common->updateData('user',array('package'=>$order['package']),array('profileid'=>$this->profileid));
        $this->common->insertData('user_package_order',$order);
        if($order['package']==1){
        	$pkg = 'Silver';
        }else{
        	$pkg = 'Gold';
        }
        $this->session->set_flashdata('message',"Thank you! your ".$pkg." package is activated now.");
        redirect(base_url('fast-track'));
    }

}