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

class Front extends MY_Front_Controller {

	Public function __construct(){
        parent::__construct(); 
        $this->load->helper('text');

    }

	public function index()
	{
		$data['slider'] = $this->common->getData("slider",array(),array(),array('field'=>'item_order','by'=>'asc'));
        $data['btools'] = $this->common->getData("partners",array(),array(),array('field'=>'item_order','by'=>'asc'));
        $data['category'] = $this->common->getData("category",array('isFeatured'=>1,'show'=>1),array(),array('field'=>'item_order','by'=>'asc'));
        $data['products'] = $this->front->getProducts(array('feat_prod'=>1));
        $data['recipes'] = $this->common->getData("recipe",array('isFeatured'=>1),array(),array('field'=>'item_order','by'=>'asc'));
        $data['news'] = $this->common->getData("post",array('isFeatured'=>1,'type'=>0),array(),array('field'=>'id','by'=>'desc'));
        $data['event'] = $this->common->getData("post",array('isFeatured'=>1,'type'=>1),array(),array('field'=>'id','by'=>'desc'));
		$this->loadHtml('index','Home Page',$data);
	}

    public function getCategoryListPage($cat='',$cid='')
    {
        $data['maincat'] = str_replace('-', ' ', $cat);
        $data['catimages'] = $this->common->getsData('category',array('c_id'=>$cid));
        $data['category']=$this->common->getData('category',array('parent'=>$cid));
        $this->loadHtml('category-list','product category list',$data);
    }
    public function getSubCategoryListPage($cat='',$scat='',$cid='')
    {
        $data['maincat'] = str_replace('-', ' ', $cat);
        $data['subcat'] = str_replace('-', ' ', $scat);
        $data['catimages'] = $this->common->getsData('category',array('c_id'=>$cid));
        $data['category']=$this->common->getData('category',array('parent'=>$cid));
        $this->loadHtml('category-list','product category list',$data);
    }

	public function getAllProducts(){
		$where = array();
        if(isset($_GET['search']) && $_GET['search']!=''){
          $data['category_title'] = array("category"=>$_GET['search']);
          $where['keyword']=$_GET['search'];
        }else if(isset($_GET['feat_prod']) && $_GET['feat_prod']==1){
          $data['category_title'] = array("category"=>'Featured Products');
          $where['feat_prod']=1;
        }else if(isset($_GET['best_selling']) && $_GET['best_selling']==1){
          $data['category_title'] = array("category"=>'SUNTEXNOLOGY Special Sale');
          $where['best_selling']=1;
        }else if(isset($_GET['last_products']) && $_GET['last_products']==1){
          $data['category_title'] = array("category"=>'Last Visited Products');
          $where['last_products']=1;
        }else if(isset($_GET['search']) && $_GET['search']!=''){
          $data['category_title'] = array("category"=>$_GET['search']);
          $where['keyword']=$_GET['search'];
        }else{
		  $data['category_title'] = array("category"=>"All Products");
        }
		if(isset($_GET['price']) && $_GET['price']!=''){
			$where['price']=$_GET['price'];
		}
        if(isset($_GET['discount']) && $_GET['discount']!=''){
            $where['discount']=$_GET['discount'];
        }
        if(isset($_GET['order_by']) && $_GET['order_by']!=''){
            $where['order_by']=$_GET['order_by'];
        }
		$data['products'] = $this->front->getProducts($where,12);
        // echo $this->db->last_query();die;
		$data['links'] = "products";
        
		$this->loadHtml('shop','Shop Page',$data);
	}


    public function productsIframe()
    {
        $where = array();
        $data['category_title'] = array("category"=>"All Products");
        if(isset($_GET['price']) && $_GET['price']!=''){
            $where['price']=$_GET['price'];
        }
        $data['products'] = $this->front->getProducts($where);
        $data['links'] = "products/All Products/pr";
        $data['links'] = "products/all-products/pr";
        return $this->load->view('shop-iframe',$data);
       
    }

