<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Admin_Controller extends MY_Controller {

	function __construct() {
		
		parent::__construct();
		$data = array();
		$this->load->model(A."/admin_model","admin");
		$this->load->helper('admin');
		$this->adminid = $this->session->userdata('adminid');
		$this->admin_name = $this->session->userdata('admin_name');
		$this->ad = $this->common->getsData('admin',array('adminid'=>$this->adminid));
		if($this->ad){
			$this->admin_type = $this->ad['admin_type'];
			$this->authority = explode('|', $this->ad['authority']);
		}
		$this->load->library('pagination');
		$this->perPage = ($this->session->userdata("admin_length")?$this->session->userdata("admin_length"):10);
	}

	public function AdminSearchLength()
    {
        $this->session->set_userdata(array("admin_length"=>$_POST['length']));
        echo 1;die;
    }

    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 = ''; 
	            break;
	        case 'image/svg': 
	            $image = ''; 
	            break; 
	        default: 
	            $image = imagecreatefromjpeg($source); 
	    } 
	     
	    if($image!=''){
		    imagejpeg($image, $destination, $quality); 
		    return $destination; 
		}else{
			return 0;
		}
	}

	public function do_upload($file_name, $path)
    {
        $config['upload_path']   = $path;
        $config['allowed_types'] = '*';
        // $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 setAdminAuthority()
    {
    	if($_POST){
    		$adminid = $_POST['adminid'];
    		unset($_POST['adminid']);
			if(isset($_POST['authority']) && $_POST['authority']){
		    	$_POST['authority'] = implode('|', $_POST['authority']);
		    }
    		$postdata = $this->common->getField('admin',$_POST);
			$res = $this->common->updateData('admin',$postdata,array('adminid'=>$adminid));
			if($res){
				$this->session->set_flashdata('message','Admin Authority Updated Successfully');
			}else{
				$this->session->set_flashdata('emessage','Admin Authority Not Updated');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function addAdmin()
    {
    	// echo "<pre>";
    	// print_r($_POST); die;
    	if($_POST){
			$_POST['plain_password'] = $_POST['password'];
			$_POST['password'] = md5($_POST['password']);
			$_POST['admin_type'] = "subadmin";
			$_POST['adminid'] = strtotime(date('Y-m-d H:i:s'));
			//print_r($_POST); die;
			if(isset($_POST['authority']) && $_POST['authority']){
		    	$_POST['authority'] = implode('|', $_POST['authority']);
		    }
    		$postdata = $this->common->getField('admin',$_POST);
			$res = $this->common->insertData('admin',$postdata);
			if($res){
				$this->session->set_flashdata('message','Admin Added Successfully');
			}else{
				$this->session->set_flashdata('emessage','Admin Not Added');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect(base_url(A."/add-admin"));
    }


    public function editAdmin()
    {
    	if($_POST){
	    	$adminid = $_POST['adminid'];
			unset($_POST['adminid']);
			$_POST['plain_password'] = $_POST['password'];
			$_POST['password'] = md5($_POST['password']);
			if(isset($_POST['authority']) && $_POST['authority']){
		    	$_POST['authority'] = implode('|', $_POST['authority']);
		    }
			$postdata = $this->common->getField('admin',$_POST);
			$res = $this->common->updateData('admin',$postdata,array('id'=>$adminid));
			if($res){
				$this->session->set_flashdata('message','Admin Updated Successfully');
			}else{
				$this->session->set_flashdata('emessage','Admin Not Updated');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }
    

    public function addProductTag()
	{
		$_POST['date'] = date('Y-m-d H:i:s');
		/*if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
           	$upload_rslt = $this->do_upload('image','assets/categories/');
           	if(!empty($upload_rslt['upload_data'])){ 
				$filename = $upload_rslt['upload_data']['file_name'];
				$image = 'assets/categories/'.$filename;
	    		$_POST['image'] = $image;
            }
        }*/
        $_POST['key_value'] = $_POST['tag'];
        $bpost = $this->common->getField('tag',$_POST);
		$res = $this->common->insertData('tag',$bpost);
		if($res)
		{
			$this->session->set_flashdata("message",'Tag Added Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editProductTag()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		/*if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
           	$upload_rslt = $this->do_upload('image','assets/categories/');
           	if(!empty($upload_rslt['upload_data'])){ 
				$filename = $upload_rslt['upload_data']['file_name'];
				$image = 'assets/categories/'.$filename;
	    		$_POST['image'] = $image;
            }
        }*/
        $bpost = $this->common->getField('tag',$_POST);
		$res = $this->common->updateData('tag',$bpost,array('id'=>$id));
		if($res)
		{
			$this->session->set_flashdata("message",'Tag Updated Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

    

    public function addBlogCategory()
	{
		$_POST['date'] = date('Y-m-d H:i:s');
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
           	$upload_rslt = $this->do_upload('image','assets/categories/');
           	if(!empty($upload_rslt['upload_data'])){ 
				$filename = $upload_rslt['upload_data']['file_name'];
				$image = 'assets/categories/'.$filename;
	    		$_POST['image'] = $image;
            }
        }
        $bpost = $this->common->getField('blog_category',$_POST);
		$res = $this->common->insertData('blog_category',$bpost);
		if($res)
		{
			$this->session->set_flashdata("message",'Category Added Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editBlogCategory()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
           	$upload_rslt = $this->do_upload('image','assets/categories/');
           	if(!empty($upload_rslt['upload_data'])){ 
				$filename = $upload_rslt['upload_data']['file_name'];
				$image = 'assets/categories/'.$filename;
	    		$_POST['image'] = $image;
            }
        }
        $bpost = $this->common->getField('blog_category',$_POST);
		$res = $this->common->updateData('blog_category',$bpost,array('id'=>$id));
		if($res)
		{
			$this->session->set_flashdata("message",'Category updated successfully.');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}    

    public function addBrand()
	{
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
           	$upload_rslt = $this->do_upload('image','assets/brand-img/');
           	if(!empty($upload_rslt['upload_data'])){ 
				$filename = $upload_rslt['upload_data']['file_name'];
				$image = 'assets/brand-img/'.$filename;
	    		$_POST['image'] = $image;
            }
        }else{
        	$_POST['image'] = '';
        }
		$res = $this->admin->addBrand($_POST);
		if($res)
		{
			$this->session->set_flashdata("message",'Brand Added Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editBrand()
	{
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
           	$upload_rslt = $this->do_upload('image','assets/brand-img/');
           	if(!empty($upload_rslt['upload_data'])){ 
				$filename = $upload_rslt['upload_data']['file_name'];
				$image = 'assets/brand-img/'.$filename;
	    		$_POST['image'] = $image;
            }
        }else{
        	$_POST['image'] = $_POST['old_image'];
        	unset($_POST['old_image']);
        }
		$res = $this->admin->editBrand($_POST);
		if($res)
		{
			$this->session->set_flashdata("message",'Brand Updated Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function addCategory()
	{
		//print_r($_POST); die;
		if(isset($_POST['addcategory']))
		{
			if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	           	$upload_rslt = $this->do_upload('image','assets/categories/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$image = 'assets/categories/'.$filename;
		    		$_POST['image'] = $image;
	            }
	        }
			if(isset($_FILES['banner_image']['name']) && $_FILES['banner_image']['name'] != ""){
	           	$upload_rslt = $this->do_upload('banner_image','assets/categories/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$banner_image = 'assets/categories/'.$filename;
		    		$_POST['banner_image'] = $banner_image;
	            }
	        }
			if(isset($_FILES['back_image']['name']) && $_FILES['back_image']['name'] != ""){
	           	$upload_rslt = $this->do_upload('back_image','assets/categories/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$back_image = 'assets/categories/'.$filename;
		    		$_POST['back_image'] = $back_image;
	            }
	        }


			$res = $this->admin->insertCategories($_POST,'category');

			if($res){
				$this->session->set_flashdata('message','Category Added Successfully');
			}else{
				$this->session->set_flashdata('emessage','Category is Not Added Please Try Again.');
			}
		}

		redirect(base_url(A."/add-category"));

	}
	public function addSubCategory()
	{
		if(isset($_POST['addsubcategory']))
		{
			if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	           	$upload_rslt = $this->do_upload('image','assets/categories/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$image = 'assets/categories/'.$filename;
		    		$_POST['image'] = $image;
	            }
	        }
			if(isset($_FILES['banner_image']['name']) && $_FILES['banner_image']['name'] != ""){
	           	$upload_rslt = $this->do_upload('banner_image','assets/categories/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$banner_image = 'assets/categories/'.$filename;
		    		$_POST['banner_image'] = $banner_image;
	            }
	        }
			if(isset($_FILES['back_image']['name']) && $_FILES['back_image']['name'] != ""){
	           	$upload_rslt = $this->do_upload('back_image','assets/categories/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$back_image = 'assets/categories/'.$filename;
		    		$_POST['back_image'] = $back_image;
	            }
	        }

			$res = $this->admin->insertCategories($_POST,'category');

			if($res){

				$this->session->set_flashdata('message',$this->lang->line("subcategory_added"));

			}else{

				$this->session->set_flashdata('emessage',$this->lang->line("error_subcategory_added"));

			}

		}

		redirect(base_url(A."/add-category"));

	}



	public function editCategory()
	{ 
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
           $upload_rslt = $this->do_upload('image','assets/categories/');
            if(!empty($upload_rslt['upload_data'])){ 
			    $image1 = $upload_rslt['upload_data']['file_name'];	
			    $image =  'assets/categories/'.$image1; 
        		$_POST['image'] = $image;
			    if(file_exists('assets/categories/'.$image1)){
			    	$photo_path=$this->input->post('old_img');
			    	if(!empty($photo_path)){
						$path=$photo_path;
						chown($path, 777);
						$shopdel=unlink($path);
					}
			    }
            }
        }
		if(isset($_FILES['banner_image']['name']) && $_FILES['banner_image']['name'] != ""){
           $upload_rslt = $this->do_upload('banner_image','assets/categories/');
            if(!empty($upload_rslt['upload_data'])){ 
			    $banner_image1 = $upload_rslt['upload_data']['file_name'];	
			    $banner_image =  'assets/categories/'.$banner_image1; 
        		$_POST['banner_image'] = $banner_image;
			    if(file_exists('assets/categories/'.$banner_image1)){
			    	$photo_path=$this->input->post('old_bannerimg');
			    	if(!empty($photo_path)){
						$path=$photo_path;
						chown($path, 777);
						$shopdel=unlink($path);
					}
			    }
            }
        }
		if(isset($_FILES['back_image']['name']) && $_FILES['back_image']['name'] != ""){
           $upload_rslt = $this->do_upload('back_image','assets/categories/');
            if(!empty($upload_rslt['upload_data'])){ 
			    $back_image1 = $upload_rslt['upload_data']['file_name'];	
			    $back_image =  'assets/categories/'.$back_image1; 
        		$_POST['back_image'] = $back_image;
			    if(file_exists('assets/categories/'.$back_image1)){
			    	$photo_path=$this->input->post('old_backimg');
			    	if(!empty($photo_path)){
						$path=$photo_path;
						chown($path, 777);
						$shopdel=unlink($path);
					}
			    }
            }
        }
        $catid = $_POST['catid'];
        unset($_POST['catid']);
        unset($_POST['old_img']);
        unset($_POST['old_bannerimg']);
        unset($_POST['old_backimg']);
        $res = $this->common->updateData('category',$_POST,array('c_id'=>$catid));

        if($res){
			$this->session->set_flashdata('message','Category updated successfully.');
		}else{
			$this->session->set_flashdata('emessage','Category Not Updated');
		}
		redirect(base_url(A."/all-category"));

	}

	public function deleteCategory()
	{
		if($this->admin->deleteCategory($_POST))
		{
			echo 1;
		}else{
			echo 0;
		}die;
	}

	public function checkCategory()
	{
		if($this->common->updateData('category',array('show'=>$_POST['val']),array('c_id'=>$_POST['id'])))
		{
			echo 1;
		}else{
			echo 0;
		}die;
	}

	public function checkCategoryFeatured()
	{
		if($this->common->updateData('category',array('isFeatured'=>$_POST['val']),array('c_id'=>$_POST['id'])))
		{
			echo 1;
		}else{
			echo 0;
		}die;
	}



	public function updateLoginInfo()
	{ 
		$_POST['plain_password'] = $_POST['password'];
		$_POST['password'] = md5($_POST['password']);
        $res = $this->common->updateData('admin',$_POST,array('id'=>1));
        if($res){
			$this->session->set_flashdata('message','Login Details Updated Successfully');
		}else{
			$this->session->set_flashdata('emessage','Details Not Update');
		}
		redirect($_SERVER['HTTP_REFERER']);

	}
	public function updateCompanyInfo()
	{ 
		if(isset($_FILES['popup_image']['name']) && $_FILES['popup_image']['name'] != ""){
           	$upload_rslt = $this->do_upload('popup_image','assets/categories/');
           	if(!empty($upload_rslt['upload_data'])){ 
				$filename = $upload_rslt['upload_data']['file_name'];
				$popup_image = 'assets/categories/'.$filename;
	    		$_POST['popup_image'] = $popup_image;
            }
        }
        $res = $this->common->updateData('web_setting',$_POST,array('id'=>1));
        if($res){
			$this->session->set_flashdata('message','Setting Updated Successfully');
		}else{
			$this->session->set_flashdata('emessage','Setting Not Update');
		}
		redirect($_SERVER['HTTP_REFERER']);

	}

	public function dollarRateUpdate()
	{ 
		if(isset($_POST['rate']) && $_POST['rate']!=''){
	        $res = $this->common->updateData('dollarprice',$_POST,array('id'=>1));

	        if($res){
				$this->session->set_flashdata('message','Rate Updated Successfully');
			}else{
				$this->session->set_flashdata('emessage','Rate Not Update');
			}
		}else{
			$this->session->set_flashdata('emessage','Please Enter Rate');
		}
		redirect($_SERVER['HTTP_REFERER']);

	}

	public function addPost($value='')
    {
    	// echo "<pre>";
    	// print_r($_POST); die;
    	if($_POST){
    		if(isset($_FILES['icon']['name']) && $_FILES['icon']['name']!=''){
    			$iconname = rand().'-'.str_replace(" ","-",$_FILES['icon']['name']);
    			$icontmpname = $_FILES['icon']['tmp_name'];
    			$uploadpath1 = "assets/post-image/".$iconname;
	    		if (move_uploaded_file($icontmpname, $uploadpath1)) {
				    $_POST['icon'] = $uploadpath1;
				}
    		}
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname = $_FILES['image']['tmp_name'];
    			$uploadpath = "assets/post-image/".$imagename;
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
    		}
    		if(isset($_POST['publish_date']) && $_POST['publish_date']!=''){
	    		$_POST['publish_date'] = date('Y-m-d H:i:s',strtotime($_POST['publish_date']));
	    	}else{
	    		$_POST['publish_date'] = date('Y-m-d H:i:s');
	    	}
    		$postdata = $this->common->getField('post',$_POST);
   //  		if(isset($_POST['post_category']) && $_POST['post_category']){
			// 	$postdata['post_category'] = implode(',', $_POST['post_category']);
			// 	$cid = $postdata['post_category'][0];
			// }else{
			// 	$postdata['post_category'] = '';
			// 	$cid='';
			// }
			$res = $this->common->insertData('post',$postdata);
			if($res){
				$pid = $this->db->insert_id();
				if(isset($_FILES['blog_image']['name']) && $_FILES['blog_image']['name']){
					$cccc = count($_FILES['blog_image']['name']);
					for($prt=0; $prt<$cccc; $prt++)
					{
						if(isset($_FILES['blog_image']['name'][$prt]) && $_FILES['blog_image']['name'][$prt]!=''){
			    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['blog_image']['name'][$prt]);
			    			$imagetmpname = $_FILES['blog_image']['tmp_name'][$prt];
			    			$uploadpath = "assets/post-image/".$imagename;
				    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
							    $prbar = array('postid'=>$pid,'blog_image'=>$uploadpath);
								$this->common->insertData('blog_media',$prbar);
							}
			    		}
					}
				}
				if(isset($_POST['type']) && $_POST['type']==1){
					$this->session->set_flashdata('message','Event Added Successfully');
				}else if(isset($_POST['type']) && $_POST['type']==2){
					$this->session->set_flashdata('message','Baking Class Added Successfully');
				}else{
					$this->session->set_flashdata('message','News Added Successfully');
				}
			}else{
				if(isset($_POST['type']) && $_POST['type']==1){
					$this->session->set_flashdata('emessage','Event Not Added');
				}else if(isset($_POST['type']) && $_POST['type']==2){
					$this->session->set_flashdata('emessage','Baking Class Not Added');
				}else{
					$this->session->set_flashdata('emessage','News Not Added');
				}
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editPost()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
			if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname = $_FILES['image']['tmp_name'];
    			$uploadpath = "assets/post-image/".$imagename;
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
	    			if(file_exists($uploadpath)){
				    	$image_path=$this->input->post('old_image');
				    	if(!empty($image_path)){
							chown($image_path, 777);
							$imagedel=unlink($image_path);
						}
				    }
				    $_POST['image'] = $uploadpath;
				}
    		}
    		if(isset($_FILES['icon']['name']) && $_FILES['icon']['name']!=''){
    			$iconname = rand().'-'.str_replace(" ","-",$_FILES['icon']['name']);
    			$icontmpname = $_FILES['icon']['tmp_name'];
    			$uploadpath1 = "assets/post-image/".$iconname;
	    		if (move_uploaded_file($icontmpname, $uploadpath1)) {
				    $_POST['icon'] = $uploadpath1;
				}
    		}
			$postdata = $this->common->getField('post',$_POST);
    		if(isset($_POST['publish_date']) && $_POST['publish_date']!=''){
	    		$postdata['publish_date'] = date('Y-m-d H:i:s',strtotime($_POST['publish_date']));
	    	}
			// if(isset($_POST['post_category']) && $_POST['post_category']){
			// 	$postdata['post_category'] = implode(',', $_POST['post_category']);
			// }else{
			// 	$postdata['post_category'] = '';
			// }
			$res = $this->common->updateData('post',$postdata,array('id'=>$postid));
			if($res){
				if(isset($_FILES['blog_image']['name']) && $_FILES['blog_image']['name']){
					$cccc = count($_FILES['blog_image']['name']);
					for($prt=0; $prt<$cccc; $prt++)
					{
						if(isset($_FILES['blog_image']['name'][$prt]) && $_FILES['blog_image']['name'][$prt]!=''){
			    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['blog_image']['name'][$prt]);
			    			$imagetmpname = $_FILES['blog_image']['tmp_name'][$prt];
			    			$uploadpath = "assets/post-image/".$imagename;
				    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
							    $prbar = array('postid'=>$postid,'blog_image'=>$uploadpath);
								$this->common->insertData('blog_media',$prbar);
							}
			    		}
					}
				}
				if(isset($_POST['type']) && $_POST['type']==1){
					$this->session->set_flashdata('message','Event Updated Successfully');
				}else if(isset($_POST['type']) && $_POST['type']==2){
					$this->session->set_flashdata('message','Baking Class Updated Successfully');
				}else{
					$this->session->set_flashdata('message','Event Updated Successfully');
				}
			}else{
				if(isset($_POST['type']) && $_POST['type']==1){
					$this->session->set_flashdata('emessage','Event Not Update');
				}else if(isset($_POST['type']) && $_POST['type']==2){
					$this->session->set_flashdata('emessage','Baking Class Not Update');
				}else{
					$this->session->set_flashdata('emessage','News Not Update');
				}
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function editBlogImageTitleAction()
	{
		if($_POST){
			$res = $this->common->updateData('blog_media',array($_POST['name']=>$_POST['value']),array('id'=>$_POST['pk']));
		}
	}

	public function deleteBlogMultiMedia()	{
		$image = $this->common->getsData('blog_media',array('id'=>$_POST['id'],'blog_image !='=>'assets/post-image'),'blog_image');
		if($image['blog_image'] != ""){
			if(file_exists($image['blog_image'])){
				unlink($image['blog_image']);
			}
		}
		$this->common->deletedata('blog_media',array('id'=>$_POST['id']));
		if($this->db->affected_rows()){
			echo "1";
		}else{
			echo "0";
		} die;
	}

    public function uploadPostImage(){
    	// $brand_img=''; 
		// if($_FILES['file']['name'] != ""){
        //     $brand_img = 'file';
        //    	$upload_rslt = $this->do_upload($brand_img,'assets/upload-image');
        //    	if(!empty($upload_rslt['upload_data'])){ 
		// 		$filename = $upload_rslt['upload_data']['file_name'];
		// 		print_r($filename);
        //     }else{
        //         echo 0;
        //     } die;
        // }
        if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['file']['name']);
			$imagetmpname = $_FILES['file']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                print_r($imagename);
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    print_r($imagename);
				}
			}die;
        }
    }

    public function addRecipeCategory()
	{
		$_POST['date'] = date('Y-m-d H:i:s');
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('recipe_category',$_POST);
		$res = $this->common->insertData('recipe_category',$bpost);
		if($res)
		{
			$this->session->set_flashdata("message",'Category Added Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editRecipeCategory()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('recipe_category',$_POST);
		$res = $this->common->updateData('recipe_category',$bpost,array('id'=>$id));
		if($res)
		{
			$this->session->set_flashdata("message",'Category updated successfully.');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function addRecipe($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
				$imagetmpname = $_FILES['image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['image'] = $uploadpath;
					}
				}
	        }
    		$postdata = $this->common->getField('recipe',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('recipe',$postdata);
			if($res){
				$this->session->set_flashdata('message','Recipe Added successfully');
			}else{
				$this->session->set_flashdata('emessage','Recipe Not Add');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editRecipe()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
			if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
				$imagetmpname = $_FILES['image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['image'] = $uploadpath;
					}
				}
	        }
			$postdata = $this->common->getField('recipe',$_POST);
			$res = $this->common->updateData('recipe',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','Recipe updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Recipe Not Update');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function addFaqCategory()
	{
		$_POST['date'] = date('Y-m-d H:i:s');
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('faq_category',$_POST);
		$res = $this->common->insertData('faq_category',$bpost);
		if($res)
		{
			$this->session->set_flashdata("message",'Category Added Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editFaqCategory()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('faq_category',$_POST);
		$res = $this->common->updateData('faq_category',$bpost,array('id'=>$id));
		if($res)
		{
			$this->session->set_flashdata("message",'Category updated successfully.');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function addFaq($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
				$imagetmpname = $_FILES['image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['image'] = $uploadpath;
					}
				}
	        }
    		$postdata = $this->common->getField('faq',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('faq',$postdata);
			if($res){
				$this->session->set_flashdata('message','FAQ Added successfully');
			}else{
				$this->session->set_flashdata('emessage','FAQ Not Add');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editFaq()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
			if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
				$imagetmpname = $_FILES['image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['image'] = $uploadpath;
					}
				}
	        }
			$postdata = $this->common->getField('faq',$_POST);
			$res = $this->common->updateData('faq',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','FAQ updated successfully');
			}else{
				$this->session->set_flashdata('emessage','FAQ Not Update');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function addEpCategory()
	{
		$_POST['date'] = date('Y-m-d H:i:s');
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('ep_category',$_POST);
		$res = $this->common->insertData('ep_category',$bpost);
		if($res)
		{
			$this->session->set_flashdata("message",'Category Added Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editEpCategory()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('ep_category',$_POST);
		$res = $this->common->updateData('ep_category',$bpost,array('id'=>$id));
		if($res)
		{
			$this->session->set_flashdata("message",'Category updated successfully.');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function addEp($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
				$imagetmpname = $_FILES['image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['image'] = $uploadpath;
					}
				}
	        }
    		$postdata = $this->common->getField('eproduct',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('eproduct',$postdata);
			if($res){
				$this->session->set_flashdata('message','Enquiry Product Added successfully');
			}else{
				$this->session->set_flashdata('emessage','Enquiry Product Not Add');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editEp()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
			if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
				$imagetmpname = $_FILES['image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['image'] = $uploadpath;
					}
				}
	        }
			$postdata = $this->common->getField('eproduct',$_POST);
			$res = $this->common->updateData('eproduct',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','Enquiry Product updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Enquiry Product Not Update');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function addTeam($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
    		$postdata = $this->common->getField('team',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('team',$postdata);
			if($res){
				$this->session->set_flashdata('message','Team Added successfully');
			}else{
				$this->session->set_flashdata('emessage','Team Not Add');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editTeam()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
			$postdata = $this->common->getField('team',$_POST);
			$res = $this->common->updateData('team',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','Team updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Team Not Update');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function addTestimonial($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
    		$postdata = $this->common->getField('testimonial',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('testimonial',$postdata);
			if($res){
				$this->session->set_flashdata('message','Testimonial Added successfully');
			}else{
				$this->session->set_flashdata('emessage','Testimonial Not Add');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editTestimonial()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
			$postdata = $this->common->getField('testimonial',$_POST);
			$res = $this->common->updateData('testimonial',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','Testimonial updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Testimonial Not Update');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function updateTestimonialOrder()
	{
		if(isset($_POST['div'])){
			$data = explode(',',$_POST['div']);
			// echo "<pre>";
			// print_r ($data);
			// echo "</pre>";die;
			foreach ($data as $key => $value) {
				if($this->common->getsData("testimonial",array("id"=>$value))){
					$this->common->updateData('testimonial',array('item_order'=>$key+1),array("id"=>$value));
				}
			}
		}
	}



	public function addServiceGallery($value='')
    {
    	if($_POST){
    		$_POST['date'] = date('Y-m-d H:i:s');
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$cccc = count($_FILES['image']['name']);
				for($prt=0; $prt<$cccc; $prt++)
				{
	    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name'][$prt]);
	    			$imagetmpname = $_FILES['image']['tmp_name'][$prt];
	    			$uploadpath = "assets/upload-image/".$imagename;
	    			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
		            if($compressedImage){ 
		                $_POST['image'] = $uploadpath;
					    $postdata = $this->common->getField('service_gallery',$_POST);
						$res = $this->common->insertData('service_gallery',$postdata);
		            }else{ 
			    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
						    $_POST['image'] = $uploadpath;
						    $postdata = $this->common->getField('service_gallery',$_POST);
							$res = $this->common->insertData('service_gallery',$postdata);
						}
					}
				}
    		}
			$this->session->set_flashdata('message','Images Added successfully');
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editServiceGallery()
    {
    	if($_POST){
	    	$id = $_POST['id'];
			unset($_POST['id']);
			if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
				$imagetmpname = $_FILES['image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['image'] = $uploadpath;
					}
				}
	        }
	        $bpost = $this->common->getField('service_gallery',$_POST);
			$res = $this->common->updateData('service_gallery',$bpost,array('id'=>$id));
			if($res)
			{
				$this->session->set_flashdata('message','Image updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Image Not Updated');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }
    

    public function addGalleryCategory()
	{
		$_POST['date'] = date('Y-m-d H:i:s');
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('gallery_category',$_POST);
		$res = $this->common->insertData('gallery_category',$bpost);
		if($res)
		{
			$this->session->set_flashdata("message",'Category Added Successfully');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editGalleryCategory()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != ""){
            $imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
			$imagetmpname = $_FILES['image']['tmp_name'];
			$uploadpath = "assets/upload-image/".$imagename;
			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
            if($compressedImage){ 
                $_POST['image'] = $uploadpath;
            }else{
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
			}
        }
        $bpost = $this->common->getField('gallery_category',$_POST);
		$res = $this->common->updateData('gallery_category',$bpost,array('id'=>$id));
		if($res)
		{
			$this->session->set_flashdata("message",'Category updated successfully.');
		}else{
			$this->session->set_flashdata("emessage",'Something Went Wrong...');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function addGallery($value='')
    {
    	if($_POST){
    		$_POST['date'] = date('Y-m-d H:i:s');
    		$_POST['projectid'] = time();
			if(isset($_FILES['feat_image']['name']) && $_FILES['feat_image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['feat_image']['name']);
				$imagetmpname = $_FILES['feat_image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['feat_image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['feat_image'] = $uploadpath;
					}
				}
	        }
			if(isset($_FILES['logo_image']['name']) && $_FILES['logo_image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['logo_image']['name']);
				$imagetmpname = $_FILES['logo_image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['logo_image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['logo_image'] = $uploadpath;
					}
				}
	        }
			if(isset($_FILES['cover_image']['name']) && $_FILES['cover_image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['cover_image']['name']);
				$imagetmpname = $_FILES['cover_image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['cover_image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['cover_image'] = $uploadpath;
					}
				}
	        }
	        $bpost = $this->common->getField('gallery_project',$_POST);
			$res = $this->common->insertData('gallery_project',$bpost);
			if($res)
			{
	    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
	    			$cccc = count($_FILES['image']['name']);
					for($prt=0; $prt<$cccc; $prt++)
					{
		    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name'][$prt]);
		    			$imagetmpname = $_FILES['image']['tmp_name'][$prt];
		    			$uploadpath = "assets/upload-image/".$imagename;
		    			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
			            if($compressedImage){ 
			                $_POST['image'] = $uploadpath;
						    $postdata = $this->common->getField('gallery',$_POST);
							$res = $this->common->insertData('gallery',$postdata);
			            }else{ 
				    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
							    $_POST['image'] = $uploadpath;
							    $postdata = $this->common->getField('gallery',$_POST);
								$res = $this->common->insertData('gallery',$postdata);
							}
						}
					}
	    		}
	    	}
			$this->session->set_flashdata('message','Project & Images Added successfully');
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editGallery()
    {
    	if($_POST){
	    	$projectid = $_POST['projectid'];
			unset($_POST['projectid']);
			if(isset($_FILES['feat_image']['name']) && $_FILES['feat_image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['feat_image']['name']);
				$imagetmpname = $_FILES['feat_image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['feat_image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['feat_image'] = $uploadpath;
					}
				}
	        }
			if(isset($_FILES['logo_image']['name']) && $_FILES['logo_image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['logo_image']['name']);
				$imagetmpname = $_FILES['logo_image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['logo_image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['logo_image'] = $uploadpath;
					}
				}
	        }
			if(isset($_FILES['cover_image']['name']) && $_FILES['cover_image']['name'] != ""){
	            $imagename = rand().'-'.str_replace(" ","-",$_FILES['cover_image']['name']);
				$imagetmpname = $_FILES['cover_image']['tmp_name'];
				$uploadpath = "assets/upload-image/".$imagename;
				$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
	            if($compressedImage){ 
	                $_POST['cover_image'] = $uploadpath;
	            }else{
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $_POST['cover_image'] = $uploadpath;
					}
				}
	        }
	        $bpost = $this->common->getField('gallery_project',$_POST);
			$res = $this->common->updateData('gallery_project',$bpost,array('projectid'=>$projectid));
			if($res)
			{
				if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
	    			$cccc = count($_FILES['image']['name']);
					for($prt=0; $prt<$cccc; $prt++)
					{
		    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name'][$prt]);
		    			$imagetmpname = $_FILES['image']['tmp_name'][$prt];
		    			$uploadpath = "assets/upload-image/".$imagename;
		    			$compressedImage = $this->compressImage($imagetmpname, $uploadpath, 70); 
			            if($compressedImage){ 
			                $_POST['image'] = $uploadpath;
						    $postdata = $this->common->getField('gallery',$_POST);
						    $postdata['projectid'] = $projectid;
							$postdata['date'] = date('Y-m-d H:i:s');
							$res = $this->common->insertData('gallery',$postdata);
			            }else{ 
				    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
							    $_POST['image'] = $uploadpath;
							    $postdata = $this->common->getField('gallery',$_POST);
							    $postdata['projectid'] = $projectid;
								$postdata['date'] = date('Y-m-d H:i:s');
								$res = $this->common->insertData('gallery',$postdata);
							}
						}
					}
	    		}
				$this->session->set_flashdata('message','Project & Images updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Project & Images Not Updated');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function setFeaturedGalleryProject()
	{
		$result = $this->common->updateData("gallery_project",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setFeaturedGalleryImage()
	{
		$result = $this->common->updateData("gallery",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setFeaturedRecipe()
	{
		$result = $this->common->updateData("recipe",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function updateGalleryProjectOrder()
	{
		if(isset($_POST['div'])){
			$data = explode(',',$_POST['div']);
			// echo "<pre>";
			// print_r ($data);
			// echo "</pre>";die;
			foreach ($data as $key => $value) {
				if($this->common->getsData("gallery_project",array("id"=>$value))){
					$this->common->updateData('gallery_project',array('item_order'=>$key+1),array("id"=>$value));
				}
			}
		}
	}

	public function updatePortfolioOrder()
	{
		if(isset($_POST['div'])){
			$data = explode(',',$_POST['div']);
			// echo "<pre>";
			// print_r ($data);
			// echo "</pre>";die;
			foreach ($data as $key => $value) {
				if($this->common->getsData("gallery",array("id"=>$value))){
					$this->common->updateData('gallery',array('item_order'=>$key+1),array("id"=>$value));
				}
			}
		}
	}

	public function addLR($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname = $_FILES['image']['tmp_name'];
    			$uploadpath = "assets/upload-image/".$imagename;
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
    		}
    		$postdata = $this->common->getField('lresource',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('lresource',$postdata);
			if($res){
				$this->session->set_flashdata('message','Learning Resource Added successfully');
			}else{
				$this->session->set_flashdata('emessage','Learning Resource Not Added');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editLR()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname = $_FILES['image']['tmp_name'];
    			$uploadpath = "assets/upload-image/".$imagename;
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $_POST['image'] = $uploadpath;
				}
    		}
			$postdata = $this->common->getField('lresource',$_POST);
			$res = $this->common->updateData('lresource',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','Learning Resource updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Learning Resource Not Updated');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function addCredential($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
    		$postdata = $this->common->getField('credentials',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('credentials',$postdata);
			if($res){
				$this->session->set_flashdata('message','Credential Added successfully');
			}else{
				$this->session->set_flashdata('emessage','Credential Not Add');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editCredential()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
			$postdata = $this->common->getField('credentials',$_POST);
			$res = $this->common->updateData('credentials',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','Credential updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Credential Not Update');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function addClient($value='')
    {
    	if($_POST){
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
    		$postdata = $this->common->getField('partners',$_POST);
    		$postdata['publish_date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('partners',$postdata);
			if($res){
				$this->session->set_flashdata('message','Baking Tool Added successfully');
			}else{
				$this->session->set_flashdata('emessage','Baking Tool Not Add');
			}
    	}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

    public function editClient()
    {
    	if($_POST){
	    	$postid = $_POST['id'];
			unset($_POST['id']);
    		if(isset($_FILES['image']['name']) && $_FILES['image']['name']!=''){
    			$imagename1 = rand().'-'.str_replace(" ","-",$_FILES['image']['name']);
    			$imagetmpname1 = $_FILES['image']['tmp_name'];
    			$uploadpath1 = "assets/upload-image/".$imagename1;
	    		if (move_uploaded_file($imagetmpname1, $uploadpath1)) {
				    $_POST['image'] = $uploadpath1;
				}
    		}
			$postdata = $this->common->getField('partners',$_POST);
			$res = $this->common->updateData('partners',$postdata,array('id'=>$postid));
			if($res){
				$this->session->set_flashdata('message','Baking Tool updated successfully');
			}else{
				$this->session->set_flashdata('emessage','Baking Tool Not Update');
			}
		}else{
    		$this->session->set_flashdata('emessage','Something Went Wrong...');
    	}
    	redirect($_SERVER['HTTP_REFERER']);
    }

	public function setFeaturedClient()
	{
		$result = $this->common->updateData("partners",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setFeaturedPromotion()
	{
		$result = $this->common->updateData("promotions",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setFeaturedTestimonial()
	{
		$result = $this->common->updateData("testimonial",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setFeaturedTeam()
	{
		$this->common->updateData("team",array('isFeatured'=>0));
		$result = $this->common->updateData("team",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setFeaturedPost()
	{
		$result = $this->common->updateData("post",array('isFeatured'=>$_POST['isFeatured']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function updateListItemOrder()
	{
		if(isset($_POST['div'])){
			//print_r($_POST['div']); die;
			$data = explode(',',$_POST['div']);
			foreach ($data as $key => $value) {
				if($this->common->getsData($_POST['table'],array("id"=>$value))){
					$this->common->updateData($_POST['table'],array('item_order'=>$key+1),array("id"=>$value));
				}
			}
		}
	}


	public function addProduct()
	{
		$productdata = $this->common->getField('products',$_POST);

		if((isset($_POST['product_price']) && $_POST['product_price']>0) && (isset($_POST['product_sale_price']) && $_POST['product_sale_price']>0 && $_POST['product_sale_price']<$_POST['product_price'])){
			$discount = ((($_POST['product_price']-$_POST['product_sale_price'])/$_POST['product_price'])*100);
			$productdata['discount'] = number_format($discount,2);
		}else{
			$productdata['discount'] = 0;
		}

		if(isset($_POST['shop_rewards']) && $_POST['shop_rewards']==1){
			$productdata['shop_rewards'] = 1;
		}else{
			$productdata['shop_rewards'] = 0;
		}

		if(isset($_POST['best_selling']) && $_POST['best_selling']==1){
			$productdata['best_selling'] = 1;
		}else{
			$productdata['best_selling'] = 0;
		}

		if(isset($_POST['new_arrival']) && $_POST['new_arrival']==1){
			$productdata['new_arrival'] = 1;
		}else{
			$productdata['new_arrival'] = 0;
		}
		
		$search_text = '';
		if(isset($_POST['product_category']) && $_POST['product_category']){
			foreach ($_POST['product_category'] as $key => $value) {
				$catname = $this->common->getsData('category',array('c_id'=>$value),'category');
				$search_text .= ' and '.$catname['category'];
			}
			$productdata['product_category'] = implode(',', $_POST['product_category']);
		}
		$productdata['search_text'] = $search_text;
		// if($_POST['product_slug']!=""){
		// 	$productdata['product_slug'] = $this->createSlug($_POST['product_slug']);
		// }else{
		// }
		$productdata['product_slug'] = $this->createSlug($_POST['product_name']);

		$productdata['product_upload_date'] = date('Y-m-d H:i:s');

		$productdata['productid'] = time();
		// $productdata['meta_keyword'] = $_POST['meta_keyword'];
		// $productdata['meta_decs'] = $_POST['meta_decs'];
		//echo "<pre>";
		//print_r($productdata); die;
		$res = $this->common->insertData('products',$productdata);
		if($res){
			if(isset($_FILES['product_photos_thumb']['name']) && $_FILES['product_photos_thumb']['name']!=''){
    			$imagename = rand().'-'.str_replace(" ","-",$_FILES['product_photos_thumb']['name']);
    			$imagetmpname = $_FILES['product_photos_thumb']['tmp_name'];
    			$uploadpath = "assets/product_image/".$imagename;
	    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
				    $p_img = $uploadpath;
				    $data = array(
				        'product_id' => $productdata['productid'],
				        'product_image' => $p_img,
				        'isThumb' => 1
				    );
		     		$res1 = $this->common->insertData('product_media',$data);
				}
    		}

		    if(isset($_FILES['product_photos']['name']) && $_FILES['product_photos']['name']){
			    $cpt = count($_FILES['product_photos']['name']);
			    for($i=0; $i<$cpt; $i++)
			    {
			    	$imagename = rand().'-'.str_replace(" ","-",$_FILES['product_photos']['name'][$i]);
	    			$imagetmpname = $_FILES['product_photos']['tmp_name'][$i];
	    			$uploadpath = "assets/product_image/".$imagename;
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $p_img = $uploadpath;
					    $data = array(
					        'product_id' => $productdata['productid'],
					        'product_image' => $p_img,
					        'isThumb' => 0
					    );
			     		$res1 = $this->common->insertData('product_media',$data);
					}
			    }
			}
			$this->session->set_flashdata('message','Product Added Successfully');
		}else{
			$this->session->set_flashdata('emessage','Product Not Add');
		}
		redirect(base_url(A."/product-list"));


	}

	public function editProduct()
	{
		
		$productid = $_POST['productid'];
		$url = $_POST['url'];
		unset($_POST['productid'],$_POST['url']);

		$productdata = $this->common->getField('products',$_POST);
		if((isset($_POST['product_price']) && $_POST['product_price']>0) && (isset($_POST['product_sale_price']) && $_POST['product_sale_price']>0 && $_POST['product_sale_price']<$_POST['product_price'])){
			$discount = ((($_POST['product_price']-$_POST['product_sale_price'])/$_POST['product_price'])*100);
			$productdata['discount'] = number_format($discount,2);
		}else{
			$productdata['discount'] = 0;
		}

		if(isset($_POST['shop_rewards']) && $_POST['shop_rewards']==1){
			$productdata['shop_rewards'] = 1;
		}else{
			$productdata['shop_rewards'] = 0;
		}

		if(isset($_POST['best_selling']) && $_POST['best_selling']==1){
			$productdata['best_selling'] = 1;
		}else{
			$productdata['best_selling'] = 0;
		}

		if(isset($_POST['new_arrival']) && $_POST['new_arrival']==1){
			$productdata['new_arrival'] = 1;
		}else{
			$productdata['new_arrival'] = 0;
		}

		$search_text = '';

		if(isset($_POST['product_category']) && $_POST['product_category']){
			foreach ($_POST['product_category'] as $key => $value) {
				$catname = $this->common->getsData('category',array('c_id'=>$value),'category');
				$search_text .= ' and '.$catname['category'];
			}
			$productdata['product_category'] = implode(',', $_POST['product_category']);
		}

		$productdata['search_text'] = $search_text;

		$productdata['product_slug'] = $this->createSlug($_POST['product_name']);

		$productdata['product_upload_date'] = date('Y-m-d H:i:s');
		// $productdata['meta_keyword'] = $_POST['meta_keyword'];
		// $productdata['meta_decs'] = $_POST['meta_decs'];
		// echo "<pre>";
		// print_r($productdata); die;
		$res = $this->common->updateData('products',$productdata,array('productid'=>$productid));
		if($res){

			if(isset($_FILES['product_photos']['name']) && $_FILES['product_photos']['name']){
			    $cpt = count($_FILES['product_photos']['name']);
			    for($i=0; $i<$cpt; $i++)
			    {
			    	$imagename = rand().'-'.str_replace(" ","-",$_FILES['product_photos']['name'][$i]);
	    			$imagetmpname = $_FILES['product_photos']['tmp_name'][$i];
	    			$uploadpath = "assets/product_image/".$imagename;
		    		if (move_uploaded_file($imagetmpname, $uploadpath)) {
					    $p_img = $uploadpath;
					    $data = array(
					        'product_id' => $productid,
					        'product_image' => $p_img
					    );
			     		$res1 = $this->common->insertData('product_media',$data);
					}
			    }
			}

			$this->session->set_flashdata('message','Product Updated Successfully');
		}else{
			$this->session->set_flashdata('emessage','Product Not Update');
		}
		redirect(base_url($url));
	}

	public function deleteproductMultiMedia()	{
		
		$image = $this->common->getsData('product_media',array('id'=>$_POST['id'],'product_image !='=>'assets/product_image'),'product_image');
		if($image['product_image'] != ""){
			if(file_exists($image['product_image'])){
				unlink($image['product_image']);
			}
		}
		$this->common->deletedata('product_media',array('id'=>$_POST['id']));
		if($this->db->affected_rows()){
			echo "1";
		}else{
			echo "0";
		} die;
	}

	public function deleteProduct()
	{
		$pid = $_POST['id'];
		$product = $this->common->getsData('products',array('productid'=>$pid));
		$this->common->deleteData('products',array('productid'=>$pid));
		if($this->db->affected_rows())
		{
			$pimage = $this->common->getData('product_media',array('product_id'=>$pid,'product_image !='=>'assets/product_image'));
			//$dir = $_POST['pimage'];
			if($pimage){
				foreach ($pimage as $key => $value) {
					$dir = $value['product_image'];
					if(is_dir($dir))
					{
						$this->rmdirRecursive($dir);
						//unlink($dir);
					}
					if(is_file($dir)){				
						unlink($dir);
					}
				}
			}
			$this->common->deleteData('product_media',array('product_id'=>$pid));
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function rmdirRecursive($dir)

	{
	    foreach(scandir($dir) as $file) {
	        if ('.' === $file || '..' === $file) continue;
	        if (is_dir("$dir/$file")) $this->rmdirRecursive("$dir/$file");
	        else unlink("$dir/$file");
	    }
	    rmdir($dir);
	}

	public function createSlug($title='')
	{
		$slug =  url_title($title);
		return $slug;
	}

	public function setProductImageThumb()
	{
		$this->common->updateData("product_media",array('isThumb'=>0),array('product_id'=>$_POST['pid']));
		$result = $this->common->updateData("product_media",array('isThumb'=>1),array('product_id'=>$_POST['pid'],'id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setBestSellingProducts()
	{
		$result = $this->common->updateData("products",array('best_selling'=>$_POST['best_selling']),array('productid'=>$_POST['productid']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setFeatProdProducts()
	{
		$result = $this->common->updateData("products",array('feat_prod'=>$_POST['feat_prod']),array('productid'=>$_POST['productid']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function setShopRewardsProducts()
	{
		$result = $this->common->updateData("products",array('shop_rewards'=>$_POST['shop_rewards']),array('productid'=>$_POST['productid']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function popupSetting()
	{
		$result = $this->common->updateData("web_setting",array('home_popup'=>$_POST['home_popup']),array('id'=>$_POST['id']));
		if($result){
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function uploadSliderImage()
	{
		$url = $_POST['rurl'];
		unset($_POST['rurl']);
		if(isset($_POST['addbanner']))
		{			
			$image=''; 

			if($_FILES['image']['name'] != ""){
	            $image = 'image';
	           	$upload_rslt = $this->do_upload($image,'assets/slider/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$image = 'assets/slider/'.$filename;
	            }
	        }

		    $_POST['image'] = $image;

			$res = $this->admin->insertCategories($_POST,'slider');

			if($res){
				$this->session->set_flashdata('message','Banner Added Successfully');
			}else{
				$this->session->set_flashdata('emessage','Banner is Not Added Please Try Again.');
			}
		}

		redirect(base_url($url));
	}

	public function updateSlider()
	{
		$sid = $_POST['id'];
		unset($_POST['id']);
		if(isset($_POST))
		{			
			$image=''; 

			if($_FILES['image']['name'] != ""){
	            $image = 'image';
	           	$upload_rslt = $this->do_upload($image,'assets/slider/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$image = 'assets/slider/'.$filename;
		    		$_POST['image'] = $image;
	            }
	        }


			$spost = $this->common->getField('slider',$_POST);
			$res = $this->common->updateData('slider',$spost,array('id'=>$sid));

			if($res){
				$this->session->set_flashdata('message','Banner Updated Successfully');
			}else{
				$this->session->set_flashdata('emessage','Banner is Not Added Please Try Again.');
			}
		}

		redirect($_SERVER['HTTP_REFERER']);
	}
	public function uploadFlexImage()
	{
		$url = $_POST['rurl'];
		unset($_POST['rurl']);
		if(isset($_POST['addflex']))
		{			
			$image=''; 

			if($_FILES['image']['name'] != ""){
	            $image = 'image';
	           	$upload_rslt = $this->do_upload($image,'assets/flex/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$image = 'assets/flex/'.$filename;
	            }
	        }

		    $_POST['image'] = $image;


			$res = $this->admin->insertCategories($_POST,'flex_image');

			if($res){
				$this->session->set_flashdata('message','Flex Image Added Successfully');
			}else{
				$this->session->set_flashdata('emessage','Flex Image is Not Added Please Try Again.');
			}
		}

		redirect(base_url($url));
	}
	public function uploadLeftImage()
	{

		$url = $_POST['rurl'];
		unset($_POST['rurl']);
		if(isset($_POST['addleft']))
		{			
			$image=''; 

			if($_FILES['image']['name'] != ""){
	            $image = 'image';
	           	$upload_rslt = $this->do_upload($image,'assets/leftimage/');
	           	if(!empty($upload_rslt['upload_data'])){ 
					$filename = $upload_rslt['upload_data']['file_name'];
					$image = 'assets/leftimage/'.$filename;
	            }
	        }

		    $_POST['image'] = $image;

             
			$res = $this->admin->insertCategories($_POST,'left_image');

			if($res){
				$this->session->set_flashdata('message','Left Image Added Successfully');
			}else{
				$this->session->set_flashdata('emessage','Left Image is Not Added Please Try Again.');
			}
		}

		redirect(base_url($url));
	}

	public function deleteSlider()
	{
		$id = $_POST['id'];
		$image= $_POST['image'];
		$table= $_POST['table'];
		$this->common->deleteData($table,array('id'=>$id));
		if($this->db->affected_rows())
		{			
			$dir = $image;
			if(is_dir($dir))
			{
				$this->rmdirRecursive($dir);
				//unlink($dir);
			}
			if(is_file($dir)){				
				unlink($dir);
			}
			echo "1";
		}else{
			echo "0";
		}die;
	}
	public function deleteFlex()
	{
		$id = $_POST['id'];
		$image= $_POST['image'];
		$table= $_POST['table'];
		$this->common->deleteData($table,array('id'=>$id));
		if($this->db->affected_rows())
		{			
			$dir = $image;
			if(is_dir($dir))
			{
				$this->rmdirRecursive($dir);
				//unlink($dir);
			}
			if(is_file($dir)){				
				unlink($dir);
			}
			echo "1";
		}else{
			echo "0";
		}die;
	}
	public function deleteleft()
	{
		 $id = $_POST['id'];
		 $image= $_POST['image'];
		 $table= $_POST['table'];

		$this->common->deleteData($table,array('id'=>$id));
		if($this->db->affected_rows())
		{			
			$dir = $image;
			if(is_dir($dir))
			{
				$this->rmdirRecursive($dir);
				//unlink($dir);
			}
			if(is_file($dir)){				
				unlink($dir);
			}
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function updateCategoryOrder()
	{
		if(isset($_POST['div'])){
			$data = explode(',',$_POST['div']);
			// echo "<pre>";
			// print_r ($data);
			// echo "</pre>";die;
			foreach ($data as $key => $value) {
				if($this->common->getsData("category",array("c_id"=>$value))){
					$this->common->updateData('category',array('item_order'=>$key+1),array("c_id"=>$value));
				}
			}
		}
	}

	public function addRewardPoint()
	{
		//print_r($_POST); die;
		if(isset($_POST))
		{
			$_POST['date'] = date('Y-m-d H:i:s');
			$res = $this->common->insertData('reward_point',$_POST);
			if($res){
				$this->session->set_flashdata('message','Reward Point Added Successfully');
			}else{
				$this->session->set_flashdata('emessage','Reward Point is Not Added Please Try Again.');
			}
		}

		redirect($_SERVER['HTTP_REFERER']);

	}

	public function editRewardPoint()
	{
		$id = $_POST['id'];
		unset($_POST['id']);
		$res = $this->common->updateData('reward_point',$_POST,array('id'=>$id));
		if($res){
			$this->session->set_flashdata('message','Reward Point Updated Successfully');
		}else{
			$this->session->set_flashdata('emessage','Reward Point is Not Updated Please Try Again.');
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function addCoupon()
	{
		//print_r($_POST); die;
		if(isset($_POST))
		{
			if($_POST['coupon_type']==1){
				if($_POST['coupon_amount']>=100){
					$this->session->set_flashdata('emessage','Coupon  % discount can not be more then 100%');
					redirect($_SERVER['HTTP_REFERER']);
				}
			}else{
				if($_POST['coupon_amount']>=$_POST['cart_amount']){
					$this->session->set_flashdata('emessage','Coupon amount can not be more then cart amount');
					redirect($_SERVER['HTTP_REFERER']);
				}
			}
			$_POST['profileid'] = $this->adminid;
			$_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_expiry_date']));
			// echo "<pre>";
			// print_r($_POST); die;
			if(isset($_POST['productid']) && $_POST['productid']){
				$_POST['productid'] = implode(',', $_POST['productid']);
			}
			$res = $this->common->insertData('coupon',$_POST);

			if($res){
				if(isset($_POST['send_newsletter']) && $_POST['send_newsletter']==1){
					$subscribers = $this->common->getData('newsletter',array(),array('email'));
					$edata['coupon_code'] = $_POST['coupon_code'];
					$edata['content'] = $_POST['content'];
					$subject = 'You got a coupon!';
                    $html = $this->load->view('email_temp/newsletter-coupon',$edata,true);
                    if($subscribers){
                    	foreach ($subscribers as $key => $value) {
                    		$email = $value['email'];
							$this->common->sendMailBySendGrid($email,'',from_email,author,$subject,$html);
                    	}
                    }
				}
				$this->session->set_flashdata('message','Coupon Added Successfully');
			}else{
				$this->session->set_flashdata('emessage','Coupon is Not Added Please Try Again.');
			}
		}

		redirect(base_url(A."/coupon-list"));

	}

	public function deleteCoupon()
	{
		$id = $_POST['id'];
		$table= $_POST['table'];
		$this->common->deleteData($table,array('id'=>$id));
		if($this->db->affected_rows())
		{	
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function orderDelete()

	{
		$table = $_POST['table'];
		unset($_POST['table']);
		$fields = $this->common->getField($table,$_POST);
		$key = key($fields);
		$this->common->deleteData($table,$fields);
		if($this->db->affected_rows())
		{
			$this->common->deleteData('cancle_order',$fields);			
			echo "1";
		}else{
			echo "0";
		}die;

	}

	/*public function updateOrderStatus()
	{
		$orderid = $_POST['orderid'];
		unset($_POST['orderid']);

		if($this->common->updateData("orders",$_POST,array("orderid"=>$orderid)))
		{
			if($_POST['order_status']!=5){
				$co = $this->common->getsData('cancle_order',array('orderid'=>$orderid));
				if($co){
					$this->common->deleteData("cancle_order",array("orderid"=>$orderid));
				}
			}
			echo 1;
		}else{
			echo 0;
		}die;
	}*/

	public function updateOrderStatus()
	{
		$result = $this->common->updateData("orders",array('order_status'=>$_POST['order_status']),array('orderid'=>$_POST['orderid']));//die;
		/*$os = $this->common->getsData('order_status_message',array('status'=>$_POST['order_status'],'orderid'=>$_POST['orderid']));
		$post['status_date'] = date('Y-m-d H:i:s');
		$post['date'] = $_POST['status_date'];
		$post['status'] = $_POST['order_status'];
		$post['link'] = $_POST['link'];
		$post['message'] = $_POST['message'];
		$post['orderid'] = $_POST['orderid'];
		if($os){
			$result = $this->common->updateData("order_status_message",$post,array('status'=>$post['status'],'orderid'=>$_POST['orderid']));
		}else{			
			$result = $this->common->insertData("order_status_message",$post);	
		}*/

		if($result){
			$order = $this->common->getsData('orders',array('orderid'=>$_POST['orderid']));
			$userdata = $this->common->getsData('user',array('profileid'=>$order['profileid']));
			$e['orderid'] = $order['invoice_no'];
			if($_POST['order_status']==8){
				$subject = "Order: ".$order['invoice_no']." is out for delivery.";
				$e['title'] = "Your order is on the way!";
				$e['content'] = "Your order has been dispatched for delivery and should arrive to your shipping address today. Forgot what you’ve ordered? View it here.";
				$e['btntext'] = "My Orders";
				$e['btnlink'] = base_url('all-orders');
				$umessage = $this->load->view('email_temp/order-status',$e,true);
				$this->common->sendMailBySendGrid($userdata['email'],'',from_email,author,$subject,$umessage);
			}else if($_POST['order_status']==6){
				$subject = "Your Order: ".$order['invoice_no']." has been refunded.";
				$e['title'] = "Your order has been refunded.";
				$e['content'] = "We’re sorry for your unfulfilled order. You may browse other similar products here.";
				$e['btntext'] = "View Products";
				$e['btnlink'] = base_url('products');
				$umessage = $this->load->view('email_temp/order-status',$e,true);
				$this->common->sendMailBySendGrid($userdata['email'],'',from_email,author,$subject,$umessage);
			}else if($_POST['order_status']==4){
				$subject = "Your Order: ".$order['invoice_no']." has been delivered.";
				$e['title'] = "Your Order is delivered!";
				$e['content'] = "Thank you for your being our valued customer. Find other products you may like? View them here.";
				$e['btntext'] = "View Products";
				$e['btnlink'] = base_url('products');
				$umessage = $this->load->view('email_temp/order-status',$e,true);
				$this->common->sendMailBySendGrid($userdata['email'],'',from_email,author,$subject,$umessage);
			}else if($_POST['order_status']==5){
				$subject = "Your Order: ".$order['invoice_no']." has been cancelled.";
				$e['title'] = "Your Order is cancelled!";
				$e['content'] = "Your Order (".$_POST['orderid'].") is Cancelled";
				$e['btntext'] = "View Products";
				$e['btnlink'] = base_url('products');
				$umessage = $this->load->view('email_temp/order-status',$e,true);
				$this->common->sendMailBySendGrid($userdata['email'],'',from_email,author,$subject,$umessage);
			}
			// echo $umessage; die;
			if($_POST['order_status']!=5){
				$co = $this->common->getsData('cancle_order',array('orderid'=>$_POST['orderid']));
				if($co){
					$this->common->deleteData("cancle_order",array("orderid"=>$_POST['orderid']));
				}
			}

			$this->session->set_flashdata("message","Order Status Updated Successfully");
		}else{
			$this->session->set_flashdata("emessage","something Went Wrong");
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function updateOrderPaymentStatus()
	{
		$result = $this->common->updateData("orders",array('payment_status'=>$_POST['payment_status']),array('orderid'=>$_POST['orderid']));
		if($result){
			$order = $this->common->getsData('orders',array('orderid'=>$_POST['orderid']));
			$userdata = $this->common->getsData('user',array('profileid'=>$order['profileid']));
			if($userdata['verify']==1){
				$yes = $this->common->getsData('point_history',array('orderid'=>$_POST['orderid'],'profileid'=>$order['profileid'],'type'=>0));
				if($yes){

				}else{
					$query = ('UPDATE  user SET `total_point` =  total_point+'.$order['earn_point'].', `remain_point` =  remain_point+'.$order['earn_point'].' WHERE `profileid` ="'.$order['profileid'].'"');
	                $this->db->query($query);
	                $reason = "Earn points on order - #".$_POST['orderid'];
	                $this->common->insertData('point_history',array('orderid'=>$_POST['orderid'],'point'=>$order['earn_point'],'profileid'=>$order['profileid'],'type'=>0,'reason'=>$reason,'date'=>date('Y-m-d H:i:s')));
				}
			}
			$data['address'] = $this->common->getsData("user_order_address",array("profileid"=>$order['profileid'],'orderid'=>$_POST['orderid']));
			$data['cart'] = $this->common->getData('cart_mapping',array('orderid'=>$_POST['orderid']));
			$data['orderid'] = $_POST['orderid'];
	        $data['currency'] = $order['payment_currency'];
	        $data['order_time'] = $order['order_time'];
	        $data['coupon'] = $order['coupon_amount'];
	        $data['firstorder'] = $order['first_order'];
	        $data['ship_charge'] = $order['delivery_charge'];
	        $data['birthday'] = $order['birthday_discount'];
	        $data['txn_id'] = $order['txn_id'];
	        $data['invoice_no'] = $order['invoice_no'];
			$umessage = $this->load->view("email_temp/order-payment-confirm",$data,true);
			// echo $umessage;die;
			$subject = "Order Payment Confirmation";
	        // $this->email->from("ben@websentials.com.sg",author);
	        // $this->email->to($userdata['email']);
	        // $this->email->subject("Order Payment Confirmation");
	        // $this->email->message($umessage);
	        // $this->email->send(); //die;
	        $res = $this->common->sendMailBySendGrid($userdata['email'],'',from_email,author,$subject,$umessage);
			$this->session->set_flashdata("message","Payment Status Updated Successfully");
		}else{
			$this->session->set_flashdata("emessage","something Went Wrong");
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function cancleOrder()
    {
    	// echo "<pre>";
    	// print_r ($_POST);
    	// echo "</pre>"; die;
    	if(isset($_POST)){
    		$od = $this->common->getsData('orders',array('orderid'=>$_POST['orderid']));
    		$status_cancle = $this->common->updateData('orders',array('order_status'=>5),array('orderid'=>$_POST['orderid']));
    		if($status_cancle){
    			$corder = $this->common->getData('cancle_order',array('orderid'=>$_POST['orderid']));
    			$_POST['cancle_by'] = "Super Admin";
    			if($corder){
    				$res = $this->common->updateData('cancle_order',$_POST,array('orderid'=>$_POST['orderid']));
    			}else{
	    			$res = $this->common->insertData('cancle_order',$_POST);
	    		}
    			if($res){
    				$usermobile = $this->common->getsData('user',array('profileid'=>$_POST['profileid']),'mobile_no,email,total_point,remain_point,withdraw_point');

    				$refund_point = $od['earn_point'];
    				$withdraw_point = $usermobile['withdraw_point']+$od['earn_point'];
    				$remain_point = $usermobile['remain_point']-$od['earn_point'];
    				$this->common->updateData('user',array('remain_point'=>$remain_point,'withdraw_point'=>$withdraw_point),array('profileid'=>$_POST['profileid']));

    				$mobile_no = $usermobile['mobile_no'];
    				$email = $usermobile['email'];

    				$umessage = "Your Order (".$_POST['orderid'].") is Cancelled because of ".$_POST['order_cancle_reson'];

    				$subject = "Your ".author." order is Cancelled with Order Id ".$_POST['orderid'];

    				$res = $this->common->sendMailBySendGrid($email,'',from_email,author,$subject,$umessage);

			        $this->session->set_flashdata("message","Order Is Cancelled");
    			}else{
    				$this->session->set_flashdata("emessage","something Went Wrong");
    			}
    		}else{
				$this->session->set_flashdata("emessage","something Went Wrong");
			}
    	}
    	redirect(base_url(A.'/cancle-order-list'));
    }

    public function ajaxDelete()
	{
		$table = $_POST['table'];
		unset($_POST['table']);
		$fields = $this->common->getField($table,$_POST);
		$key = key($fields);
		//print_r($fields);print_r($key);die;
		$this->common->deleteData($table,$fields);
		if($this->db->affected_rows())
		{
			$dir = $_POST['image'];
			//echo $dir;
			if(is_dir($dir))
			{
				$this->rmdirRecursive($dir);
				//unlink($dir);
			}
			if(is_file($dir)){
				unlink($dir);
			}
			echo "1";
		}else{
			echo "0";
		}die;
	}

	public function orderReport()
	{
		$data['result'] = $this->admin->orderReportSearch($_POST);
		$order_status = $this->common->getData("order_status",array(),array(),array("field"=>"ob","by"=>"asc"));
		$data['order_status'] = array_column($order_status, "order_status_name","os_id");
		$this->loadAdminHtml('order-report','Order Report',$data);
	}

	public function downloadProductExcel()
	{
		header("Content-Type: application/csv");
		header("Content-Disposition: attachment; filename=product-list.csv");
		header("Pragma: no-cache");
		header("Expires: 0");

		$handel = fopen("php://output","w");
		fputcsv($handel,array("Id","Product Name","SKU","Regular Price","Sale Price","Stock","Category"));
		$query = explode("limit", $this->session->userdata("product_excel"));
        $query = $query[0];
        $result = $this->db->query($query)->result_array();
		if($result){
			foreach($result as $key => $value) {
				$cat = explode(',',$value['product_category']);
				$pcat = array();
				if($cat){
					foreach ($cat as $ckey => $cvalue) {
						$category = $this->common->getsData('category',array('c_id'=>$cvalue),'category');
						if(isset($category) && $category){
							array_push($pcat, $category['category']);
						}
					}
				}
				$cat = implode(' | ', $pcat);
				fputcsv($handel,array($value['pid'],$value['product_name'],$value['product_sku'],$value['product_price'],$value['product_sale_price'],$value['product_stock'],$cat));
			}
		}
		fclose($handel);
		return true;
	}

	public function downloadCouponExcel()
	{
		header("Content-Type: application/csv");
		header("Content-Disposition: attachment; filename=coupon-list.csv");
		header("Pragma: no-cache");
		header("Expires: 0");

		$handel = fopen("php://output","w");
		fputcsv($handel,array("Coupon Code","Coupon Type","Amount","Quantity","Cart Amount","Coupon Date","Expiry Date"));
        $result = $this->common->getData('coupon',array('profileid'=>$this->adminid),array(),array('field'=>'id','by'=>'desc'));
		if($result){
			foreach($result as $key => $value) {
				$ct = (($value['coupon_type']==0)?'$':'%');
				fputcsv($handel,array($value['coupon_code'],$ct,$value['coupon_amount'],$value['coupon_quantity'],$value['cart_amount'],$value['coupon_current_date'],$value['coupon_expiry_date']));
			}
		}
		fclose($handel);
		return true;
	}

	public function orderInvoiceExcelOld()
	{

		$this->load->dbutil();
        $this->load->helper('file');
        $this->load->helper('download');
        $delimiter = ",";
        $newline = "\r\n";
        $filename = "order_invoice.csv";
        $query = explode(" limit", $this->session->userdata("order_invoice"));
        $query = $query[0];
        $query1 = str_replace("`O`.*, `UOA`.*, `OS`.`order_status_name`, `U`.`name`", "`O`.`orderid`,`O`.`order_time`,`O`.`quantity`,`O`.`grandtotal`,`O`.`payment_status`,`O`.`order_by`,`UOA`.`bname`, `UOA`.`bmobile_no`, `UOA`.`bstate`, `UOA`.`bcity`, `UOA`.`baddress1`, `UOA`.`bemail`, `PM`.`payment_method_name`, `OS`.`order_status_name`", $query);
        $result = $this->db->query($query1);
        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
        force_download($filename, $data);
        redirect(base_url(A."/order-list"));
	}

	public function orderInvoiceExcel()
	{
		header("Content-Type: application/csv");
		header("Content-Disposition: attachment; filename=order_invoice.csv");
		header("Pragma: no-cache");
		header("Expires: 0");

		$handel = fopen("php://output","w");
		fputcsv($handel,array("Invoice_No","Order_Time","Product","quantity","Sub_Total","Discount","Grand_Total","Payment Method","Payment Status","Full Name","Email","Mobile_No","Billing_Address","Billing_Postal_Code","Shipping_Address","Shipping_Postal_Code","Order Status"));
		$query = explode(" limit", $this->session->userdata("order_invoice"));
        $query = $query[0];
        $result = $this->db->query($query)->result_array();
		if($result){
			$order_status = $this->config->item("order_status");
			foreach($result as $key => $value) {
				// echo "<pre>";
				// print_r ($value);
				// echo "</pre>"; die;
				$cart = $this->common->getData('cart_mapping',array('orderid'=>$value['orderid']));
				$psku = array();
				$pqty = array();
				if($cart){
					foreach ($cart as $ckey => $cvalue) {
						$product = $this->common->getsData('products',array('productid'=>$cvalue['productid']),'product_sku');
						if(isset($product) && $product){
							array_push($psku, $product['product_sku']);
							array_push($pqty, $cvalue['qty']);
						}
					}
				}
				$sku = implode(' | ', $psku);
				$qty = implode(' | ', $pqty);
				if($value['payment_method']==1 || $value['payment_method']=='COD'){
                    $pm = "COD";
                }else if($value['payment_method']==2 || $value['payment_method']=='paynow'){
                    $pm = "PayNow";
                }else if($value['payment_method']==3 || $value['payment_method']=='omise'){
                    $pm = "Omise";
                }else{
                	$pm = "COD";
                }
				$os = (array_key_exists($value['order_status'], $order_status)?$order_status[$value['order_status']]:"");
				$discount = $value['first_order']+$value['birthday_discount']+$value['coupon_amount'];
				$address = $this->common->getsData('user_order_address',array('orderid'=>$value['orderid']));
				fputcsv($handel,array($value['invoice_no'],$value['order_time'],$sku,$qty,$value['subtotal'],$discount,$value['grandtotal'],$pm,$value['payment_status'],$address['bname'],$address['bemail'],$address['bmobile_no'],$address['baddress1'],$address['bpincode'],$address['saddress1'],$address['spincode'],$os));
			}
		}
		fclose($handel);
		return true;
	}

	public function orderInvoiceExcelReportOld()
	{

		$this->load->dbutil();
        $this->load->helper('file');
        $this->load->helper('download');
        $delimiter = ",";
        $newline = "\r\n";
        $filename = "order_invoice.csv";
        $query = explode(" limit", $this->session->userdata("order_search"));
        $query = $query[0];
        $query1 = str_replace("`O`.*, `UOA`.*, `OS`.`order_status_name`, `U`.`name`", "`O`.`orderid`,`O`.`order_time`,`O`.`quantity`,`O`.`grandtotal`,`O`.`payment_status`,`O`.`order_by`,`UOA`.`bname`, `UOA`.`bmobile_no`, `UOA`.`bstate`, `UOA`.`bcity`, `UOA`.`baddress1`, `UOA`.`bemail`, `PM`.`payment_method_name`, `OS`.`order_status_name`", $query);
        $result = $this->db->query($query1);
        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
        force_download($filename, $data);
        redirect(base_url(A."/order-list"));
	}

	public function orderInvoiceExcelReport()
	{
		header("Content-Type: application/csv");
		header("Content-Disposition: attachment; filename=order_invoice.csv");
		header("Pragma: no-cache");
		header("Expires: 0");

		$handel = fopen("php://output","w");
		fputcsv($handel,array("Invoice_No","Order_Time","Product","quantity","Sub_Total","Discount","Grand_Total","Payment Method","Payment Status","Full Name","Email","Mobile_No","Billing_Address","Billing_Postal_Code","Shipping_Address","Shipping_Postal_Code","Order Status"));
		$query = explode(" limit", $this->session->userdata("order_search"));
        $query = $query[0];
        $result = $this->db->query($query)->result_array();
		if($result){
			$order_status = $this->config->item("order_status");
			foreach($result as $key => $value) {
				// echo "<pre>";
				// print_r ($value);
				// echo "</pre>"; die;
				$cart = $this->common->getData('cart_mapping',array('orderid'=>$value['orderid']));
				$psku = array();
				$pqty = array();
				if($cart){
					foreach ($cart as $ckey => $cvalue) {
						$product = $this->common->getsData('products',array('productid'=>$cvalue['productid']),'product_sku');
						array_push($psku, $product['product_sku']);
						array_push($pqty, $cvalue['qty']);
					}
				}
				$sku = implode(' | ', $psku);
				$qty = implode(' | ', $pqty);
				if($value['payment_method']==1 || $value['payment_method']=='COD'){
                    $pm = "COD";
                }else if($value['payment_method']==2 || $value['payment_method']=='paynow'){
                    $pm = "PayNow";
                }else if($value['payment_method']==3 || $value['payment_method']=='omise'){
                    $pm = "Omise";
                }else{
                	$pm = "COD";
                }
				$os = (array_key_exists($value['order_status'], $order_status)?$order_status[$value['order_status']]:"");
				$discount = $value['first_order']+$value['birthday_discount']+$value['coupon_amount'];
				$address = $this->common->getsData('user_order_address',array('orderid'=>$value['orderid']));
				fputcsv($handel,array($value['invoice_no'],$value['order_time'],$sku,$qty,$value['subtotal'],$discount,$value['grandtotal'],$pm,$value['payment_status'],$value['name'],$address['bemail'],$value['mobile_no'],$address['baddress1'],$address['bpincode'],$address['saddress1'],$address['spincode'],$os));
			}
		}
		fclose($handel);
		return true;
	}

	public function downloadOrderInvoicePdfZip()
	{
		// print_r($_GET['orderid']); die;
		$this->deleteFiles('assets/pdf/*');
        $this->load->library('zip');
		$allids = explode(',', $_GET['orderid']);

		foreach ($allids as $key => $value) {
			//print_r($value);
			$invoice = $this->admin->getOrders($value,1);
			$order_status = $this->common->getData("order_status");
			$cart = $this->common->getData("cart_mapping",array("orderid"=>$invoice['orderid']),array(),array(),array("field"=>"cmid","by"=>"asc"));

			$this->load->library('pdf');
			$pdfhtml = $this->load->view('order-invoice-pdf',compact("invoice","order_status","cart"),true);
			//print_r($pdfhtml); die;
			$filepath = "assets/pdf/" . $value .".pdf";
			$this->pdf->savePdf($pdfhtml,'order-invoice-pdf',$filepath);
		}
		$this->zip->read_dir(FCPATH."assets/pdf/",FALSE);
		$this->zip->download('invoce-pdf'.date('Y-m-d').'.zip');die;
	}

	public function downloadOrderInvoicePdf()
	{
		// print_r($_GET['orderid']); die;
		$allids = $_GET['orderid'];

			$invoice = $this->admin->getOrders($_GET['orderid'],1);
			$order_status = $this->common->getData("order_status");
			$cart = $this->common->getData("cart_mapping",array("orderid"=>$invoice['orderid']),array(),array(),array("field"=>"cmid","by"=>"asc"));

			$this->load->library('pdf');
			$pdfhtml = $this->load->view('order-invoice-pdf',compact("invoice","order_status","cart"),true);
			//print_r($pdfhtml); die;
			$this->pdf->create($pdfhtml,'order-invoice-pdf');
	}

	public function deleteFiles($path='')
	{
		if($path != "") {
			$files = glob(FCPATH.$path); // get all file names
	        foreach($files as $file){ // iterate files
	          if(is_file($file))
	            unlink($file); // delete file
	        }
		}
	}

	public function downloadGstReportStateWise()
	{
			$where = array();
			if(isset($_GET['date']) && $_GET['date']!=''){
				$where['date'] = $_GET['date'];
			}
			if(isset($_GET['category']) && $_GET['category']!=''){
				$where['category'] = $_GET['category'];
			}

			$gst = $this->admin->calculateGst($where);

			$this->load->library('pdf');
			$pdfhtml = $this->load->view('gst-state-pdf',compact("gst"),true);
			//print_r($pdfhtml); die;
			$this->pdf->create($pdfhtml,'gst-calculate-pdf');
	}

	public function downloadUserCsv()
	{
		header("Content-Type: application/csv");
		header("Content-Disposition: attachment; filename=users.csv");
		header("Pragma: no-cache");
		header("Expires: 0");

		$handel = fopen("php://output","w");
		// fputcsv($handel,array("id","Name","Birth Date","Mobile Number","Email","Password","Newsletter Consent","Reg. Date"));
		fputcsv($handel,array("id","Name","Mobile Number","Email","Password","Reg. Date"));
		$user = $this->common->getData('user',array('user_type'=>'register_user'));
		if($user){
			foreach($user as $key => $value) {
				// if($value['total_point']>500){
                //    $level = "Gold";
                // }else if($value['total_point']>300 && $value['total_point']<=500){
                //     $level = "Silver";
                // }else{
                //     $level = "Bronze";
                // }
				// $newsletter = ($value['newsletter']==1)?'Yes':'No';
				// fputcsv($handel,array($value['profileid'],$value['name'],$value['dob'],$value['mobile_no'],$value['email'],$value['plain_password'],$newsletter,$value['reg_date']));
				fputcsv($handel,array($value['profileid'],$value['name'],$value['mobile_no'],$value['email'],$value['plain_password'],$value['reg_date']));
			}
		}
		fclose($handel);
		return true;
	}

	public function downloadProductCsvFormat()
	{
		header("Content-Type: application/csv");
		header("Content-Disposition: attachment; filename=product-upload.csv");
		header("Pragma: no-cache");
		header("Expires: 0");

		$handel = fopen("php://output","w");
		fputcsv($handel,array("id","product_name","product_sku","product_price","product_sale_price","product_stock","product_description","product_category","size","product_tag","product_status"));
		/*$products = $this->common->getData('products');
		if($products){
			foreach($products as $key => $value) {
				if($value['p_image']!=''){
					$imgname = explode('/', $value['p_image']);
					$imgname = end($imgname);
				}else{
					$imgname = '';
				}
				fputcsv($handel,array($value['product_name'],$value['product_tag'],$value['product_category'],$value['product_brand'],$value['product_gst'],$imgname,$value['product_sku'],$value['p_shortdescription'],$value['p_price'],$value['p_saleprice'],$value['showDetail'],$value['p_stock']));
			}
		}*/
		fclose($handel);
		return true;
	}

	public function importCsv(){
	  	$filename=$_FILES["csv"]["tmp_name"];
	  	if($_FILES["csv"]["size"] > 0)
	    {
	      	$file = fopen($filename, "r");
	      	$count=10000;
	      	$fr = 0;
	      	//echo "<pre>"; print_r($file); die;
	       	while (($importdata = fgetcsv($file, 10000, ",")) !== FALSE)
	       	{
	       		if($fr>0){
	       			$productid=md5(uniqid('wyz',''));
	       			$slug = $this->createSlug($importdata[1]);	       			
	       			if((isset($importdata[3]) && $importdata[3]!="") && (isset($importdata[4]) && $importdata[4]!="")){
						$dis = ((($importdata[3]-$importdata[4])/$importdata[3])*100);
						$discount = number_format($dis,2);
					}else{
						$discount = 0;
					}
	              	$csvdata = array(
	              	  'productid' => $productid,
	                  'product_name' => $importdata[1],
	                  'product_slug' =>$slug,
	                  'product_sku' =>$importdata[2],
	                  'product_price' =>$importdata[3],
	                  'product_sale_price' =>$importdata[4],
	                  'product_stock' =>$importdata[5],
	                  'product_description' =>$importdata[6],
	                  'product_category' =>$importdata[7],
	                  'size' =>$importdata[8],                 
	                  'product_upload_date' =>date('Y-m-d H:i:s'),                
	                  'product_tag' =>$importdata[9],                  
	                  'type' =>0,                  
	                  'best_selling' =>0,                  
	                  'feat_prod' =>0,                  
	                  'discount' =>$discount                  
	                );

					//echo "<pre>"; print_r($csvdata); die;

	               $insert = $this->common->insertData('products',$csvdata);
 
				}
					$count++;
					$fr++;
	       	}  
	       	      //die;                  
	      	fclose($file);
	      	 
				$this->session->set_flashdata('message', 'Data are imported successfully..');
		}else{
				$this->session->set_flashdata('message', 'Something went wrong..');
	    	}
		redirect($_SERVER['HTTP_REFERER']);
	}
	public function deleteMultipleProduct()
	{
		$pid = $_POST['productids'];
		$productids = explode(',', $pid);
		//print_r($productids); die;
		if($productids){
			foreach ($productids as $key => $value) {
				$product = $this->common->getsData('products',array('productid'=>$value));
				$this->common->deleteData('products',array('productid'=>$value));
				if($this->db->affected_rows())
				{
					$pimage = $this->common->getData('product_media',array('product_id'=>$value,'product_image !='=>'assets/product_image'));
					//$dir = $_POST['pimage'];
					if($pimage){
						foreach ($pimage as $key => $value1) {
							$dir = $value1['product_image'];
							if(is_dir($dir))
							{
								$this->rmdirRecursive($dir);
								//unlink($dir);
							}
							if(is_file($dir)){				
								unlink($dir);
							}
						}
					}
					$this->common->deleteData('product_media',array('product_id'=>$value));
				}
			}
		}
	}

	public function sendMailToNewsletterSubsciber()
	{
		if(isset($_GET['productid']) && $_GET['productid']){
			$user = $this->common->getData("newsletter");
			$data['product'] = $this->common->getsData('products',array('productid'=>$_GET['productid']));
			$data['pimage'] = $this->common->getsData('product_media',array('product_id'=>$_GET['productid'],'isThumb'=>1));
			if($user){
				foreach ($user as $key => $value) {
					$email = $value['email'];
					$html = $this->load->view('email_temp/newsletter-product-email',$data,true);
					// print_r ($html); die;
					$subject = 'Exclusive Offer';
					$this->common->sendMailBySendGrid($email,'',from_email,author,$subject,$html);
				}
			}
		}
		$this->session->set_flashdata("message","Mail Send Successfully");
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function sendInstantMail()
	{
		if(isset($_POST['message']) && $_POST['message']!=''){
			$subject = ($_POST['subject']!='')?$_POST['subject']:'Welcome to '.author;
			$userid = explode(',', $_POST['ids']);
			// echo "<pre>";
			// print_r ($userid);
			// echo "</pre>";
			if($userid){
				foreach ($userid as $key => $value) {
					$user = $this->common->getsData('newsletter',array('id'=>$value),array('email'));
					$email = $user['email'];
					$html = $_POST['message'];
					$html .= "<br>";
					$html .= 'If you wish to opt out of all type of emails, click <a href="'.base_url('unsubscribeNewsletter?info='.base64_encode($user['email'])).'">Unsubscribe</a>.';
					// print_r ($user); die;
					$this->common->sendMailBySendGrid($email,'',from_email,author,$subject,$html);
				}
			}
			$this->session->set_flashdata("message","Mail Send Successfully");
		}else{
			$this->session->set_flashdata("emessage","Message is required");
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function editOrderAdminCommentAction()
	{
		if($_POST){
			$res = $this->common->updateData('orders',array($_POST['name']=>$_POST['value']),array('id'=>$_POST['pk']));
		}
	}

	public function updateOrderComment()
	{
		if($_POST){
			$res = $this->common->updateData('orders',array('admin_comment'=>$_POST['admin_comment']),array('id'=>$_POST['id']));
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	public function getSubCatByCategory()
	{
		$cat = $this->common->getData('int_category',array('parent'=>$_POST['cid']),array(),array('field'=>'item_order','by'=>'asc'));
		$html = '<option value="">Select</option>';
		foreach ($cat as $key => $value) {
			$html .= '<option value="'.$value['id'].'">'.$value['category'].'</option>';
		}
		echo $this->common->jsonEncode(array('html'=>$html));
	}
        
}