	public function shopPage($category_name='',$pr='',$offset='')
	{
		$where = array();
	    if(isset($_GET['catid']) && $_GET['catid']){
            $where['product_category']=$_GET['catid'];
            $data['category_title'] = $this->common->getsData('category',array('c_id'=>$_GET['catid']));
        }
        if(isset($_GET['search']) && $_GET['search']!=""){
            $where['keyword']=$_GET['search'];
        }

        if(isset($_GET['price']) && $_GET['price']!=''){
            $where['price']=$_GET['price'];
        }

		if(isset($_GET['discount']) && $_GET['discount']!=''){
			$where['discount']=$_GET['discount'];
		}

        if(isset($_GET['order_by']) && $_GET['order_by']!=''){
            $where['order_by']=$_GET['order_by'];
        }

        if(isset($_GET['brand']) && $_GET['brand']!=''){
            $where['brandid']=$_GET['brand'];
        }

        if(isset($_GET['sale']) && $_GET['sale']!=''){
            $where['sale']=$_GET['sale'];
        }

        if(isset($_GET['top']) && $_GET['top']!=''){
            $where['top']=$_GET['top'];
        }

        if(isset($_GET['new']) && $_GET['new']!=''){
            $where['new']=$_GET['new'];
        }

        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $offset = $_GET['per_page'];
        }

        $get = $_GET;
        $query = $_SERVER['QUERY_STRING'];
        if(isset($get)){
            if(isset($get['per_page'])){
                unset($get['per_page']);
            }
            $query = http_build_query($get);
        }
        $records = $this->front->record_count('products',$where);
        $config =  array(
            'page_query_string' => true,
            'base_url' => base_url('products') ,
            'per_page' =>9,
            'reuse_query_string' => true,
            'total_rows' => $records,
            'full_tag_open' => "<ul class='pagination justify-content-center align-items-center mt-md-5 mt-4 mb-4'>",
            'full_tag_close' => "</ul>",
            'first_tag_open' => '<li class="page-item">',
            'first_tag_close' => '</li>',
            'last_tag_open' => '<li class="page-item">',
            'last_tag_close' => '</li>',
            'next_tag_open' => '<li class="page-item ps-3">',
            'next_tag_close' => '</li>',
            'prev_tag_open' => '<li class="page-item pe-3">',
            'prev_tag_close' => '</li>',
            'num_tag_open' => '<li class="page-item">',
            'num_tag_close' => '</li>',
            'cur_tag_open' => "<li class='page-item'><a class='active page-link'>",
            'cur_tag_close' => "</a></li>"
        );

        $config['prev_link'] = '<i class="fa fa-angle-left"></i>';
        $config['next_link'] = '<i class="fa fa-angle-right"></i>';
        $this->pagination->initialize($config);

		$data['products'] = $this->front->getProducts($where,$config["per_page"],$offset);
        // echo $this->db->last_query();die;
        $data['trecords'] = $records;
        $data['links'] = "products/";
        // if(isset($_GET['catid']) && $_GET['catid']!=""){
        //     $data['catimages'] = $this->common->getsData('category',array('c_id'=>$_GET['catid']));
        // }
		$this->loadHtml('products','Shop Page',$data);
	}

	public function productDetailPage($p_name='',$pid='')
	{
		if ($pid!="") {
            $data['product'] = $this->common->getsData("products",array("productid"=>$pid));
            if($data['product']){
                $this->common->updateData("products",array('last_products'=>date('Y-m-d H:i:s')),array('productid'=>$pid));
                $data['related'] = $this->front->getProducts(array('npid'=>$data['product']['productid']),4);
                $data['seo'] = array('seo_title'=>$data['product']['product_name'],'seo_keyword'=>$data['product']['meta_keyword'],'seo_description'=>$data['product']['meta_decs']);
                $this->loadHtml("product-details","Product Detail",$data);
            }else{
                redirect(base_url());
            }
        }else{
            redirect(base_url());
        }
	}

    public function eproductsPage($limit='')
    {
        $get=array();
        if (isset($_GET)) {
            $get = $_GET;
        }
        if($limit!="")
        {
            $get['limit'] = $limit;            
        }
        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $get['limit'] = $_GET['per_page'];
        }
        $get['base_url'] = base_url('products');
        $data = $this->front->getEnqProductsListWithPag($get);
        $this->loadHtml("enq-products","Products",$data);
    }

    public function eproductsEnquiryPage()
    {
        $this->loadHtml("enq-product-enquiry","Product Enquiry");
    }

    public function brandPage()
    {
        $data['brand'] = $this->common->getData("brand",array(),array(),array('field'=>'id','by'=>'desc'));
        $this->loadHtml("brand","All Brand",$data);
    }

    public function aboutUsPage()
    {
        $data['featured'] = $this->common->getsData("team",array('isFeatured'=>1));
        $data['team'] = $this->common->getData("team",array(),array(),array('field'=>'item_order','by'=>'asc'));
        $this->loadHtml("about-us","About Us",$data);
    }

    public function awardPage()
    {
        $data['award'] = $this->common->getData("partners",array(),array(),array('field'=>'item_order','by'=>'asc'));
        $this->loadHtml("award","Awards",$data);
    }

    public function recipesPage($limit='')
    {
        $get=array();
        if (isset($_GET)) {
            $get = $_GET;
        }
        if($limit!="")
        {
            $get['limit'] = $limit;            
        }
        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $get['limit'] = $_GET['per_page'];
        }
        $get['base_url'] = base_url('recipes');
        $data = $this->front->getRecipesListWithPag($get);
        $this->loadHtml("recipes","Recipes",$data);
    }

    public function recipeDetailPage($slug='',$id='')
    {
        if ($id!="") {
            $data['post'] = $this->common->getsData("recipe",array("id"=>$id));
            if($data['post']){
                $data['related'] = $this->front->getRecipesList(array('nid'=>$data['post']['id']),array('limit'=>6),0);
                $this->loadHtml("recipes-detail","Recipes Detail",$data);
            }else{
                redirect(base_url());
            }
        }else{
            redirect(base_url());
        }
    }

    public function testimonialPage($limit='')
    {
        $get=array();
        if (isset($_GET)) {
            $get = $_GET;
        }
        if($limit!="")
        {
            $get['limit'] = $limit;            
        }
        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $get['limit'] = $_GET['per_page'];
        }
        $get['base_url'] = base_url('testimonials');
        // $data = $this->front->getTestimonialListWithPag($get);
        $data['testimonials'] = $this->front->getTestimonialList($get);
        $this->loadHtml("testimonial","Testimonials",$data);
    }

    public function servicesPage()
    {
        $this->loadHtml("services","Services");
    }

    public function serviceGalleryPage($slug='',$id='')
    {
        $data['service'] = $this->common->getsData('service_category',array('id'=>$id));
        $data['gallery'] = $this->common->getData('service_gallery',array('category'=>$id),array(),array('field'=>'item_order','by'=>'asc'));
        $this->loadHtml("service-gallery","Service Gallery",$data);
    }

    public function wishlistPage()
    {
        $this->loadHtml("wishlist","Wishlist");
    }

    public function prPage($limit='')
    {
        $get=array();
        if (isset($_GET)) {
            $get = $_GET;
        }
        if($limit!="")
        {
            $get['limit'] = $limit;            
        }
        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $get['limit'] = $_GET['per_page'];
        }
        $get['base_url'] = base_url('portfolio');
        $data = $this->front->getGalleryProjectListWithPag($get);
        $this->loadHtml("projects","Projects",$data);
    }

    public function getMoreGalleryProject()
    {
        $get=array();
        $_GET['catid'] = $_POST['catid'];
        $get['limit'] = $_POST['page'];
        $get['base_url'] = base_url('portfolio/');
        $data = $this->front->getGalleryProjectListWithPag($get);
        $html = '';
        if(isset($data['project']) && $data['project']){
            foreach ($data['project'] as $key => $value) {
                $html .= '<div class="col-md-4 col-sm-6">
                            <div class="project-box">
                              <a href="'.base_url('portfolio-detail/'.url_title(strtolower($value['title'])).'/'.$value['projectid']).'">';
                                if($value['feat_image']!=''){
                                  $html .= '<img src="'.base_url($value['feat_image']).'" class="w-100" alt="img">';
                                }else{
                                  $html .= '<img src="'.base_url().'assets/user/img/project-1.webp" class="w-100" alt="project1 img">';
                                }
                        $html .= '<div class="project-text">
                                  <ul class="list-unstyled d-flex">
                                    <li>';
                                        if($value['logo_image']!=''){
                                            $html .= '<img src="'.base_url($value['logo_image']).'" width="50" alt="award img">';
                                        }
                            $html .= '</li>
                                    <li style="max-width: 200px;">'.$value['logo_title'].'</li>
                                  </ul>
                                  <h6 class="project-title">'.$value['title'].'</h6>
                                  <button class="btn btn-link text-start p-0">VIEW PROJECT</button>
                                </div>
                                <div class="plus-icon">
                                  <i class="fa fa-plus"></i>
                                </div>
                              </a>
                            </div>
                        </div>';
            }
        }
        echo $this->common->jsonEncode(array('html'=>$html));
    }

    public function getProjectGallery()
    {
        $data['project'] = $this->common->getsData('gallery_project',array('projectid'=>$_POST['projectid']));
        $data['gallery'] = $this->common->getData('gallery',array('projectid'=>$_POST['projectid']),array(),array('field'=>'item_order','by'=>'asc'));
        $html = $this->load->view("gallery",$data,true);
        echo $this->common->jsonEncode(array('html'=>$html));
    }

    public function galleryDetailPage($slug='',$pid)
    {
        $data['project'] = $this->common->getsData('gallery_project',array('projectid'=>$pid));
        $data['gallery'] = $this->common->getData('gallery',array('projectid'=>$pid),array(),array('field'=>'item_order','by'=>'asc'));
        $this->loadHtml("project-inner","Project Gallery",$data);
    }

    public function privacyPolicyPage()
    {
        $this->loadHtml("privacy-policy","Privacy Policy");
    }

    public function refundPolicyPage()
    {
        $this->loadHtml("refund-policy","Refund Policy");
    }

    public function termConditionPage()
    {
        $this->loadHtml("terms-condition","Terms & Condition");
    }

    public function paymentPage()
    {
        $this->loadHtml("payment","Payment");
    }

    public function contactUsPage()
    {
        $this->loadHtml("contact-us","Contact Us");
    }
    public function trackPage()
    {
        $this->loadHtml("trackorder","trackPage");
    }

    public function notifyProductByUser()
    {
    	// echo "<pre>";
    	// print_r($_POST); die;
    	$url = $_POST['url'];
    	unset($_POST['url']);
    	if($_POST){
    		$_POST['date'] = date('Y-m-d H:i:s');
    		$res = $this->common->insertData('product_notify',$_POST);
    		if($res){
    			$this->session->set_flashdata('message', 'Enquiry Submitted.');
    		}else{
    			$this->session->set_flashdata('emessage', 'Enquiry Not Submitted.');
    		}
    	}else{
    		$this->session->set_flashdata('emessage', 'Something Went Wrong...');
    	}
    	redirect($url);
    }

    public function contactUs()	{
        if(isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response']!=''){
            unset($_POST['g-recaptcha-response']);
    		$html='You have a new enquiry from '.author.'. Here are the details - <br><br>';
    		foreach ($_POST as $key => $value) {
                if($key=='fname'){
                    $key = 'Name';
                }
    			$html.=ucwords(str_replace("_", " ", $key)).': '.$value."<br /><br/>";
    		}
            $image = '';
            $subject = "You have a new enquiry from ".author;
            $to = enquiry_email;
            // $to = 'vinod.starwebindia@gmail.com';
            $res = $this->common->sendMailBySendGrid($to,'',from_email,author,$subject,$html,$image);
    		if($res){
    			$this->session->set_flashdata("message","Thank you for showing your interest! We will contact you soon.");
    		}else{
    			$this->session->set_flashdata("emessage","Something went wrong.");
    		}
        }else{
            $this->session->set_flashdata("emessage","Captcha is required.");
        }
		redirect($_SERVER['HTTP_REFERER']);
	}

    public function productCartEnquiry() {
        if(isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response']!=''){
            unset($_POST['g-recaptcha-response']);
            $html='You have a new enquiry from '.author.'. Here are the details - <br><br>';
            foreach ($_POST as $key => $value) {
                $html.=ucwords(str_replace("_", " ", $key)).': '.$value."<br /><br/>";
            }
            $html .= "Product Details - <br><br>";
            $carthtml = '<ul>';
            if($this->wishlist->contents()){
                foreach ($this->wishlist->contents() as $key => $value) {
                    $carthtml .= '<li>
                                    <p><strong>Product - </strong>'.$value['options']['product_name'].' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Quantity - </strong>'.$value['qty'].'</p>
                                </li>';
                }
            }
            $carthtml .= '</ul>';
            $html .= $carthtml;
            // echo ($html);die;
            $image = '';
            $subject = "You have a new products enquiry from ".author;
            $to = enquiry_email;
            // $to = 'vinod.starwebindia@gmail.com';
            $res = $this->common->sendMailBySendGrid($to,'',from_email,author,$subject,$html,$image);
            if($res){
                $this->session->unset_userdata("wishlist_contents");
                $this->session->set_flashdata("message","Thank you for showing your interest! We will contact you soon.");
            }else{
                $this->session->set_flashdata("emessage","Something went wrong.");
            }
        }else{
            $this->session->set_flashdata("emessage","Captcha is required.");
        }
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function subscribeNewsletter() {
        if(isset($_POST['email']) && $_POST['email']!=''){
            if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $this->session->set_flashdata("emessage","Please Enter Valid Email Address");
                redirect($_SERVER['HTTP_REFERER']);
            }
            if(isset($_POST['name']) && $_POST['name']!=''){
                $name = $_POST['name'];
            }else{
                $name = '';
            }
            $email = $_POST['email'];
            $yes = $this->common->getsData('newsletter',array('email'=>$email));
            if($yes){
                $this->session->set_flashdata("emessage","You are already subscribed using this mail id");
            }else{
                $ip = $this->input->ip_address();
                $res = $this->common->insertData('newsletter',array('email'=>$email,'name'=>$name,'ip_address'=>$ip,'date'=>date('Y-m-d H:i:s')));
                    
                if($res){
                    $user = $this->common->getsData("user",array("email"=>$email));
                    if($user){
                        $cpost['profileid'] = $user['profileid'];
                    }else{
                        $cpost['profileid'] = 0;
                    }
                    $cpost['email'] = $email;
                    $cpost['coupon_code'] = time().strtoupper($this->getRandomString(2));
                    $cpost['coupon_type'] = 1;
                    $cpost['coupon_amount'] = 10;
                    $cpost['coupon_quantity'] = 1;
                    $cpost['cart_amount'] = 100;
                    $cpost['coupon_current_date'] = date('Y-m-d H:i:s');
                    $cpost['coupon_expiry_date'] = date('Y-m-d H:i:s',strtotime($cpost['coupon_current_date'].' + 240 days'));
                    // $this->common->insertData('coupon',$cpost);
                    $edata['coupon_code'] = $cpost['coupon_code'];
                    $subject = 'Newsletter Confirmation';
                    $html = $this->load->view('email_temp/newsletter-email',$edata,true);
                    // print_r ($html); die;
                    $this->common->sendMailBySendGrid($email,'',from_email,author,$subject,$html);
                    $this->session->set_flashdata("message","Thank you for showing your interest!");
                }else{
                    $this->session->set_flashdata("emessage","Something went wrong.");
                }
            }
        }else{
            $this->session->set_flashdata("emessage","Email is required");
        }
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function unsubscribeNewsletterNow()
    {
        if(isset($_GET['info']) && $_GET['info']!=''){
            $email = base64_decode($_GET['info']);
            $res = $this->common->deleteData('newsletter',array('email'=>$email));
            $this->session->set_flashdata("message","Your are successfully unsubscribed newsletter");
        }else{
            $this->session->set_flashdata("emessage","Something went wrong");
        }
        redirect(base_url()); 
    }

    public function searchProductAuto()
	{

		$html='';

		$term = $_GET['term'];

        $data = $this->front->autocomplete($term);

        print_r(json_encode($data));die;

	}

    public function searchProductByTagPage($tag='')
    {
        $tag = str_replace('-', ' ', $tag);
        if(isset($tag) && $tag!=''){
            $data['head_title'] = $tag;
            $data['products'] = $this->front->searchByTag($tag);
        }else{
            $data['head_title'] = '';
            $data['products'] = '';
        }        
        $this->loadHtml("search-result","Search",$data);
    }

    public function trackOrderAction()
    {
        if(isset($_POST['orderid']) && $_POST['orderid']!=''){
            $orderid = $_POST['orderid'];
            $data['trackorder'] = $this->front->getOrders($orderid,1);
            $data['order_status_message'] = $this->common->getData('order_status_message',array('orderid'=>$orderid),array(),array('field'=>'status','by'=>'desc'));
            // echo "<pre>";
            // print_r($data['oldorder']); die;
            $this->loadHtml("track-order","Track Order",$data);
        }else{
            $data['trackorder']='';
            $this->loadHtml("track-order","Track Order",$data);
        }
    }

    public function ourBlogList($limit='')
    {
        $get=array();
        if (isset($_GET)) {
            $get = $_GET;
        }
        if($limit!="")
        {
            $get['limit'] = $limit;            
        }
        $get['base_url'] = base_url('articles');
        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $get['limit'] = $_GET['per_page'];
        }
        $get['type'] = 0;
        $data = $this->front->getBlogListWithPag($get);
        $this->loadHtml('articles','All Articles',$data);
    }

    public function blogDetailPage($slug='',$id='')
    {
        $data['blog']=$this->common->getsData('post',array('id'=>$id));
        // $seo_title = ($data['blog']['seo_title']!='')?$data['blog']['seo_title']:$data['blog']['post_title'];
        // $seo_keyword = (($data['blog']['seo_keyword']!='')?$data['blog']['seo_keyword']:$data['blog']['post_title'].', Pest Control in Singapore , PestWerkz');
        // $seo_keyword = (($data['blog']['seo_description']!='')?$data['blog']['seo_description']:$data['blog']['post_title'].', PestWerkz is a trusted pest control company in Singapore that provides a full range of services to help you keep your premises pest-free. Call today.');
        // $data['seo'] = array('seo_title'=>$seo_title,'seo_keyword'=>$seo_keyword,'seo_description'=>$seo_keyword);
        $this->loadHtml('articles-detail','Article Detail',$data);
    }

    public function eventsList($limit='')
    {
        $get=array();
        if (isset($_GET)) {
            $get = $_GET;
        }
        if($limit!="")
        {
            $get['limit'] = $limit;            
        }
        $get['base_url'] = base_url('events');
        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $get['limit'] = $_GET['per_page'];
        }
        $get['type'] = 1;
        $data = $this->front->getBlogListWithPag($get);
        $this->loadHtml('events','All Events',$data);
    }

    public function eventDetailPage($slug='',$id='')
    {
        $data['blog']=$this->common->getsData('post',array('id'=>$id));
        $this->loadHtml('events-detail','Event Detail',$data);
    }

    public function serviceBakingClassPage($limit='')
    {
        $get=array();
        if (isset($_GET)) {
            $get = $_GET;
        }
        if($limit!="")
        {
            $get['limit'] = $limit;            
        }
        $get['base_url'] = base_url('service-baking-class');
        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $get['limit'] = $_GET['per_page'];
        }
        $get['type'] = 2;
        $data = $this->front->getBlogListWithPag($get);
        $this->loadHtml('baking-class','All Service Baking Class',$data);
    }

    public function serviceBakingClassDetailPage($slug='',$id='')
    {
        $data['blog']=$this->common->getsData('post',array('id'=>$id));
        $this->loadHtml('class-details','Baking Class Detail',$data);
    }

    public function submitProductReview()
    {
        $_POST['date'] = date('Y-m-d H:i:s');
        $rdata = $this->common->getField('prodcut_rating',$_POST);
        $res = $this->common->insertData('prodcut_rating',$rdata);
        if($res){
            $rate = $this->common->getData('prodcut_rating',array('product_id'=>$_POST['product_id']),array('AVG(rating) AS rating','count("id") as reviews'));
            if($rate){
                $this->common->updateData('products',array('rating'=>$rate[0]['rating'],'reviews'=>$rate[0]['reviews']),array('productid'=>$_POST['product_id']));
            }else{
                $this->common->updateData('products',array('rating'=>$_POST['rating'],'reviews'=>1),array('productid'=>$_POST['product_id']));
            }
            $this->session->set_flashdata('message','Rating Added');
        }
        else{
            $this->session->set_flashdata('message','Rating Not Added');
        }
        redirect($_SERVER['HTTP_REFERER']);
    }

	function logout()
    {
        //$this->session->sess_destroy();
        $this->session->unset_userdata('email');
        $this->session->unset_userdata('profileid');
        $this->session->unset_userdata('is_user_logged_in');
        $this->session->set_userdata(array("user_login_type"=>"guest_user"));
        $this->session->unset_userdata("sfirst_name");
        $this->session->unset_userdata("slast_name");
        $this->session->unset_userdata("scity");
        $this->session->unset_userdata("sstate");
        $this->session->unset_userdata("scountry");
        $this->session->unset_userdata("spostalcode");
        $this->session->unset_userdata("smobile_no");
        $this->session->unset_userdata("saddress1");
        $this->session->unset_userdata("saddress2");
        $this->session->unset_userdata("bfirst_name");
        $this->session->unset_userdata("blast_name");
        $this->session->unset_userdata("bcity");
        $this->session->unset_userdata("bstate");
        $this->session->unset_userdata("bcountry");
        $this->session->unset_userdata("bpostalcode");
        $this->session->unset_userdata("bmobile_no");
        $this->session->unset_userdata("baddress1");
        $this->session->unset_userdata("baddress2");
        $this->session->unset_userdata("payment_method");
        $this->session->unset_userdata("awtc");
        $this->session->unset_userdata("user_coupon");
        redirect(base_url('user-login'));
    }

    public function getProductWiseCouponCode()
    {
        $html = '';
        // $pcoupon = $this->common->getData('coupon',array('productid'=>$_POST['productid'],'coupon_quantity>='=>1,'coupon_expiry_date>='=>date('Y-m-d')));
        $query = 'SELECT * FROM coupon WHERE productid regexp "[[:<:]]'.$_POST['productid'].'[[:>:]]" AND coupon_quantity > 0 AND UNIX_TIMESTAMP() < UNIX_TIMESTAMP(coupon_expiry_date)';
        $pcoupon = $this->db->query($query)->result_array();
        if($pcoupon){
            foreach ($pcoupon as $key => $value) {
                $html .= '<div class="row align-items-center">
                            <div class="col-lg-7 col-md-7 col-sm-7 col-12">
                              <h5>'.$value['coupon_amount'].' '.(($value['coupon_type']==0)?"$":"%").' Discount</h5>
                              <h6>Coupon Code: '.$value['coupon_code'].'</h6>
                              <p>Limited promotion till '.date('d M Y',strtotime($value['coupon_expiry_date'])).'</p>
                            </div>
                            <div class="col-lg-5 col-md-5 col-sm-5 col-12">
                              <a href="'.base_url('front/applyProductCoupon?cid='.$value['id'].'&coupon_code='.$value['coupon_code']).'&productid='.$_POST['productid'].'" class="btn btn-outline-primary">Use Now</a>
                            </div>
                        </div>';
            }
        }
        echo $this->common->jsonEncode(array('html'=>$html));
    }

    public function applyProductCoupon()
    {
        $pcoupon = $this->common->getsData('coupon',array('id'=>$_GET['cid'],'coupon_code'=>$_GET['coupon_code'],'coupon_quantity>='=>1,'coupon_expiry_date>='=>date('Y-m-d')));
        if($pcoupon){
            $pids = explode(',', $pcoupon['productid']);
            foreach ($pids as $key => $value) {
                if($value==$_GET['productid']){
                    $product = $this->common->getsData('products',array('productid'=>$_GET['productid']));
                    $product_coupon[$_GET['productid']] = array(
                        'coupon_code'=>$pcoupon['coupon_code'],
                        'coupon_amount'=>$pcoupon['coupon_amount'],
                        'coupon_type'=>$pcoupon['coupon_type'],
                    ); 
                    $this->session->set_userdata('product_coupon',$product_coupon);
                }else{
                    $coupon_apply = $this->session->userData('product_coupon');
                    unset($coupon_apply[$value]);
                    unset($coupon_apply[$value]['coupon_code']);
                    unset($coupon_apply[$value]['coupon_amount']);
                    unset($coupon_apply[$value]['coupon_type']);
                }
            }
            $this->session->set_flashdata('message','Coupon code applied!');
        }else{
            $this->session->set_flashdata('emessage','Something went wrong...');
        }
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function removeProductCoupon()
    {
        $coupon_apply = $this->session->userData('product_coupon');
        // echo "<pre>";
        // print_r ($coupon_apply[$_GET['productid']]);
        // echo "</pre>";
        unset($coupon_apply[$_GET['productid']]);
        unset($coupon_apply[$_GET['productid']]['coupon_code']);
        unset($coupon_apply[$_GET['productid']]['coupon_amount']);
        unset($coupon_apply[$_GET['productid']]['coupon_type']);
        $this->session->set_userdata('product_coupon',$coupon_apply);
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function addProductInWishlist()
    {
        $is_user_logged_in = $this->session->userdata('is_user_logged_in');
        if($is_user_logged_in==true){
            $profileid = $this->profileid;
        }else{
            $profileid = $this->input->ip_address();
        }
        $yes = $this->common->getsData('wishlist',array('profileid'=>$profileid,'productid'=>$_POST['productid']));
        if($yes){

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

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

    public function userfavouritesPage($offset='')
    {
        $where = array();

        if(isset($_GET['order_by']) && $_GET['order_by']!=''){
            $where['order_by']=$_GET['order_by'];
        }

        if(isset($_GET['search']) && $_GET['search']!=''){
            $where['keyword']=$_GET['search'];
        }

        $is_user_logged_in = $this->session->userdata('is_user_logged_in');
        if($is_user_logged_in==true){
            $profileid = $this->profileid;
        }else{
            $profileid = $this->input->ip_address();
        }

        $where['fav'] = 1;
        $where['profileid'] = $profileid;

        if(isset($_GET['per_page']) && $_GET['per_page']!=''){
            $offset = $_GET['per_page'];
        }

        $get = $_GET;
        $query = $_SERVER['QUERY_STRING'];
        if(isset($get)){
            if(isset($get['per_page'])){
                unset($get['per_page']);
            }
            $query = http_build_query($get);
        }

        $config =  array(
            'page_query_string' => true,
            'base_url' => base_url('user-favourites') ,
            'per_page' =>15,
            'total_rows' => $this->front->record_count('wishlist',$where),
            'full_tag_open' => "<ul class='pagination'>",
            'full_tag_close' => "</ul>",
            'first_tag_open' => '<li>',
            'first_tag_close' => '</li>',
            'last_tag_open' => '<li>',
            'last_tag_close' => '</li>',
            'next_tag_open' => '<li>',
            'next_tag_close' => '</li>',
            'prev_tag_open' => '<li>',
            'prev_tag_close' => '</li>',
            'num_tag_open' => '<li>',
            'num_tag_close' => '</li>',
            'cur_tag_open' => "<li><a class='active'>",
            'cur_tag_close' => "</a></li>"
             );
        $this->pagination->initialize($config);

        $data['products'] = $this->front->getProducts($where,$config["per_page"],$offset);
        $data['links'] = "my-favourites";
        $this->loadHtml('wishlist','Favourites Products',$data);
    }

    /*public function getCartProductInfo()
    {
        $cart_time = $this->session->userdata('view_cart_time');
        if($cart_time){
            $cvt = strtotime(date("H:i", strtotime('+10 minutes', $cart_time)));
        }else{
            $cvt = time();
            $this->session->set_userdata('view_cart_time',time());
        }
        $ctime = time();
        $cart = $this->cart->contents();
        if($cart){
            if($ctime>$cvt){
                $is_user_logged_in = $this->session->userdata('is_user_logged_in');
                if($is_user_logged_in){
                    $this->session->set_userdata('view_cart_time',time());
                    $user = $this->common->getsData("user",array("profileid"=>$this->session->userdata('profileid')),'email');
                    
                    $data['cart'] = $cart;

                    $subject = 'Still thinking about it?';
                    $message = $this->load->view('email_temp/cart-product-notify',$data,true);

                    $res = $this->common->sendMailBySendGrid($user['email'],'',from_email,author,$subject,$message);
                    echo $res;
                }else{
                    echo 0;
                }
            }else{
                echo 0;
            }
        }else{
            echo 0;
        }
    }*/
}
