<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
//Mahek Admin
class Admin extends MY_Controller { 
  function __construct(){
        parent::__construct();
		$this->load->library('pagination');
		if(!$this->session->userdata("admin")){redirect("home/admin");}	
		error_reporting(0);$this->load->library('email');
    }
	
	public function influ_report($id){
		
	}	
	
	public function db_backup(){
		
	}
	
	public function site_backup(){
		
	}
	
	public function influ_excel(){
        // create file name
        $fileName = 'data-'.time().'.xlsx';  
        // load excel library
        $this->load->library('excel');
       
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        // set Header
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Name');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Mobile');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Email');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Code');
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'Discount%'); 
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'Margin%');        
        // set Row
        $rowCount = 2;
		$listInfo = $this->db->get('influs')->result();
        foreach ($listInfo as $list) {
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $list->influ_name);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $list->influ_mob);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, $list->influ_email);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, $list->influ_code);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $list->influ_discount);
            $rowCount++;
        }
        $filename = "tutsmake". date("Y-m-d-H-i-s").".csv";
        header('Content-Type: application/vnd.ms-excel'); 
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0'); 
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');  
        $objWriter->save('php://output'); 
 
    }
     
	
	public function send_mail(){
		///echo "<pre>";print_r($_POST);exit;
		$mail_users=array();
		if($_POST['users']=='Customers'){
			$users=$this->db->get("users")->result();
			foreach($users as $u){
				array_push($mail_users,$u->email);	
			}
		}else if($_POST['users']=='Influencer'){
			$users=$this->db->get("influs")->result();
			foreach($users as $u){
				array_push($mail_users,$u->influ_email);	
			}
		}else if($_POST['users']=='Centers'){
			$users=$this->db->get("emps")->result();
			foreach($users as $u){
				array_push($mail_users,$u->email);	
			}
		}
		//$moremails
		
		//$users=implode(",",$mail_users);
		//echo "<pre>";print_r($users);exit;
		$sent=0;$not_sent=0;
		foreach($users as $u){
		$to = $u;//.','.$_POST['email'];
		$subject =$_POST['subject'];
		
		// Always set content-type when sending HTML email
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
		
		// More headers
		$headers .= 'From: info@y1electronics.in';
		
		if(mail($to,$subject,$_POST['messsage'],$headers)==true){
			$sent++;
		}else{
			$not_sent++;
			// $this->session->set_flashdata('msg', '<div class="alert alert-success">Mail couldnot be sent.</div>');	
		}
		}
		if($_POST['email']!=''){
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
		
		// More headers
		$headers .= 'From: info@y1electronics.in';
		
		if(mail($_POST['email'],$subject,$_POST['messsage'],$headers)==true){
			$sent++;
		}else{
			$not_sent++;
		}
		}
		$this->session->set_flashdata('msg', '<div class="alert alert-success">$sent Mails Sent Successfully. $not_sent Mails couldnot be Sent. </div>');	
		redirect("admin/mails");
	}
	
	public function testmail(){
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
		
		// More headers
		$headers .= 'From: info@y1electronics.in';
		
		if(mail('satshl3112@gmail.com','Test Subject','<h1>Hello</h1>',$headers)==true){
			echo 1;
		}else{
			 echo 0;
		}
	}

	public function profile(){
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/profile',$data,true);
		$this->adminlayout();
	}
	
	public function mails(){
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/mails',$data,true);
		$this->adminlayout();
	}
	
	public function pre_book_status_update(){
		$this->db->where("pre_bid",$_POST['id']);
		$this->db->update("pre_booking",array("pre_status"=>$_POST['v']));
	}
	
	public function pre_book_remark_update(){
		$this->db->where("pre_bid",$_POST['id']);
		$this->db->update("pre_booking",array("pre_bremarks"=>$_POST['v']));
	}
	
	public function bookings($type=false){
		$this->db->select("*");
		$this->db->from("pre_booking");
		$this->db->join("products","products.pid=pre_booking.pre_pid","left");
		$this->db->where("pre_booking.pre_pay_status","SUCCESS");
		if($type==true){
			$this->db->where("pre_booking.pre_status",$type);
		}else{
			$this->db->where("pre_booking.pre_status","");
		}
		$this->db->order_by("pre_booking.pre_bid","desc");
		$data['books']=$this->db->get()->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/bookings',$data,true);
		$this->adminlayout();
	}
	
	public function blogs(){
		$data['blogs']=$this->db->get("blogs")->result();///array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/blogs',$data,true);
		$this->adminlayout();
	}
	
	public function blog_delete(){
		$this->db->delete("blogs",array("blog_id"=>$_POST['id'])) ;
 	}
	
	
	public function lab_tests(){

		if($_GET['test_id']){

		$data['edit']=$this->db->get_where("lab_tests",array("test_id"=>$_GET['test_id']))->row();

		}

		$this->db->order_by("test_name","asc");
		$data['tests']=$this->db->get("lab_tests")->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/lab_tests',$data,true);

		$this->adminlayout();	
	}
	
	public function add_test(){
		//echo "<pre>";print_R($_POST);exit;
		$test_img="test.jpg";
		if(!empty($_FILES["test_img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('test_img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$test_img=$pic['file_name'];

				}

		}  
		if($this->db->insert("lab_tests",array("test_img"=>$test_img,"test_name"=>$_POST['test_name'],"test_desc"=>$_POST['test_desc'],"test_price"=>$_POST['test_price']))==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Test Added Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Test couldnot be added.</div>');	
		}redirect("admin/lab_tests");
	}
	
	public function update_test(){
		$test_img=$_POST['oldtest_img'];

		if(!empty($_FILES["test_img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('test_img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$test_img=$pic['file_name'];

				}

		}  
		$this->db->where("test_id",$_POST['test_id']);
		if($this->db->update("lab_tests",array("test_img"=>$test_img,"test_name"=>$_POST['test_name'],"test_desc"=>$_POST['test_desc'],"test_price"=>$_POST['test_price']))==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Test Details Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Test Details couldnot be Updated.</div>');	
		}redirect("admin/lab_tests");
	}
	
	public function products_list(){

		
		$data=array();//['prods']=$this->db->get()->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/products_list',$data,true);

		$this->adminlayout();	
	}
	
	public function add_medprod(){
		//echo "<pre>";print_R($_POST);exit;
		$prod_img="prod.jpg";
		if(!empty($_FILES["prod_img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('prod_img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$prod_img=$pic['file_name'];

				}

		}  
		if($this->db->insert("med_prods",array("prod_img"=>$prod_img,"prod_title"=>$_POST['prod_title'],"prod_price"=>$_POST['prod_price'],"prod_desc"=>$_POST['prod_desc'],"prod_cat"=>$_POST['prod_cat']))==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Product Added Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Product couldnot be added.</div>');	
		}redirect("admin/products_list");
	}
	
	public function update_medprod(){
		$prod_img=$_POST['oldprod_img'];

		if(!empty($_FILES["prod_img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('prod_img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$prod_img=$pic['file_name'];

				}

		}  
		$this->db->where("prod_id",$_POST['prod_id']);
		if($this->db->update("med_prods",array("prod_img"=>$prod_img,"prod_title"=>$_POST['prod_title'],"prod_price"=>$_POST['prod_price'],"prod_desc"=>$_POST['prod_desc'],"prod_cat"=>$_POST['prod_cat']))==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Product Details Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Product Details couldnot be Updated.</div>');	
		}redirect("admin/products_list");
	}
	

	
	public function staff_reports($id){
		$data['staff']=$this->db->get_where("emps",array("uid"=>$id))->row();
		
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/staff_reports',$data,true);
		$this->adminlayout(); 
	}
	
	public function influ_payments($id){
		$fileName = 'data-'.time().'.xlsx';  
        // load excel library
        $this->load->library('excel');
       
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        // set Header
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'S.No.');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Order.No.');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'OrderDate');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Customer Name'); 
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'Order Total');
        $objPHPExcel->getActiveSheet()->SetCellValue('F1', 'Order Discount');    
        $objPHPExcel->getActiveSheet()->SetCellValue('G1', 'Influ Margin');     
        // set Row
        $rowCount = 2;$i=1;
		
		$this->db->select("*");
		$this->db->from('orders');
		$this->db->where("orders.oinflu_id",$id);
		//$this->db->where("orders.ostatus",'Completed');
		$this->db->order_by("orders.oid","desc");
		$orders=$this->db->get()->result();
		$influ=$this->db->get_where("influs",array("influ_id"=>$id))->row();
        foreach ($orders as $list) {
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $i);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $list->order_uid);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, date("d M Y",strtotime($list->odate)));
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, $list->bname);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $list->ototal-$list->odis);
            $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, $list->odis);
            $objPHPExcel->getActiveSheet()->SetCellValue('G' . $rowCount, $list->grand_total*$influ->influ_margin/100);
            $rowCount++;$i++;
        }
        $filename = "tutsmake". date("Y-m-d-H-i-s").".csv";
        header('Content-Type: application/vnd.ms-excel'); 
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0'); 
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');  
        $objWriter->save('php://output'); 
	}
	
	public function influ_orders($id){
		$this->db->select("*");
		$this->db->from('orders');
		$this->db->where("orders.oinflu_id",$id);
		//$this->db->where("orders.ostatus",'Completed');
		$this->db->order_by("orders.oid","desc");
		$data['orders']=$this->db->get()->result();
		$data['influ']=$this->db->get_where("influs",array("influ_id"=>$id))->row();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/influ_orders',$data,true);
		$this->adminlayout(); 	
	}
	
	public function dsell_excel($id) {
        // create file name
        $fileName = 'data-'.time().'.xlsx';  
        // load excel library
        $this->load->library('excel');
       
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        // set Header
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'S.No.');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Order No');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Customer');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Phone');
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', 'Sub Total'); 
        $objPHPExcel->getActiveSheet()->SetCellValue('F1', 'Discount');     
        $objPHPExcel->getActiveSheet()->SetCellValue('G1', 'Grand Total');        
        // set Row
        $rowCount = 2;
		
		$this->db->select("*");
		$this->db->from('orders');
		$this->db->where("orders.admin_id",$id);
		$this->db->order_by("orders.oid","desc");
		$listInfo=$this->db->get()->result();
		///echo "<pre>";print_r($data);exit;
		$i=1;
        foreach ($listInfo as $list) {
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $i);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $list->order_uid);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, $list->bname);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, $list->bphone);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $list->ototal-$list->odis);
            $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, $list->odis);
            $objPHPExcel->getActiveSheet()->SetCellValue('G' . $rowCount, $list->grand_total);
            $rowCount++;$i++;
        }
        $filename = "tutsmake". date("Y-m-d-H-i-s").".csv";
        header('Content-Type: application/vnd.ms-excel'); 
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0'); 
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');  
        $objWriter->save('php://output'); 
 
    }
	
	public function dist_sells($id){
		$this->db->select("*");
		$this->db->from('orders');
		$this->db->where("orders.admin_id",$id);
		$this->db->order_by("orders.oid","desc");
		$data['orders']=$this->db->get()->result();
		$data['emp']=$this->db->get_where('emps',array("uid"=>$id))->row();
		///echo "<pre>";print_r($data);exit;
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/dist_sells',$data,true);
		$this->adminlayout(); 	
	}
	
	public function staff($brid=false){
		if($brid==true){
			$this->db->select("*");
			$this->db->from("emps");
			//$this->db->join("branches","branches.br_id=agents.brid");
			$this->db->where("uid",$brid);
			$data['edit']=$this->db->get()->row();
		}
		$this->db->select("*");
		$this->db->from("emps");
		$this->db->join("cities","cities.city_id=emps.emp_state","left");
		//$this->db->order_by("agents.ag_id","desc");
		$data['emps']=$this->db->get()->result();
		
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/add_employee',$data,true);
		$this->adminlayout();
	}
	
	public function add_city(){
		if($this->db->insert("cities",array("city_name"=>$_POST['city_name'],"city_state"=>$_POST['ag_state']))==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">City Added Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">City couldnot be added.</div>');	
		}redirect("admin/cities");
	}
	
	public function update_city(){
		
		$this->db->where("city_id",$_POST['city_id']);
		if($this->db->update("cities",array("city_name"=>$_POST['city_name'],"city_state"=>$_POST['state_id']))==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">City Updated Successfully.</div>');	
		}else{
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">City couldnot be Updated.</div>');	
		}redirect("admin/cities");
	}
	
	public function ajax_city_delete(){
		$this->db->delete("cities",array("city_id"=>$_POST['id']));
	}
	public function ajax_app_delete(){
		$this->db->delete("apps",array("app_id"=>$_POST['id']));
	}
	
	public function ajax_test_delete(){
		$this->db->delete("lab_tests",array("test_id"=>$_POST['id']));
	}
	public function ajax_prod_delete(){
		$this->db->delete("products",array("pid"=>$_POST['id']));
	}
	
	public function areas($id,$edit=false){
		$this->db->select("*");
		$this->db->from("city_areas");
		$this->db->where("city_id",$id);
		$data['city_areas']=$this->db->get()->result();
		if($edit==true){
		$data['edit']=$this->db->get_where("city_areas",array("area_id"=>$edit))->row();
		}
		$data['city']=$this->db->get_where("cities",array("city_id"=>$id))->row();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/areas',$data,true);
		$this->adminlayout();
	}
	
	public function add_money_submit(){

		parse_str($_POST['formdata'],$form);
		//print_r($form);exit;

		$this->db->order_by("wid","desc");

		$chk=$this->db->get_where("wallet",array("did"=>$form['user']));

			if($chk->num_rows()>0){

				$l=$chk->row();

				//print_r($l);

				$wallet=$l->wallet_amt;}else{$wallet=0;}

				if($form['type']=="Credit"){

					$newbal=$wallet+$form['amount'];
					$tr_desc="Deposite";

				}else{

					$newbal=$wallet-$form['amount'];
					$tr_desc="Withdrawal";

				}

				if($this->db->insert("wallet",array("trans_remarks"=>$form['trans_remarks'],"wallet_staff_id"=>$form['staff_id'],"wallet_state_id"=>$form['wallet_state_id'],"pay_month"=>date("M-y"),"pay_year"=>date("Y"),"trans_amt"=>$form['amount'],"trans_type"=>$form['type'],"trans_date"=>date("Y-m-d"),"wallet_amt"=>$newbal,"did"=>$form['user']))==true){echo "Balance Updated";
				//if($form['depid']){
//					$this->db->where("depid",$form['depid']);
//					$this->db->update("deposites",array("admin_remarks"=>$form['remarks'],'dep_status'=>'Approved'));
//					
//					
//				}
//				if($form['wid']){
//					$this->db->where("wid",$form['wid']);
//					$this->db->update("withdrawls",array("remarks"=>$form['remarks'],'req_status'=>'Approved'));
//					
//				}
				}else{echo "Balance Could not be updated.";}

	}
	
	public function user_wallet(){
		//echo $_POST['id'];exit;
		$data['user']=$this->db->get_where("agents",array("ag_id"=>$_POST['id']))->row();
		//print_r($data);exit;
		$this->load->view("admin/wallet",$data);	
	}
	
	public function appr_dist(){
		$this->db->select("*");
		$this->db->from("agents");
		$this->db->join("emps","emps.uid=agents.staff_id","left");
		$this->db->join("cities","cities.city_id=agents.ag_city","left");
		$this->db->join("states","states.state_id=agents.ag_state","left");
		$this->db->where("agents.kyc_approve","Approved");
		$this->db->order_by("agents.ag_id","desc");
		$data['agents']=$this->db->get()->result();
		
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/appr_dist',$data,true);
		$this->adminlayout();
	}
	
	
	
	public function distributors($brid=false){
		if($brid==true){
			$this->db->select("*");
			$this->db->from("agents");
			$this->db->join("cities","cities.city_id=agents.ag_city","left");
			$this->db->join("states","cities.city_state=states.state_id","left");
			$this->db->join("emps","emps.uid=agents.staff_id","left");
			$this->db->where("agents.ag_id",$brid);
			$data['edit']=$this->db->get()->row();
		}
		$this->db->select("*");
		$this->db->from("agents");
		$this->db->join("emps","emps.uid=agents.staff_id","left");
		$this->db->join("cities","cities.city_id=agents.ag_city","left");
		$this->db->join("states","cities.city_state=states.state_id","left");
		$this->db->where("agents.kyc_approve!=","Approved");
		$this->db->order_by("agents.ag_id","desc");
		$data['agents']=$this->db->get()->result();
		
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/city_admins',$data,true);
		$this->adminlayout();
	}
	
	public function add_area(){
		if($this->db->insert("city_areas",$_POST)==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Area Added Successfully.</div>');	
		}else{$this->session->set_flashdata('msg', '<div class="alert alert-danger">Area Couldnot be Added.</div>');	}
		redirect("admin/areas/".$_POST['city_id']);
	}
	public function update_area(){
		$this->db->where("area_id",$_POST['area_id']);
		if($this->db->update("city_areas",$_POST)==true){
			 $this->session->set_flashdata('msg', '<div class="alert alert-success">Area Updated Successfully.</div>');	
		}else{$this->session->set_flashdata('msg', '<div class="alert alert-danger">Area Couldnot be Updated.</div>');	}
		redirect("admin/areas/".$_POST['city_id']);
	}
	
	public function ajax_area_delete(){
		$this->db->delete("city_areas",array("area_id"=>$_POST['id']));
	}
	
	public function cities(){
		$this->db->select("*");
		$this->db->from("cities");
		$this->db->join("states","states.state_id=cities.city_state","left");
		$this->db->order_by("cities.city_name","asc");
		$data['cities']=$this->db->get()->result();//array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/cities',$data,true);
		$this->adminlayout();
	}	

	public function plan_history(){

		$this->db->select("*");

		$this->db->from("vplan_purchase");

		$this->db->join("vendors","vendors.vid=vplan_purchase.vid");

		$this->db->join("plans","plans.plid=vplan_purchase.plid");

		$this->db->where("vplan_purchase.vid",$this->session->userdata("userid"));

		$data['pls']=$this->db->get()->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/plan_history',$data,true);

		$this->adminlayout(); 

	}

	

	public function event_delete(){

		$this->db->delete("event",array("id_event"=>$_POST['id']));

	}

	public function events($id=false){

		if($id==true){

			$data['edit']=$this->db->get_where("event",array("id_event"=>$id))->row();

		}

		$this->db->select("*");

		$this->db->from('event');		

		$this->db->join("vendors","event.user_id=vendors.vid");

		if($this->session->userdata("type")=="vendor"){

		$this->db->where("event.user_id",$this->session->userdata("userid"));}

		$data['events']=$this->db->get()->result();

		//echo "<pre>";print_r($data);exit;

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/events',$data,true);

   		$this->adminlayout(); 

	}

	

	public function update_event(){

		$img=$_POST['oldimg'];

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

		$data=array("name"=>$_POST['name'],"address"=>$_POST['address'],"images"=>$img,"lat"=>$_POST['lat'],"lng"=>$_POST['lng'],"description"=>$_POST['description'],

		"tel"=>$_POST['tel'],"user_id"=>$_POST['user_id'],"date_created"=>date("Y-m-d"));

		$this->db->where("id_event",$_POST['id_event']);

		if($this->db->update("event",$data)==true)

		{

			echo $this->session->set_flashdata('msg', '<div class="alert alert-success">Event Updated Successfully.</div>');

		 }

		 else

		 {

			echo $this->session->set_flashdata('msg', '<div class="alert alert-danger">Event Couldnot be Updated.</div>');

		 }redirect("admin/events");

	

	}

	

	public function add_event(){

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

		$data=array("name"=>$_POST['name'],"address"=>$_POST['address'],"images"=>$img,"lat"=>$_POST['lat'],"lng"=>$_POST['lng'],"description"=>$_POST['description'],

		"tel"=>$_POST['tel'],"user_id"=>$_POST['user_id'],"date_created"=>date("Y-m-d"));

		if($this->db->insert("event",$data)==true)

		{

			echo $this->session->set_flashdata('msg', '<div class="alert alert-success">Event Created Successfully.</div>');

		 }

		 else

		 {

			echo $this->session->set_flashdata('msg', '<div class="alert alert-danger">Event Couldnot be Added.</div>');

		 }redirect("admin/events");

	}

	

	public function my_store($id=false){

		if($id==true){

			$data['edit']=$this->db->get_where("stores",array("store_id"=>$id))->row();

		}

		$this->db->select("*");

		$this->db->from('stores');		

		$this->db->join("store_category","stores.store_id=store_category.st_catid");

		$this->db->join("vendors","stores.vid=vendors.vid");

		$this->db->join("states","stores.st_state=states.state_id");

		$this->db->join("cities","stores.st_city=cities.city_id");

		if($this->session->userdata("type")=="vendor"){

		$this->db->where("stores.vid",$this->session->userdata("userid"));}

		$data['stores']=$this->db->get()->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/stores',$data,true);

   		$this->adminlayout(); 

	}

	

	public function add_store(){

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

		$data=array("store_name"=>$_POST['store_name'],"vid"=>$_POST['vid'],"store_cat"=>$_POST['store_cat'],"co_ord"=>$_POST['co_ord'],"st_state"=>$_POST['st_state'],"st_city"=>$_POST['st_city'],"st_pincode"=>$_POST['st_pincode'],"st_address"=>$_POST['st_address'],"st_phone"=>$_POST['st_phone'],"st_reg_date"=>date("Y-m-d"),"st_image"=>$img);

		if($this->db->insert("stores",$data)==true)

		{

			echo $this->session->set_flashdata('msg', '<div class="alert alert-success">Store Added Successfully.</div>');

		 }

		 else

		 {

			echo $this->session->set_flashdata('msg', '<div class="alert alert-danger">Store Couldnot be Added.</div>');

		 }redirect("admin/my_store");

	}

	public function update_store(){

		$img=$_POST['oldimg'];

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

		$data=array("store_name"=>$_POST['store_name'],"vid"=>$_POST['vid'],"store_cat"=>$_POST['store_cat'],"co_ord"=>$_POST['co_ord'],"st_state"=>$_POST['st_state'],"st_city"=>$_POST['st_city'],"st_pincode"=>$_POST['st_pincode'],"st_address"=>$_POST['st_address'],"st_phone"=>$_POST['st_phone'],"st_reg_date"=>date("Y-m-d"),"st_image"=>$img);

		$this->db->where("store_id",$_POST['store_id']);

		if($this->db->update("stores",$data)==true)

		{

			echo $this->session->set_flashdata('msg', '<div class="alert alert-success">Store Updated Successfully.</div>');

		 }

		 else

		 {

			echo $this->session->set_flashdata('msg', '<div class="alert alert-danger">Store Couldnot be Updated.</div>');

		 }redirect("admin/my_store");

	}

	

	public function settings(){

		$this->db->where("id",1);

		$query=$this->db->update("admin",array("rate"=>$_POST['rate'],"refer_use"=>$_POST['refer_use'],"referred_user"=>$_POST['referred_user'],"earned_point"=>$_POST['earned_point']));	

		if($query==true)

		 {

			echo $this->session->set_flashdata('msg', 'Settings Updated');

		 }

		 else

		 {

			echo $this->session->set_flashdata('msg', 'Settings Could not be Updated');

		 }redirect("admin");

	}

	

	public function autobids(){

		$this->db->select("*");

		$this->db->from("autobids");

		$this->db->join("auction_prod","auction_prod.apid=autobids.bid_id");

		$this->db->join("products","products.pid=auction_prod.pid");

		$this->db->join("users","users.id=autobids.uid");

		//$this->db->where("autobids.uid",$this->session->userdata("user"));

		$data['autobids']=$this->db->get()->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/autobids',$data,true);

		$this->adminlayout(); 

	}

	

	public function users_ep(){

		$this->db->select("*");

		$this->db->from("earned_dis");

		$this->db->join("users","users.id=earned_dis.userid");

		$this->db->group_by("earned_dis.userid");

		$data['earn']=$this->db->get()->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/users_ep',$data,true);

		$this->adminlayout();

	}

	

	

	public function all_country(){

		$this->db->order_by("country_name");

		$data['country']=$this->db->get('country')->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/country',$data,true);

		$this->adminlayout();

	}

	

	public function ajax_show_rates(){

		$data['country']="Other";

		$data['rates']=$this->db->get_where("shipping_rates",array("zone_id"=>$_POST['zone']))->result();	

		$this->load->view("admin/ajax_show_rates",$data);

	}

	

	public function nigeria(){

		$this->db->order_by("station");

		$data['states']=$this->db->get('states')->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/nigeria',$data,true);

		$this->adminlayout();

	}

	

	public function ajax_update_curr(){

		$this->db->where("crid",$_POST['crid']);

		$this->db->update("currency",array("ex_rate"=>$_POST['rate']));

		echo "Exchange Rate Updated";	

	}

	public function ajax_update_rate(){

		//print_r($_POST);exit;

		if($_POST['country']=="Other"){

		$this->db->where("ship_id",$_POST['id']);

		$this->db->update("shipping_rates",array("rate"=>$_POST['rate']));

		}

		if($_POST['country']=="Nigeria"){

		$this->db->where("ship_id",$_POST['id']);

		$this->db->update("nshipping_rates",array("rate"=>$_POST['rate']));	

		}

		echo "Shipping Rate Updated";	

	}

	

	public function add_country(){

		$this->db->insert("country",array("zone_id"=>$_POST['zone'],"country_name"=>$_POST['country']));

		redirect("admin/all_country");	

	}
	
	public function add_time(){

		if($this->db->insert("delivery_times",$_POST)==true){
			echo $this->session->set_flashdata('msg', '<div class="alert alert-success">Delivery Time Slot Added Successfully.</div>');
		}else{
		echo $this->session->set_flashdata('msg', '<div class="alert alert-danger">Delivery Time Slot Couldnot be Added.</div>');
		}
		redirect("admin");	

	}
	
	public function update_time(){
		$this->db->where("dtid",$_POST['dtid']);
		if($this->db->update("delivery_times",$_POST)==true){
			echo $this->session->set_flashdata('msg', '<div class="alert alert-success">Delivery Time Slot Updated Successfully.</div>');
		}else{
		echo $this->session->set_flashdata('msg', '<div class="alert alert-danger">Delivery Time Slot Couldnot be Updated.</div>');
		}
		redirect("admin");	

	}

	

	public function delete_country(){

		$this->db->delete("country",array("country_id"=>$_POST['id']));

	}
	public function dt_delete(){

		$this->db->delete("delivery_times",array("dtid"=>$_POST['id']));

	}

	

	public function zone_rates(){

		$data['zones']=$this->db->get("shipping_rates")->result();	

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/zone_rates',$data,true);

		$this->adminlayout(); 

	}

	public function ajax_update_zonerate(){

		$this->db->where("ship_id",$_POST['id']);

		$this->db->update("shipping_rates",array("weight"=>$_POST['wt'],"rate"=>$_POST['rate']));

		echo "Rate Updated";	

	}

	

	public function ajax_show_ratesn(){

		$data['country']="Nigeria";

		$data['rates']=$this->db->get_where("nshipping_rates",array("zone_id"=>$_POST['zone']))->result();	

		$this->load->view("admin/ajax_show_rates",$data);

	}

	

	

	

	public function index()

	{
		$data=array();//$this->db->get_where("apps",array("app_date>="=>date("Y-m-d")))->result();//array();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/dashboard',$data,true);

		$this->adminlayout(); 

	}

	

	public function add_review(){

		$img='img-01.jpg';

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{echo $this->upload->display_errors();}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}



		} 

		$this->db->insert("testimo",array("img"=>$img,"name"=>$this->input->post("name"),"review"=>$this->input->post("review"),"title"=>$this->input->post("title")));

		redirect("admin");

	}

	

	public function loadmore_auctions(){

		$crtime=strtotime(date("Y-m-d h:i a"));

		$this->db->select("*");

		$this->db->from('auction_prod');

		$this->db->join("products","products.pid=auction_prod.pid");

		$this->db->where("auction_prod.auc_date <=",date("Y-m-d"));

		$this->db->where("auction_prod.start_status","pending");

		//$this->db->where("auction_prod.start_time <=",$crtime);

		//$this->db->where("auction_prod.end_time >=",$crtime);

		$this->db->where("auction_prod.auc_status","");

		$data['auctions']=$this->db->get()->result();

		$this->db->where("apid !=","");

		$this->db->update("auction_prod",array("start_status"=>""));

		$this->load->view("admin/loadmore_auctions",$data);	

		

	}

	

	public function live(){

	    //$this->db->where("apid!=","");

	   // $this->db->update("auction_prod",array("start_status"=>""));

		$crtime=strtotime(date("Y-m-d h:i a"));

		$this->db->select("*");

		$this->db->from('auction_prod');

		$this->db->join("products","products.pid=auction_prod.pid");

		$this->db->where("auction_prod.auc_date <=",date("Y-m-d"));

		$this->db->where("auction_prod.start_status!=","pending");

		//$this->db->where("auction_prod.auc_date",date("Y-m-d"));

		//$this->db->where("auction_prod.start_time <=",$crtime);

		//$this->db->where("auction_prod.end_time >=",$crtime);

		$this->db->where("auction_prod.auc_status","");

		$data['auctions']=$this->db->get()->result();

	//	echo "<pre>";print_r($data);exit;

		$this->load->view("admin/live",$data);	

	}

	

	public function upload_excel(){

		$this->load->view("admin/upload_excel_state");

	}

	

	public function upload_product_excel(){

			$file = $_FILES['pfile']['tmp_name'];

			$handle = fopen($file, "r");

			$c = 0;
			
			$last_pro='';
			while(($filesop = fgetcsv($handle, 1000, ",")) !== false)

			{
				
				if($filesop[0]!="S.No.")

				{
					$chk=$this->db->get_where("mcategory",array("mcat_name"=>$filesop[3]));
					if($chk->num_rows()>0){
						$cat=$chk->row();
						$cat_name=$cat->mcat_name;
						$cat_id=$cat->mid;
						//echo $cat_id;exit;
						//if($filesop[1]==''){
//							echo "exist<br/>";exit;
//						$chkk=$this->db->get_where("prod_variants",array("pptype"=>$filesop[4],"ppieces"=>$filesop[5],"pid"=>$this->session->userdata("last_pro")));
//						if($chkk->num_rows()>0){
//				$this->db->where("pptype",$filesop[4]);
//				$this->db->where("ppieces",$filesop[5]);
//				$this->db->where("pid",$this->session->userdata("last_pro"));
//				$this->db->update("prod_variants",array("pmrp"=>$filesop[6],"unit_rate"=>$filesop[7],"case_rate"=>$filesop[8],"per_unit_price"=>$filesop[9]));}else{
//							echo "new<br/>";exit;
//					$this->db->insert("prod_variants",array("pptype"=>$filesop[4],"ppieces"=>$filesop[5],"pmrp"=>$filesop[6],"unit_rate"=>$filesop[7],"case_rate"=>$filesop[8],"per_unit_price"=>$filesop[9]));
//				}
			//			}else{
							$prochk=$this->db->get_where("products",array("title"=>$filesop[1],"brand"=>$filesop[2],"mid"=>$cat_id));
							if($prochk->num_rows()>0){
								//
								$pid=$prochk->row();
								$proid=$pid->pid;
								//echo $proid;exit;
								$chkk=$this->db->get_where("prod_variants",array("pptype"=>$filesop[4],"ppieces"=>$filesop[5],"pid"=>$proid));
								//echo $chkk->num_rows();exit;
						if($chkk->num_rows()>0){
				$this->db->where("pptype",$filesop[4]);
				$this->db->where("ppieces",$filesop[5]);
				$this->db->where("pid",$proid);
				$this->db->update("prod_variants",array("pmrp"=>$filesop[6],"unit_rate"=>$filesop[7],"case_rate"=>$filesop[8],"per_unit_price"=>$filesop[9]));}else{
					
					$this->db->insert("prod_variants",array("pid"=>$proid,"pptype"=>$filesop[4],"ppieces"=>$filesop[5],"pmrp"=>$filesop[6],"unit_rate"=>$filesop[7],"case_rate"=>$filesop[8],"per_unit_price"=>$filesop[9]));//echo 'second var';exit;
				}
							}else{
								
								$this->db->insert("products",array("title"=>$filesop[1],"brand"=>$filesop[2],"mid"=>$cat_id,"img"=>"default.jpg","prod_type"=>"Variant"));
								$lid=$this->db->insert_id();
								$this->db->insert("prod_variants",array("pptype"=>$filesop[4],"ppieces"=>$filesop[5],"pid"=>$lid,"pmrp"=>$filesop[6],"unit_rate"=>$filesop[7],"case_rate"=>$filesop[8],"per_unit_price"=>$filesop[9]));
								
							}
						//}
					}else{
						
					}
				}
			}  


				redirect("admin/list_products");

	}

	

	public function upload_excel_submit(){

			$file = $_FILES['excel']['tmp_name'];

			$handle = fopen($file, "r");

			$c = 0;

			while(($filesop = fgetcsv($handle, 1000, ",")) !== false)

			{

				if($filesop[0]!="wt")

				{//"zone_id"=>3,"weight"=>$filesop[0],"rate"=>$filesop[1]);//,

					$data=array("zone_id"=>4,"weight"=>$filesop[0],"rate"=>$filesop[1]);

					//$this->db->where("id",$this->uri->segment(3));

					 if($this->db->insert('nshipping_rates',$data)==true)

					 {

						echo $this->session->set_flashdata('msg', 'States Data Uploaded Successfully.');

					 }

					 else

					 {

						echo $this->session->set_flashdata('msg', 'States Data Couldnot be Uploaded.');

					 }

				}}  

				exit;

				//redirect("admin/list_pro");

    

	}

	

	

	

	public function trans_refresh(){

		$pll=$this->db->get_where("purchase",array("purid"=>$_POST['id']))->row();

//print_r($pll);exit;

$subpdtid = 6204; // your product ID

$submittedamt = $pll->amount;

$submittedref = $pll->trans_id;



        $nhash = "E187B1191265B18338B5DEBAF9F38FEC37B170FF582D4666DAB1F098304D5EE7F3BE15540461FE92F1D40332FDBBA34579034EE2AC78B1A1B8D9A321974025C4" ; 

        $hashv = $subpdtid.$submittedref.$nhash;  // concatenate the strings for hash again

		$thash = hash('sha512',$hashv); 



		$parami = array(

				"productid"=>$subpdtid,

				"transactionreference"=>$submittedref,

				"amount"=>$submittedamt

		);

		$ponmo = http_build_query($parami);



//$url = "http://172.35.2.11/webpay/api/v1/gettransaction.json?$ponmo"; // json

$url = "https://sandbox.interswitchng.com/webpay/api/v1/gettransaction.json?$ponmo"; // json



$headers = array(

        "GET /HTTP/1.1",

        "Host: sandbox.interswitchng.com",

        "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1",

        "Accept: */* ",

        "Accept-Language: en-us,en;q=0.5",

        "Keep-Alive: 300",

        "Connection: keep-alive",

        "Hash: " . $thash

    );        

//echo $url;



$ch = curl_init();  //INITIALIZE CURL///////////////////////////////

//               



curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_TIMEOUT, 60); 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 

curl_setopt($ch, CURLOPT_POST, false );

//

$data = curl_exec($ch);  //EXECUTE CURL STATEMENT///////////////////////////////

$json = null;

if (curl_errno($ch)) 

{ 

        print "Error: " . curl_error($ch) . "</br></br>";

        $errno = curl_errno($ch);

        $error_message = curl_strerror($errno);

        print $error_message . "</br></br>";

}

else 

{  

	// Show me the result

	$json = json_decode($data, TRUE);



	curl_close($ch);    //END CURL SESSION///////////////////////////////



			if($json['ResponseDescription']=="Approved Successful"){

				if($this->session->userdata("refuser")){

				$admin=$this->db->get("admin")->row();

				$this->db->insert("earned_dis",array("userid"=>$pll->userid,"earn_date"=>date("Y-m-d"),"earn_desc"=>"Referal Bonus","earn_amt"=>$admin->referred_user));	

				}

			//echo $json['ResponseDescription'];exit;

		    $this->db->where("buyid",$pll->purid);

			$this->db->update("buy_plans",array("buy_status"=>"success"));

			$plan=$this->db->get_where("plans",array("plid"=>$pll->purchase_desc))->row();

			$this->db->order_by("trid","desc");

			$chk=$this->db->get_where("transactions",array("uid"=>$pll->userid));

			$pre_credits=0;

			if($chk->num_rows()>0){

				$cr=$chk->row();

				$pre_credits=$cr->credits_left;

			}

			$new_credits=$pre_credits+$plan->credits;

			$submittedamt=$submittedamt/100;//-$this->session->userdata("discount");

			$trdt=date("Y-m-d H:i:s");

			$this->db->where("purid",$pll->purid);

			$this->db->update("purchase",array("resp_code"=>$json['ResponseCode'],"trans_type"=>"Bids","trans_id"=>$submittedref,"amount"=>$submittedamt,"currency"=>$pll->currency,"trans_date"=>$trdt,"trans_desc"=>$json['ResponseDescription'],"payment_ref"=>$json['PaymentReference'],"userid"=>$pll->userid,"purchase_desc"=>$pll->purchase_desc));

			$this->db->insert("transactions",array("tr_amt"=>0,"uid"=>$pll->userid,"credits_left"=>$new_credits,"trans_type"=>"Credit","tr_date"=>date("Y-m-d")));

	    	echo $json['ResponseDescription'];

			}else{

			$trdt=date("Y-m-d H:i:s");

            $this->db->where("purid",$pll->purid);

	    	$this->db->update("purchase",array("resp_code"=>$json['ResponseCode'],"trans_type"=>"Bids","trans_id"=>$submittedref,"amount"=>$submittedamt,"currency"=>$pll->currency,"trans_date"=>$trdt,"trans_desc"=>$json['ResponseDescription'],"payment_ref"=>$json['PaymentReference'],"userid"=>$pll->userid,"purchase_desc"=>$pll->purchase_desc));

				echo $json['ResponseDescription'];

			}

}

	  

	}

	

	

	public function close_auction(){

	$t=time();

	$bidrate=$this->db->get("admin")->row();

	date_default_timezone_set('UTC');

	$clost_time=gmdate("Y-m-d\TH:i:s\Z");

	$dd=date("H:i a");

	$totbidd=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid']))->num_rows();

	$this->db->where("apid",$_POST['apid']);

	$this->db->update("auction_prod",array("auc_status"=>"closed","end_time"=>$clost_time,"close_day"=>date("Y-m-d"),"total_bids_placed"=>$totbidd));

	$newbid=$this->db->get_where("auction_prod",array("apid"=>$_POST['apid']))->row();

	

	if($this->db->get_where("products",array("pid"=>$newbid->pid,"autoclone"=>"yes"))->num_rows()>0){

	$this->db->insert("auction_prod",array("auc_start_time"=>$clost_time,"pid"=>$newbid->pid,"min_price"=>$newbid->min_price,"max_price"=>$newbid->max_price,"auto_incre"=>$newbid->auto_incre,"start_time"=>$t,"req_credit"=>$newbid->req_credit,"duration"=>$newbid->duration,"time_left"=>"","auto_bid"=>$newbid->auto_bid,"auc_date"=>date("Y-m-d")));

	echo $this->db->insert_id().'='.$dd;

	}else{

	echo 0;	

	}

	$this->db->order_by("aucid","desc");

	$lid=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid']))->row();

	$this->db->where("aucid",$lid->aucid);

	$this->db->update("auctions",array("auc_win"=>"win"));

	

	//$chk=$this->db->query("select * from auctions where auc_dayid='".$_POST['apid']."' and auc_win!='win' group_by uid")->result();

	$this->db->group_by("uid");

	$chk=$this->db->get_where("auctions",array("auc_win!="=>"win","auc_dayid"=>$_POST['apid']))->result();

	foreach($chk as $u){

	$uu=$this->db->get_where("auctions",array("uid"=>$u->uid,"auc_dayid"=>$_POST['apid'],"auc_win"=>"win"))->num_rows();

	if($uu==0){

	$uuu=$this->db->get_where("auctions",array("uid"=>$u->uid,"auc_dayid"=>$_POST['apid']))->num_rows();

	$amt=$uuu*$bidrate->rate;

	$this->db->insert("earned_dis",array("userid"=>$u->uid,"bidcount"=>$uuu,"earn_amt"=>$amt,"earn_date"=>date("Y-m-d"),"auc_id"=>$_POST['apid']));

		}}

		$left_b=$this->db->get_where("autobids",array("bid_id"=>$_POST['apid'],"left_bids >"=>0))->result();

		foreach($left_b as $l){

			$this->db->order_by("trid","desc");

			$chk=$this->db->get_where("transactions",array("uid"=>$l->uid));

			$pre_credits=0;

			if($chk->num_rows()>0){

				$cr=$chk->row();

				$pre_credits=$cr->credits_left;

			}

			$new_credits=$pre_credits+$l->left_bids;

			$this->db->insert("transactions",array("tr_amt"=>$l->left_bids,"uid"=>$l->uid,"credits_left"=>$new_credits,"trans_type"=>"Credit","tr_date"=>date("Y-m-d")));	

		}

	}

	

	public function robot_bid(){

		$rid=rand(1,10);

		$rand_sec=rand(5,10);

		$rate=$this->session->userdata("bidrate");

		$user=$this->db->get_where("users",array("id"=>$rid))->row();

		$bid_details=$this->db->get_where("auction_prod",array("apid"=>$_POST['apid']))->row();

		$min_bids=ceil(($bid_details->min_price/$rate)/$bid_details->req_credit);

		$max_bids=ceil(($bid_details->max_price/$rate)/$bid_details->req_credit);

		//echo $min_bids.'-';

		//echo $max_bids;exit;

		$tot=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid'],"bid_type"=>""))->num_rows();

		$tot2=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid']))->num_rows();

		if($tot>=$min_bids){

			echo 0;exit;	

		}

		if($tot2>=$max_bids && $tot<$min_bids){//echo "hey";//exit;

			$this->db->order_by("aucid","desc");

			$this->db->limit(1);

			$chklast=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid']))->row();//,"bid_type"=>"robot"))->num_rows();

			//print_r($chklast);exit;

			if($chklast->bid_type=="robot"){

			//echo "hey";exit;

			echo 0;exit;

			//$this->db->insert("auctions",array("auc_win"=>"","pid"=>$_POST['pid'],"auc_dayid"=>$_POST['apid'],"auc_price"=>10,"uid"=>$rid,"bid_type"=>"robot")); //echo 0;exit;	

			}//else{}

		}

		$micro_date = microtime();

		$date_array = explode(" ",$micro_date);

		$date = date("H:i:s",$date_array[1]);

		$bid_time= "$date:" . $date_array[0];

		$this->db->insert("auctions",array("reqcredit"=>$bid_details->req_credit,"bid_time"=>$bid_time,"auc_win"=>"","pid"=>$_POST['pid'],"auc_dayid"=>$_POST['apid'],"auc_price"=>10,"uid"=>$user->id,"bid_type"=>"robot")); 

		$rand=round($rid/2);rand(0,5);

		$img=base_url().'asset/images/user'.$rand.'.jpg';

		echo $tot2.'='.$tot.'='.$min_bids.'='.$max_bids.'='.$user->username.'='.$img.'='.$rand_sec;

	}

	

	public function ajax_user_details(){

		$data['user']=$this->db->get_where("users",array("id"=>$_POST['id']))->row();

		$this->load->view("admin/ajax_user_details",$data);

	}

	

	public function autobid(){

		$micro_date = microtime();

		$date_array = explode(" ",$micro_date);

		$date = date("H:i:s",$date_array[1]);

		$bid_time= "$date:" . $date_array[0];

		

		//$chklast

		//print_r($_POST);exit;

		$this->db->order_by("aucid","desc");

		$chklast=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid']));

		$totcc=$chklast->num_rows();

		if($totcc>0){

		$chh=$chklast->row();

		//print_r($chh);exit;

		//echo $chklast->uid;exit;

		$totusers=$this->db->get_where("autobids",array("uid !="=>$chh->uid,"bid_id"=>$_POST['apid'],"left_bids >"=>0));

		//echo $totusers->num_rows();exit;

		if($totusers->num_rows()>0){

			$chk_start=$totusers->result();

			foreach($chk_start as $chkst){

				$start_point=$chkst->start_at;

				if($totcc>=$start_point){

					$this->db->limit(1);

		$auto_user=$totusers->row();

		$userd=$this->db->get_where("users",array("id"=>$auto_user->uid))->row();

		$img=$userd->profile_url;

		$query=$this->db->insert("auctions",array("bid_time"=>$bid_time,"auc_dayid"=>$_POST['apid'],"pid"=>$_POST['pid'],"auc_price"=>10,"uid"=>$auto_user->uid)); 

		$left_bids=$auto_user->left_bids-1;

		$this->db->where("aut_bid",$auto_user->aut_bid);

		$this->db->update("autobids",array("left_bids"=>$left_bids));

		if($query==true){

		echo $userd->username.'='.$img;}else{echo 0;}

		exit;

		}else{

		echo 0;	

		}

				}

			}

		///$rand=rand(1,$totusers->num_rows());

		}

	}

	

	public function robot_bidold(){

		$rid=rand(1,10);

//		$ltime=0;

		//$this->db->select("id,username");

		//$ruser=$this->db->get_where("users",array("id"=>$rid))->row();

//		$bid_start=$this->db->get_where("auction_prod",array("apid"=>$_POST['apid']))->row();

//		

//		$lbid=$bid_start->min_price;

//		$inc=$bid_start->auto_incre;


//		$this->db->order_by("aucid","desc");

//		$chk=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid']));

//		if($chk->num_rows()>0){

//			$lastbid=$chk->row();

//			$lbid=$lastbid->auc_price;

//			$ltime=strtotime($lastbid->auc_time);

//		}

//		$ctime=strtotime(date("Y-m-d H:i:s"));

//		$diff=$ctime-$ltime;

//		

//		 $newbid=$lbid+$inc;

		 $auc_win="";

//		 if($newbid>=$bid_start->max_price){$auc_win="yes";

//		 $this->db->where("apid",$bid_start->apid);

//		 $this->db->update("auction_prod",array("auc_status"=>"Closed","winner"=>$this->session->userdata("user")));

//		 }

		 

		 $this->db->insert("auctions",array("auc_win"=>$auc_win,"pid"=>$_POST['pid'],"auc_dayid"=>$_POST['apid'],"auc_price"=>10,"uid"=>$rid,"bid_type"=>"robot"));

		 

	}

	

	public function pay_gate_change(){

		$this->db->update("admin",array("pay_gate"=>$_POST['st']));	

	}

	

	public function time_update(){

		$this->db->where("apid",$_POST['apid']);

		$this->db->update("auction_prod",array("time_left"=>$_POST['sec']));	

	}

	

	public function check_bids(){

		//echo $_POST['apid'];exit;

		$this->db->where("apid",$_POST['apid']);

		$this->db->update("auction_prod",array("time_left"=>$_POST['sec']));

//		$this->db->select("*");

//		$this->db->from("auctions");

//		$this->db->join("users","users.id=auctions.uid");

//		$this->db->where("auctions.auc_dayid",$_POST['apid']);

		//$this->db->order_by("aucid","desc");

		$chkb=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid']))->num_rows();

		$real=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid'],"bid_type"=>""))->num_rows();

		$fake=$this->db->get_where("auctions",array("auc_dayid"=>$_POST['apid'],"bid_type"=>"robot"))->num_rows();

		echo $total_bids=$chkb.'-'.$real.'-'.$fake;

		//if($total_bids>$_POST['prebid']){

			///echo $total_bids;

			

		//$u=$chkb->row();

//			echo "Total Bids: <b id='totalbid".$u->auc_dayid."'>".$total_bids.'</b><br/>';

//		if($total_bids>0){

//			echo '<label class="label label-warning">'.$u->username.'</label>';

//			echo '<br/>Bid Value : '.$u->auc_price;

//		}

		//}

	}

	

	public function reset_bids(){

		$this->db->delete("auctions",array("aucid!="=>""));

		//$this->db->

		$this->db->update("auction_prod",array("auc_status"=>""));

		//$this->db->delete("auction_prod",array("apid >"=>46723));

		$this->db->delete("earned_dis",array("edid !="=>""));

		redirect("admin/live");	

	}

	

	public function kyc_uploads(){

		$data['docs']=$this->db->get_where("users",array("doc_type!="=>""))->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/kycs',$data,true);

		$this->adminlayout(); 

	}

	

	public function approve_form_submit(){

	  	parse_str($_POST['formdata'], $form);

		$this->db->where("id",$form['uid']);

		$this->db->update("users",array("doc_status"=>$form['status'],"doc_remarks"=>$form['remarks']));

  }

	

	public function bids_purchase($uid=false){

		$this->db->select("*");

		$this->db->from("purchase");

		$this->db->join("plans","plans.plid=purchase_desc");

		$this->db->join("users","users.id=purchase.userid");

		if($uid==true){

		$this->db->where("purchase.userid",$uid);

		}

		$this->db->order_by("purchase.purid","desc");

		$data['bid_trans']=$this->db->get()->result();

		

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/bids_purchase',$data,true);

		$this->adminlayout(); 	

	}

	

	public function offline_payments(){

		$this->db->select("*");

		$this->db->from("purchase");

		$this->db->join("plans","plans.plid=purchase_desc");

		$this->db->join("users","users.id=purchase.userid");

		$this->db->where("purchase.offline_pay","yes");

		$this->db->order_by("purchase.purid","desc");

		$data['bid_trans']=$this->db->get()->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/offline_payments',$data,true);

		$this->adminlayout();	

	}

	

	public function view_live_bid(){

		$this->db->select("*");

		$this->db->from("auctions");

		$this->db->join("users","users.id=auctions.uid");

		$this->db->where("auctions.auc_dayid",$_POST['apid']);

		$this->db->order_by("auctions.aucid","desc");

		$data['live_bids']=$this->db->get()->result();

		$this->load->view("admin/view_live_bid",$data);

	}

	

	public function live_auction(){

		

		$this->db->select("*");

		$this->db->from('auction_prod');

		$this->db->join("products","products.pid=auction_prod.pid");

		$this->db->where("auction_prod.auc_date <=",date("Y-m-d"));

		$this->db->where("auction_prod.auc_status!=","closed");

		$data['auctions']=$this->db->get()->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/auctions',$data,true);

		$this->adminlayout(); 	

	}

	public function closed_auction(){

		

		if(isset($_GET['date'])){

		$d=$_GET['date'];	

		}else{

		$d=date("Y-m-d");	

		}

		$this->db->select("*");

		$this->db->from('auction_prod');

		$this->db->join("products","products.pid=auction_prod.pid");

		$this->db->where("auction_prod.close_day",$d);

		$this->db->where("auction_prod.auc_status","closed");

		$tot=$this->db->get();

		

		$config['base_url'] = base_url().'admin/closed_auction/';

		$config['total_rows'] = $tot->num_rows();

		$config['per_page'] = 10;

		$config['full_tag_open'] = "<ul class='pagination'>";

		$config['full_tag_close'] ="</ul>";

		$config['num_tag_open'] = '<li>';

		$config['num_tag_close'] = '</li>';

		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";

		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";

		$config['next_tag_open'] = "<li>";

		$config['next_tagl_close'] = "</li>";

		$config['prev_tag_open'] = "<li>";

		$config['prev_tagl_close'] = "</li>";

		$config['first_tag_open'] = "<li>";

		$config['first_tagl_close'] = "</li>";

		$config['last_tag_open'] = "<li>";

		$config['last_tagl_close'] = "</li>";

		$config['reuse_query_string'] = true;

		$this->pagination->initialize($config);

		

		

		if(isset($_GET['date'])){

		$d=$_GET['date'];	

		}else{

		$d=date("Y-m-d");	

		}

		$this->db->select("*");

		$this->db->from('auction_prod');

		$this->db->join("products","products.pid=auction_prod.pid");

		$this->db->where("auction_prod.close_day",$d);

		$this->db->where("auction_prod.auc_status","closed");

		$this->db->limit(10,$this->uri->segment(3));

		$this->db->order_by("auction_prod.apid","desc");

		$data['auctions']=$this->db->get()->result();

		

		$this->load->view("admin/header");

		$this->load->view("admin/closed_auctions",$data);

		//$this->template['middle'] = $this->load->view ($this->middle = 'admin/closed_auctions',$data,true);

		//$this->adminlayout(); 	

	}

	public function bid_history($uid){

		  $this->db->select("*");

		  $this->db->from("auctions");

		  $this->db->join("products","products.pid=auctions.pid");

		  $this->db->where("auctions.uid",$uid);

		  $this->db->order_by("auctions.aucid","desc");

		  $this->db->limit(50);

		  $data['auc']=$this->db->get()->result();

		  $data['user']=$this->db->get_where("users",array("id"=>$uid))->row();

		  //echo "<pre>";print_r($data);exit;

		  $this->template['middle'] = $this->load->view ($this->middle = 'admin/bid_history',$data,true);

		  $this->adminlayout(); 

	}



	public function auction($st,$from=false){

	  	$crtime=strtotime(date("Y-m-d h:i a"));

		//exit;

		$this->db->select("*");

		$this->db->from('auction_prod');

		$this->db->join("products","products.pid=auction_prod.pid");

		//

		if($st=="live"){

		$this->db->where("auction_prod.auc_date",date("Y-m-d"));

		$this->db->where("auction_prod.start_time <=",$crtime);

		$this->db->where("auction_prod.end_time >=",$crtime);

		}

		if($st=="closed"){

		$this->db->join("users","users.id=auction_prod.winner");

		$this->db->where("auction_prod.auc_status","Closed");

			if(isset($_GET['date'])){

				$this->db->where("auction_prod.auc_date",$_GET['date']);

			}else{

				$this->db->where("auction_prod.auc_date",date("Y-m-d"));

			}	

		}

		if($from==true){

		$this->db->limit(10,7)	;

		}else{

		$this->db->limit(12);	

		}

		$data['auctions']=$this->db->get()->result();

		$this->load->view ($this->middle = 'admin/auctions',$data,true);

      	$this->adminlayout();

	}



	public function invoice_pdf(){

		$this->db->select('*');

		$this->db->from('orders');

		// Get

		$this->db->join('users', 'orders.userid = users.id');

		$this->db->where("oid",$_POST['id']);

		// Get

		$orders=$this->db->get();

		$data['order']=$orders->row();

		$data['items']=$this->db->get_where("order_items",array("oid"=>$_POST['id']))->result();

		//$this->load->view("admin/invoice",$data); 
		
			$message = $this->load->view("admin/invoice",$data,true);
			$this->email->set_newline("\r\n");
			$this->email->set_mailtype("html");
			$this->email->to('satshl3112@gmail.com,yaarasales2002@gmail.com,info@y1electronics.in,'.$order->email);
			$this->email->from("orders@y1electronics.in");
			$this->email->subject('Y1Electronics Order Invoice');
			$this->email->message($message);
			if($this->email->send()==true){
				echo "Invoice Mail is sent to customer.";	
			}else{
				echo "Invoice Mail couldnot be sent.";
			}

		// Get output html

		//$html = $this->output->get_output();
//
//		// Load library
//
//		$this->load->library('Dompdf_gen');
//
//		// Convert to PDF
//
//		$this->dompdf->load_html($html);
//
//		$this->dompdf->set_paper('a4', 'portrait');
//
//		$this->dompdf->render();
//
//		$this->dompdf->stream("welcome.pdf");

  	}
	
	public function print_invoice($oid){

		$this->db->select('*');

		$this->db->from('orders');

		// Get

		$this->db->join('users', 'orders.userid = users.id');

		$this->db->where("oid",$oid);

		// Get

		$orders=$this->db->get();

		$data['order']=$orders->row();

		$data['items']=$this->db->get_where("order_items",array("oid"=>$oid))->result();

		$this->load->view("admin/invoice",$data); 
		
			

		// Get output html

		//$html = $this->output->get_output();
//
//		// Load library
//
//		$this->load->library('Dompdf_gen');
//
//		// Convert to PDF
//
//		$this->dompdf->load_html($html);
//
//		$this->dompdf->set_paper('a4', 'portrait');
//
//		$this->dompdf->render();
//
//		$this->dompdf->stream("welcome.pdf");

  	}



	public function csort(){

		foreach($_POST as $key=>$val){

			$this->db->where("cid",$key);

			$this->db->update("category",array("csort"=>$val));

		}

		redirect("admin/category");

	}

	public function msort(){

		foreach($_POST as $key=>$val){

			$this->db->where("mid",$key);

			$this->db->update("mcategory",array("msort"=>$val));

		}

		redirect("admin/mcategory");

	}

	

	public function pre_designs(){

		$data['cds']=$this->db->get("pre_designs")->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/add_designs',$data,true);

		$this->adminlayout(); 

	}



	public function pre_arts(){

		$data['arts']=$this->db->get("arts")->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/add_art',$data,true);

		$this->adminlayout(); 

	}



	public function add_art_submit(){

		$art="";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("aclass"=>$this->input->post("title"),"aimage"=>$img);

			if($this->db->insert("arts",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Art Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Art Couldnot be Added.</div>");

			}

		redirect("admin/pre_arts");

	}



	public function Agents($page=false){

		$data['agents']=$this->db->get_where("admin",array("username!="=>"admin"))->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/agents',$data,true);

		$this->adminlayout(); 	

	}
	
	public function kyc_status_update(){
		parse_str($_POST['formdata'],$form);
		
		$acc_verify='';
		if($form['kyc_approve']=='Approved'){
			$acc_verify='active';	
		}
		$this->db->where("ag_id",$form['ag_id']);
		$this->db->update("agents",array("kyc_approve"=>$form['kyc_approve'],"acc_verify"=>$acc_verify,"kyc_remarks"=>$form['kyc_remarks']));
		
		echo "Remarks Updated";
	}
	
	public function ajax_view_details(){
		//print_r($_POST);exit;
		$this->db->select('*');
		$this->db->from('agents');
		$this->db->join("cities","cities.city_id=agents.ag_city");
		$this->db->where("agents.ag_id",$_POST['id']);
		$data['user']=$this->db->get()->row();//_where("agents",array("ag_id"=>$_POST['id']))->row();  
		//echo "<pre>";print_r($data);exit;
		$this->load->view("admin/ajax_user_details",$data);
	}

	
	public function update_agent(){
		$aadhar=$_POST['old_ag_ad_front'];
		$ag_ad_back=$_POST['old_ag_ad_back'];
		$pancard=$_POST['old_pan_card'];
		$agreement=$_POST['oldagreement'];
		if(!empty($_FILES["ag_ad_front"]["name"])){
			$config['upload_path'] = './assets/images/dist_docs/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('ag_ad_front'))
			{ echo $this->upload->display_errors(); }
			else
			{	
			$pic = $this->upload->data();
			$aadhar=base_url().'assets/images/dist_docs/'.$pic['file_name'];
			}
		} 
		if(!empty($_FILES["ag_ad_back"]["name"])){
			$config['upload_path'] = './assets/images/dist_docs/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('ag_ad_back'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$ag_ad_back=base_url().'assets/images/dist_docs/'.$pic['file_name'];
			}
		} 
		if(!empty($_FILES["pancard"]["name"])){
			$config['upload_path'] = './assets/images/dist_docs/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('pancard'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$pancard=base_url().'assets/images/dist_docs/'.$pic['file_name'];
			}
		} 
		if(!empty($_FILES["agreement"]["name"])){
			$config['upload_path'] = './assets/images/dist_docs/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg|pdf|txt|doc|docx';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('agreement'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$agreement=$pic['file_name'];
			}
		} 
		$data=array("agreement"=>$agreement,"ag_state"=>$_POST['state_id'],"staff_id"=>$_POST['staff_id'],"ag_name"=>$_POST['ag_name'],"ag_username"=>$_POST['ag_username'],"firm_name"=>$_POST['firm_name'],"ag_address"=>$_POST['ag_address'],"brid"=>$brr[0],"ag_city"=>$_POST['city'],"ag_mobile"=>$_POST['ag_mobile'],"pan_no"=>$_POST['pannum'],"ag_ad_front"=>$aadhar,"ag_ad_back"=>$ag_ad_back,"aadhar_no"=>$_POST['aadhar_no'],"pan_card"=>$pancard);
		$this->db->where("ag_id",$_POST['ag_id']);
		if($this->db->update("agents",$data)==true){
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Agent Updated Successfully.</div>');	
		}else{$this->session->set_flashdata('msg', '<div class="alert alert-danger">Agent Couldnot be Updated.</div>');	}
		redirect("admin/distributors");
	}
	
	public function add_staff(){
		$data=array("daddress"=>$_POST['daddress'],"dcode"=>$_POST['dcode'],"emp_type"=>$_POST['emp_type'],"emp_state"=>$_POST['emp_state'],"fname"=>$_POST['fname'],"mob1"=>$_POST['mob1'],"email"=>$_POST['email'],"u_username"=>$_POST['u_username'],"u_password"=>md5($_POST['u_password']),"added_date"=>date("Y-m-d"));
		if($this->db->insert("emps",$data)==true){
			//$lid=$this->db->insert_id();
//			$this->db->where("uid",$lid);
//			$this->db->update
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Staff Added Successfully.</div>');	
		}else{$this->session->set_flashdata('msg', '<div class="alert alert-danger">Staff Couldnot be Added.</div>');	}
		redirect("admin/staff");
	}
	
	public function update_staff(){
		$data=array("daddress"=>$_POST['daddress'],"dcode"=>$_POST['dcode'],"emp_type"=>$_POST['emp_type'],"fname"=>$_POST['fname'],"mob1"=>$_POST['mob1'],"email"=>$_POST['email'],"u_username"=>$_POST['u_username'],"added_date"=>date("Y-m-d"));
		$this->db->where("uid",$_POST['uid']);
		if($this->db->update("emps",$data)==true){
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Staff Details Updated Successfully.</div>');	
		}else{$this->session->set_flashdata('msg', '<div class="alert alert-danger">Staff Details Couldnot be Updated.</div>');	}
		redirect("admin/staff");
	}
	
	public function add_agent(){
		//echo "<pre>";print_r($_POST);print_r($_FILES);exit;
		//$brr=explode("-",$_POST['brid']);
		$aadhar=$aadhar2=$pancard=$agreement="";
		$ag_img="agent.jpg";
		if(!empty($_FILES["ag_ad_front"]["name"])){
			$config['upload_path'] = './assets/images/dist_docs/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('ag_ad_front'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$aadhar=base_url().'assets/images/dist_docs/'.$pic['file_name'];
			}
		} 
		if(!empty($_FILES["ag_ad_back"]["name"])){
			$config['upload_path'] = './assets/images/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('ag_ad_back'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$ag_ad_back=base_url().'assets/images/dist_docs/'.$pic['file_name'];
			}
		} 
		if(!empty($_FILES["pancard"]["name"])){
			$config['upload_path'] = './assets/images/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('pancard'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$pancard=base_url().'assets/images/dist_docs/'.$pic['file_name'];
			}
		} 
		$ag_img="agent.jpg";
		if(!empty($_FILES["ag_ad_front"]["name"])){
			$config['upload_path'] = './assets/images/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('ag_ad_front'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$aadhar=$pic['file_name'];
			}
		} 
		if(!empty($_FILES["agreement"]["name"])){
			$config['upload_path'] = './assets/images/dist_docs/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg|svg|pdf|txt|doc|docx';
			$config['max_size']	= '1000000';
			$this->upload->initialize($config);
			if (!$this->upload->do_upload('agreement'))
			{
			echo $this->upload->display_errors();
			}
			else
			{	
			$pic = $this->upload->data();
			$agreement=$pic['file_name'];
			}
		} 
		$data=array("agreement"=>$agreement,"staff_id"=>$_POST['staff_id'],"ag_name"=>$_POST['ag_name'],"ag_state"=>$_POST['state_id'],"ag_img"=>$ag_img,"firm_name"=>$_POST['firm_name'],"ag_address"=>$_POST['ag_address'],"ag_city"=>$_POST['city'],"ag_reg_date"=>date("Y-m-d"),"ag_mobile"=>$_POST['ag_mobile'],"ag_username"=>$_POST['ag_username'],"ag_password"=>md5($_POST['ag_password']),"ag_ad_front"=>$aadhar,"ag_ad_back"=>$ag_ad_back,"aadhar_no"=>$_POST['aadhar_no'],"pan_card"=>$pancard,"pan_no"=>$_POST['pannum']);
		if($this->db->insert("agents",$data)==true){
			$this->session->set_flashdata('msg', '<div class="alert alert-success">Distributor Added Successfully.</div>');	
		}else{$this->session->set_flashdata('msg', '<div class="alert alert-danger">Distributor Couldnot be Added.</div>');	}
		redirect("admin/distributors");
	}
	

	public function chknewmsguser(){

		$this->db->select("*");

		$this->db->from("chat");

		$this->db->join("chat_users","chat_users.cuid=chat.cuid");

		$this->db->where("chat.admin_read","");

		$this->db->group_by("chat.cuid");

		$data=$this->db->get()->result();

		print_r(json_encode($data));

	//	$this->load->view("admin/chknewmsguser",$data);

	}



	public function chat(){//echo "asdf";exit;

		$data['chat_users']=$this->db->get("chat_users")->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/chat',$data,true);

		$this->adminlayout(); 

	}

	

	public function loadchat(){

		if($this->db->get_where("chat",array("cuid"=>$_POST['id'],"admin_read"=>""))->num_rows()>0){

		$this->db->where("cuid",$_POST['id']);

		$this->db->update("chat",array("admin_read"=>"yes"));

		$data['msg']=$this->db->get_where("chat",array("cuid"=>$_POST['id']))->result();

		$this->load->view("admin/messages",$data);

		}else{

		echo 0;	

		}

	}



	public function fload(){

	$data['msg']=$this->db->get_where("chat",array("cuid"=>$_POST['id']))->result();

			$this->load->view("admin/messages",$data);

	}

	

	public function adminreply(){

		parse_str($_POST['formdata'],$form);

		if($form['msg']!=""){

		$this->db->insert("chat",array("msg_from"=>"admin","msg_to"=>"user","msg"=>$form['msg'],"chdate"=>date("Y-m-d H:i"),"cuid"=>$form['userid']));

		}

	}

	

	public function add_seo(){

	$data=array("meta_title"=>$this->input->post("meta_title"),"meta_key"=>$this->input->post("meta_key"),"meta_desc"=>$this->input->post("meta_desc"));

	$this->db->where("page",$this->input->post("page"));

	if($this->db->update("pages",$data)==true){

		//$link=str_replace(" ","-",$this->input->post("title"))."/".$this->db->insert_id();

		$this->session->set_flashdata('msg', '<div class="alert alert-success">SEO details updated successfully.</div>');

		

	}else{

		$this->session->set_flashdata('msg', '<div class="alert alert-danger">SEO details Could not be updated.</div>');

		

	}

	redirect("admin/PageSeo");

	}

	

	public function PageSeo($aid=false){

		$data['seo']=$this->db->get("pages")->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/pageseo',$data,true);

		$this->adminlayout(); 	

	}

	

	public function catenable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("cid",$_POST['id']);

		$this->db->update("category",array("cat_status"=>$st));	

	}
	
	public function influ_enable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("influ_id",$_POST['id']);

		$this->db->update("influs",array("influ_status"=>$st));	

	}
	public function prod_enable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("pid",$_POST['id']);

		$this->db->update("products",array("prod_status"=>$st));	

	}
	
	

	public function mcatenable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("mid",$_POST['id']);

		$this->db->update("mcategory",array("mcat_status"=>$st));	

	}

	public function store_enable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("store_id",$_POST['id']);

		$this->db->update("stores",array("st_status"=>$st));	

	}

	public function vendorenable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("vid",$_POST['id']);

		$this->db->update("vendors",array("v_status"=>$st));

		$ch = curl_init();

		$data="status=".$_POST['st']."&phone=".$_POST['ph'];//."&email=".$_POST['v_email']."&phone=".$_POST['v_phone'];

		curl_setopt($ch, CURLOPT_URL,"http://offera.in/frontend/home/vendorenable");

		curl_setopt($ch, CURLOPT_POST, 1);

		curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

		

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		

		$server_output = curl_exec($ch);

		//print_r($server_output);

		curl_close ($ch);	

	}

	

	public function store_proenable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("store_pid",$_POST['id']);

		$this->db->update("store_products",array("store_p_status"=>$st));	

	}

	public function proenable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("pid",$_POST['id']);

		$this->db->update("products",array("pstatus"=>$st));	

	}

	

	

	public function subcatenable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("sid",$_POST['id']);

		$this->db->update("subcategory",array("subcat_status"=>$st));	

	}

	

	public function packenable(){

		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}

		$this->db->where("packid",$_POST['id']);

		$this->db->update("packs",array("pack_status"=>$st));	

	}
	

	public function catdelete(){
		$this->db->delete("category",array("cid"=>$_POST['id'])) ;
 	}
	
	public function mcatdelete(){
		$this->db->delete("mcategory",array("mid"=>$_POST['id'])) ;
	}
	
	public function ajax_agent_areas(){
		$ids=explode("-",$_POST['id']);
		$data['agent']=$ids[0];
		$data['city']=$ids[1];
		$data['areas']=$this->db->get_where("city_areas",array("city_id"=>$ids[1]))->result();
		$this->db->select("*");
		$this->db->from("agent_areas");
		$this->db->join("city_areas","city_areas.area_id=agent_areas.area_id");
		$this->db->where("agent_areas.agent_id",$ids[0]);
		$data['agent_areas']=$this->db->get()->result();
		//echo "<pre>";print_r($data);exit;
		$this->load->view("admin/ajax_agent_areas",$data);
	}
	
	public function ajax_agent_delete(){
		$ids=explode("-",$_POST['id']);
		$this->db->delete("agents",array("ag_id"=>$ids[0]));
		$this->db->delete("delivery_times",array("city_id"=>$ids[1]));
		$this->db->delete("orders",array("admin_id"=>$ids[0]));
		$this->db->delete("prod_stock",array("admin_id"=>$ids[0]));
	}
	
	public function ajax_staff_delete(){
		$this->db->delete("emps",array("uid"=>$_POST['id']));
	}
	
	public function ajax_update_password(){
		parse_str($_POST['formdata'],$form);
		//print_r($form);exit;
		$this->db->where("ag_id",$form['emp_id']);
		if($this->db->update("agents",array("ag_password"=>md5($form['pass'])))==true){
			echo "Password Changed Successfully.";
		}else{
			echo "Password couldnot be changed.";
		}
	}
	
	public function ajax_update_staff_password(){
		parse_str($_POST['formdata'],$form);
		//print_r($form);exit;
		$this->db->where("uid",$form['emp_id']);
		if($this->db->update("emps",array("u_password"=>md5($form['pass'])))==true){
			echo "Password Changed Successfully.";
		}else{
			echo "Password couldnot be changed.";
		}
	}
	
	public function agent_enable(){
		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}
		$this->db->where("ag_id",$_POST['id']);
		$this->db->update("agents",array("ag_status"=>$st));	
	}
	
	public function staff_enable(){
		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}
		$this->db->where("uid",$_POST['id']);
		$this->db->update("emps",array("user_status"=>$st));	
	}
	
	public function ajax_agent_areas_assign(){
		//echo "<pre>";print_r($_POST);exit;
		$chk=$this->db->get_where("agent_areas",array("area_id"=>$_POST['id'],"agent_id"=>$_POST['agent']));
		if($chk->num_rows()==0){
			$this->db->insert("agent_areas",array("area_id"=>$_POST['id'],"agent_id"=>$_POST['agent'],"assign_date"=>date("Y-m-d")));	
		}else{
			$this->db->delete("agent_areas",array("area_id"=>$_POST['id'],"agent_id"=>$_POST['agent']));	
		}
	}
	
	public function ajax_addall_area(){
		if($_POST['type']=='add'){
		$careas=$this->db->get_where("city_areas",array("city_id"=>$_POST['city']))->result();
		foreach($careas as $car){
			if($this->db->get_where("agent_areas",array("area_id"=>$car->area_id,"agent_id"=>$_POST['agent']))->num_rows()==0){
				$this->db->insert("agent_areas",array("area_id"=>$car->area_id,"agent_id"=>$_POST['agent'],"assign_date"=>date("Y-m-d")));
			}
		}
		}else{
		$this->db->delete("agent_areas",array("agent_id"=>$_POST['agent']));	
		}
	}

	 public function vendordelete(){
		$this->db->delete("vendors",array("vid"=>$_POST['id']));
 	 }

	 public function brand_delete(){
		$this->db->delete("brands",array("brid"=>$_POST['id']));
 	 }

	 public function plandelete(){
		$this->db->delete("plans",array("plid"=>$_POST['id']));
 	 }

	 public function add_dept(){
		$brand_logo="brand.jpg";

		if(!empty($_FILES["brand_logo"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('brand_logo'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$brand_logo=$pic['file_name'];

				}

		}  
		$this->db->insert("brands",array("brand_logo"=>$brand_logo,"brname"=>$_POST['machine']));
		$this->session->set_flashdata('msg', '<div class="alert alert-success">Brand Added Successfully.</div>');	
		redirect("admin/brands");
	 }

	 public function update_dept(){
		 $brand_logo=$_POST['oldbrand_logo'];

		if(!empty($_FILES["brand_logo"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('brand_logo'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$brand_logo=$pic['file_name'];

				}

		}  
		$this->db->where("brid",$_POST['depid']);
		$this->db->update("brands",array("brand_logo"=>$brand_logo,"brname"=>$_POST['machine']));
		$this->session->set_flashdata('msg', '<div class="alert alert-success">Brand Updated Successfully.</div>');
		redirect("admin/brands");
	 }

	 public function brands($depid=false){
		if($depid==true){$data['edit']=$this->db->get_where("brands",array("brid"=>$depid))->row();}
		$data['deps']=$this->db->get("brands")->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/brands',$data,true);
		$this->adminlayout();
	 }

	 public function bandelete(){
    	if($this->db->delete("banner",array("bid"=>$_POST['id'])) && $_POST['img']!="default.png"){
		unlink(base_url()."assets/images/category/".$_POST['img']);		
		}

 	 }

	 

	public function packdelete(){

		if($this->db->delete("packs",array("packid"=>$_POST['id'])) && $_POST['img']!="default.png"){

		//unlink(base_url()."assets/images/products/".$_POST['img']);		

		}

 	 }

	 

  	public function agedelete(){

		$this->db->delete("admin",array("id"=>$_POST['id']));

  	}

  

  public function showallf(){

	  //echo "asdf";exit;

		$data['f']=$this->db->get_where("fields",array("sid"=>$_POST['id']))->result();

		$this->load->view("admin/ajax_fields",$data);

  }

  

  public function add_fields(){

	  parse_str($_POST['formdata'],$form);

	  //echo $_POST['id'];exit;

	  $this->db->insert("fields",array("f_title"=>$form['label'],"f_type"=>$form['type'],"f_values"=>$form['vals'],"sid"=>$form['sid']));

	  $data['f']=$this->db->get_where("fields",array("sid"=>$form['sid']))->result();

		$this->load->view("admin/ajax_fields",$data);

  }

  

  public function remove_f(){

	  $this->db->delete("fields",array("fid"=>$_POST['id']));

  }

  //Manage Category Add/Edit

  public function category($id=false){
		if($id==true){
			$data['editcat']=$this->db->get_where("category",array("cid"=>$id))->row();
		}
		$data['cats']=$this->db->get("category")->result();  
		$this->load->view ($this->middle = 'admin/category',$data,true);
      	$this->adminlayout();
  }
  
  public function influs($id=false){
		if($id==true){
			$data['edit']=$this->db->get_where("influs",array("influ_id"=>$id))->row();
		}
		$data['cats']=$this->db->get("influs")->result();  
		$this->load->view ($this->middle = 'admin/influs',$data,true);
      	$this->adminlayout();
  }

  public function mcategory($id=false){

		if($id==true){

			$data['editcat']=$this->db->get_where("mcategory",array("mid"=>$id))->row();

		}

		$data['cats']=$this->db->get("mcategory")->result();  

		$this->load->view ($this->middle = 'admin/mcategory',$data,true);

      	$this->adminlayout();

  }

  

  public function Plans($id=false){

		if($id==true){

			$data['edit']=$this->db->get_where("plans",array("plid"=>$id))->row();

		}

		$data['plans']=$this->db->get("plans")->result();  

		$this->load->view ($this->middle = 'admin/plans',$data,true);

      	$this->adminlayout();

  }

  public function ajax_city(){
	    //echo "<pre>";print_r($_POST);exit;

		$city=$this->db->get_where("cities",array("city_state"=>$_POST['id']))->result();

		echo '<option value="">Select City</option>';

		foreach($city as $c){echo '<option value="'.$c->city_id.'">'.$c->city_name.'</option>';}	

	}

  

  public function vendors($id=false){

		if($id==true){

			$data['vendor']=$this->db->get_where("vendors",array("vid"=>$id))->row();

		}

		$this->db->select("*");

		$this->db->from("vendors");

		//$this->db->join("states","vendors.vstate=states.state_id");

		//$this->db->join("cities","vendors.vcity=cities.city_id");

		$data['vendors']=$this->db->get()->result();  

		$this->load->view ($this->middle = 'admin/vendor',$data,true);

      	$this->adminlayout();

  }

  

   public function ajax_remove_imgs(){

		//$ad=$this->db->get_where("products",array("pid"=>$_POST['aid']))->row();

		$imgs=explode(",",$_POST['oldimgs']);

		$to_remove = array($_POST['img']);

		$result = array_diff($imgs, $to_remove); 

		$imgs= implode(",",$result);

		//$this->db->where("aid",$_POST['aid']

		echo $imgs; 

	  }

	  

   public function ajax_remove_colors(){

	$o=explode("|",$_POST['old']);

	$ad=$this->db->get_where("products",array("pid"=>$_POST['aid']))->row();

	$cols=explode(",",$_POST['oldcols']);

	$oldcolor=explode(",",$_POST['oldcolor']);

	$to_remove1 = array($o[0]);

	$to_remove2 = array($o[1]);

	$result1 = array_diff($cols, $to_remove1); 

	$result2 = array_diff($oldcolor, $to_remove2); 

	$imgs= implode(",",$result1).'|'.implode(",",$result2);

	//$this->db->where("aid",$_POST['aid']

	echo $imgs; 

  }

  

  public function banner($id=false){

		if($id==true){

			$data['editcat']=$this->db->get_where("banner",array("bid"=>$id))->row();

		}

		$data['ban']=$this->db->get("banner")->result();

		$data['cats']=$this->db->get("category")->result();  

		$this->load->view ($this->middle = 'admin/banner',$data,true);

      	$this->adminlayout();

  }

  

  public function packs($id=false){

		if($id==true){

			$data['p']=$this->db->get_where("packs",array("packid"=>$id))->row();

		}

		$data['packs']=$this->db->get("packs")->result();  

		$data['cats']=$this->db->get("category")->result();  

		$this->load->view ($this->middle = 'admin/packs',$data,true);

      	$this->adminlayout();

  }

  

  public function add_pack(){

	//echo "<pre>";print_r($_POST);exit;  

			$img='default.jpg';

			if(!empty($_FILES["profile_img"]["name"])){

				$config['upload_path'] = './assets/images/products/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('profile_img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

					

				$img=$pic['file_name'];

				} 

			}

		$pros=implode(",",$_POST['designs']);

		$packin=$this->db->insert("packs",array("ptitle"=>$this->input->post("title"),"pprice"=>$this->input->post("price"),

									"pthumb"=>$img,"pimgs"=>$pros));//exit;

		if($packin==true){

			$this->session->set_flashdata('msg', '<div class="alert alert-success">Design Pack has been Added to Stock successfully.</div>');	

		}else{

			$this->session->set_flashdata('msg', '<div class="alert alert-danger">Design Pack Could not be added to stock. Please try later.</div>');	

		}

		redirect('admin/packs');		

  }

  

  

  public function in_trend(){

	$this->db->where("sid",$_POST['id']);

	$this->db->update("subcategory",array("in_trend"=>$_POST['v']));  

  }

  public function in_trendcat(){

	$this->db->where("cid",$_POST['id']);

	$this->db->update("category",array("in_trend"=>$_POST['v']));  

  }

  

   public function pack_trend(){

	$this->db->where("packid",$_POST['id']);

	$this->db->update("packs",array("ptrend"=>$_POST['v']));  

  }

  

  public function pro_trend(){
	//print_r($_POST);
	$this->db->where("pid",$_POST['id']);

	$this->db->update("products",array("feat"=>$_POST['v']));  

  }
  
  public function pro_trend2(){
	//print_r($_POST);
	$this->db->where("pid",$_POST['id']);

	$this->db->update("products",array("book_pro"=>$_POST['v']));  

  }

  

  public function set_deal_submit(){

	  parse_str($_POST['formdata'],$form);

	  //print_r($form);exit;

	  $data=array("pro_id"=>$form['pid'],"deal_date"=>$form['date'],"deal_start"=>$form['start_time'],"deal_end"=>$form['end_time']);

		if($form['did']!=""){

			$this->db->where("deal_id",$form['did']);

			$query=$this->db->update("deals",$data);

		}else{

			$query=$this->db->insert("deals",$data);

		}

		if($query==true){//echo "Set";}else{echo "Not set";}

		$data['prod']=$this->db->get_where("products",array("pid"=>$form['pid']))->row(); 

	    $data['deals']=$this->db->get_where("deals",array("deal_date >="=>date("Y-m-d"),"pro_id"=>$form['pid']))->result();

		$data['deal']=array(); 

		$this->load->view("admin/set_deals",$data);

		}else{echo 0;}

  }

  

  public function deal_pro(){

	$data['pid']=$_POST['pid'];

	//print_r($_POST);exit;

	$data['prod']=$this->db->get_where("products",array("pid"=>$_POST['pid']))->row(); 

	$data['deals']=$this->db->get_where("deals",array("deal_date >="=>date("Y-m-d"),"pro_id"=>$_POST['pid']))->result();

	if(isset($_POST['d'])){

		$data['apid']=$_POST['d'];

		$data['deal']=$this->db->get_where("deals",array("pro_id"=>$_POST['pid'],"deal_id"=>$_POST['d']))->row(); 

	}else{

		$data['deal']=array(); 

	}

	//echo "<pre>";print_r($data);exit;

	$this->load->view("admin/set_deals",$data);

  }

  

  public function delete_deal(){

	$this->db->delete('deals',array('deal_id'=>$_POST['id']));  

  }
   public function influ_delete(){

	$this->db->delete('influs',array('influ_id'=>$_POST['id']));  

  }


  

  public function buy_now(){

	$this->db->where("pid",$_POST['id']);

	$this->db->update("products",array("buy_now"=>$_POST['v']));  

  }

  public function autoclone(){

	//  print_r($_POST);exit;

	$chk= $this->db->get_where("products",array("autoclone"=>""))->num_rows();

	if($_POST['v']!="" && $chk>=4){

		echo "Max 4 Auctions can be set to Autoclone.";

	}else{

	$this->db->where("pid",$_POST['id']);

	$this->db->update("products",array("autoclone"=>$_POST['v']));  

	echo "Autoclone Set";

	}

  }

  public function ad_status(){

	$this->db->where("aid",$_POST['id']);

	$this->db->update("ads",array("ad_status"=>$_POST['v']));  

  }

  

  public function update_product_submit(){

	 		//echo "<pre>";print_r($_POST);print_r($_FILES);exit;

			$img=$_POST['oldprofile_img'];

			if(!empty($_FILES["profile_img"]["name"])){

				$config['upload_path'] = './assets/images/products/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg|webp';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('profile_img'))

				{

					echo $this->upload->display_errors();

				}

				else

				{	

					$pic = $this->upload->data();

					$img=$pic['file_name'];

				} 

			}	

		

			$r2="";

			if(!empty($_FILES['test11']['name'])){//echo "asdf";

			$r2=array('No_Image_Available.jpg');

            $filesCount = count($_FILES['test11']['name']);

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

                $_FILES['userFile']['name'] = $_FILES['test11']['name'][$i];

                $_FILES['userFile']['type'] = $_FILES['test11']['type'][$i];

                $_FILES['userFile']['tmp_name'] = $_FILES['test11']['tmp_name'][$i];

                $_FILES['userFile']['error'] = $_FILES['test11']['error'][$i];

                $_FILES['userFile']['size'] = $_FILES['test11']['size'][$i];



                $uploadPath = './assets/images/products/';

                $config['upload_path'] = $uploadPath;

                $config['allowed_types'] = 'gif|jpg|png|jpeg';

                

                $this->upload->initialize($config);

                if($this->upload->do_upload('userFile')){

                    $fileData = $this->upload->data();

					array_push($r2,$fileData['file_name']);

                   // $uploadData[$i]['file_name'] = $fileData['file_name'];

                }if($i==0){array_shift($r2);}

            }

			$r2=implode(",",$r2);

			

        	}

			//$price=$oprice=$qty=$packs=$prices=$oprices=$qtys="";
//
//			if($_POST['ptype']=="Normal"){
//
//			$price=$_POST['nprice'];	
//
//			$oprice=$_POST['noprice'];	
//
//			$qty=$_POST['nqty'];	
//
//			}else{
//
//			$packs=implode(",",$_POST['pack']);	
//
//			$prices=implode(",",$_POST['price']);
//
//			if($_POST['oprice'][0]!=""){
//
//			$oprices=implode(",",$_POST['oprice']);
//
//			}
//
//			$qtys=implode(",",$_POST['qty']);
//
//			}
//
//			if(isset($_POST['no_of_pc'])){$pieces=$_POST['no_of_pc'];}else{$pieces="";}
			$sizes="";
			if($_POST['sizes']){$sizes=implode(",",$_POST['sizes']);}
			$this->db->where("pid",$_POST['pid']);
	  		$insert=$this->db->update("products",array("color"=>$_POST['color'],
			"fabric"=>$_POST['fabric'],"psizes"=>$sizes,"sid"=>$_POST['cid2'],"qtys"=>$_POST['qtys'],"book_last_date"=>$_POST['book_last_date'],"wr_month"=>$_POST['wr_month'],"prod_slug"=>str_replace(" ","-",strtolower($_POST['prod_slug'])),"cid"=>$_POST['cid'],"price"=>$_POST['price'],"oprice"=>$_POST['oprice'],"book_amt"=>$_POST['book_amt'],"sdesc"=>$this->input->post("sdesc"),"title"=>$this->input->post("title"),"pdesc"=>$this->input->post("pdesc"),"extimgs"=>$r2,"img"=>$img));

			if($insert==true){		
				
					
				$this->session->set_flashdata('msg', '<div class="alert alert-success">Product has been Updated to Stock successfully.</div>');

			}else{

				$this->session->set_flashdata('msg', '<div class="alert alert-danger">Product Could not be Updated to stock. Please try later.</div>');

			}

			redirect('admin/products_list');

  }
  
  public function order_submit(){
	    //echo "<pre>";print_r($this->session->all_userdata());exit;
	 	//echo "<pre>";print_r($_POST);
		//$shipping=$_POST['shipping'];
		//$grand_total=$
		$stt=$this->db->get_where("states",array("state_id"=>$_POST['state']))->row();	
		$bstate=$stt->state_name;
	  	$mon=date("M-Y");
		$data=$this->db->insert("orders",array("ostatus"=>"Confirmed","bstate"=>$bstate,"shiptot"=>$_POST['shipping'],"grand_total"=>$_POST['total'],"odis"=>$_POST['discount'],"omonth"=>$mon,"userid"=>$_POST['uid'],"odate"=>date("Y-m-d"),"ototal"=>$_POST['total'],"bname"=>$_POST['customer'],"baddress"=>$_POST['address'],"bitems"=>1,"bcity"=>$_POST['city'],"bpin"=>$_POST['pincode'],"admin_id"=>$this->session->userdata("userid")));
		$oid=$this->db->insert_id();
		
		$order_uid="Y1".date("Ym").$oid;
		$this->db->where("oid",$oid);
		$this->db->update("orders",array("order_uid"=>$order_uid));
		
		$wdate = date("d/m/Y", strtotime(" +".$_POST['wrt']." months"));
		$data=array("wr_end"=>$wdate,"wr_period"=>$_POST['wrt'],"oitem_uid"=>$_POST['uid'],"item_wid"=>$order_uid.'1',"wr_start"=>date("d/m/Y"),"oid"=>$oid,"pid"=>$_POST['pid'],"price"=>$_POST['subtotal'],"pname"=>$_POST['product'],"pimg"=>$_POST['pimg'],"qty"=>1,"subtotal"=>$_POST['subtotal']);
				$this->db->insert("order_items",$data);	
				redirect("admin/orders/Confirmed");
	//echo "<pre>";print_r($data);exit;

		//if($this->db->insert("orders",$data)==true){ 
  }	
  
  public function ajax_search_customer(){
	  	$this->db->select("*");
		$this->db->like("first_name",$_POST['cust']);
		$this->db->or_like("email",$_POST['cust']);
		$this->db->or_like("mobile",$_POST['cust']);
		$data['custs']=$this->db->get('users')->result();
		$this->load->view("admin/ajax_search_customer",$data);
  }
  
  public function ajax_search_product(){
	  	$this->db->select("*");
		$this->db->like("title",$_POST['pro']);
		$data['pros']=$this->db->get('products')->result();
		$this->load->view("admin/ajax_search_pro",$data);
  }
  
  public function create_order($customer=false){//
		$data=array();///['cats']=$this->db->get("category")->result();  
		$this->load->view ($this->middle = 'admin/create_order',$data,true);
		$this->adminlayout();   
  }	
  
  public function add_product_submit(){

	 		//echo "<pre>";print_r($_POST);print_r($_FILES);exit;

			$img='default.jpg';

			if(!empty($_FILES["profile_img"]["name"])){

				$config['upload_path'] = './assets/images/products/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg|webp';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('profile_img'))

				{

					echo 'Error '.$this->upload->display_errors();

				}

				else

				{	

					$pic = $this->upload->data();

					$img=$pic['file_name'];

				} 

			}	

		

			$r2="";

			if(!empty($_FILES['test11']['name'])){//echo "asdf";

			$r2=array('No_Image_Available.jpg');

            $filesCount = count($_FILES['test11']['name']);

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

                $_FILES['userFile']['name'] = $_FILES['test11']['name'][$i];

                $_FILES['userFile']['type'] = $_FILES['test11']['type'][$i];

                $_FILES['userFile']['tmp_name'] = $_FILES['test11']['tmp_name'][$i];

                $_FILES['userFile']['error'] = $_FILES['test11']['error'][$i];

                $_FILES['userFile']['size'] = $_FILES['test11']['size'][$i];



                $uploadPath = './assets/images/products/';

                $config['upload_path'] = $uploadPath;

                $config['allowed_types'] = 'gif|jpg|png|jpeg|webp';

                

                $this->upload->initialize($config);

                if($this->upload->do_upload('userFile')){

                    $fileData = $this->upload->data();

					array_push($r2,$fileData['file_name']);

                   // $uploadData[$i]['file_name'] = $fileData['file_name'];

                }if($i==0){array_shift($r2);}

            }

			$r2=implode(",",$r2);

			

        	}

			//$price=$oprice=$qty=$packs=$prices=$oprices=$qtys="";
//
//			if($_POST['ptype']=="Normal"){
//
//			$price=$_POST['nprice'];	
//
//			$oprice=$_POST['noprice'];	
//
//			$qty=$_POST['nqty'];	
//
//			}else{
//
//			$packs=implode(",",$_POST['pack']);	
//
//			$prices=implode(",",$_POST['price']);
//
//			if($_POST['oprice'][0]!=""){
//
//			$oprices=implode(",",$_POST['oprice']);
//
//			}
//
//			$qtys=implode(",",$_POST['qty']);
//
//			}
//
//			if(isset($_POST['no_of_pc'])){$pieces=$_POST['no_of_pc'];}else{$pieces="";}
			
			
$sizes="";
if($_POST['sizes']){$sizes=implode(",",$_POST['sizes']);}
	  		$insert=$this->db->insert("products",array("sid"=>$_POST['cid2'],"color"=>$_POST['color'],
			"fabric"=>$_POST['fabric'],"psizes"=>$sizes,"qtys"=>$_POST['qtys'],"book_last_date"=>$_POST['book_last_date'],"wr_month"=>$_POST['wr_month'],"prod_slug"=>$_POST['prod_slug'],"cid"=>$_POST['cid'],"price"=>$_POST['price'],"book_amt"=>$_POST['book_amt'],"oprice"=>$_POST['oprice'],"sdesc"=>$this->input->post("sdesc"),"title"=>$this->input->post("title"),"pdesc"=>$this->input->post("pdesc"),"extimgs"=>$r2,"img"=>$img));

			if($insert==true){		
				
					
				$this->session->set_flashdata('msg', '<div class="alert alert-success">Product has been Added to Stock successfully.</div>');

			}else{

				$this->session->set_flashdata('msg', '<div class="alert alert-danger">Product Could not be added to stock. Please try later.</div>');

			}

			redirect('admin/products_list');

  }
  
  public function ajax_gallery_form_submit(){
		//print_r($_POST);exit;
		
				$config['upload_path'] = './assets/images/products/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|webp';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('gall_img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();
				$gall_img=$pic['file_name'];
				
				}
		//parse_str($_POST['formdata'],$form);
		//echo "<pre>";print_r($form);exit;
		if($this->db->insert("pgallery",array("pg_img"=>$gall_img,"pid"=>$_POST['pid'],"pcolor"=>$_POST['pcolor']))==true){
		echo "Image added";
		}else{echo "Image Couldnot be added";}
	}
	
	public function ajax_gallery(){
		//print_r($_POST);exit;
		$data['galls']=$this->db->get_where("pgallery",array("pid"=>$_POST['id']))->result();
		//print_r($data);exit;
		$data['pid']=$_POST['id'];
		$this->load->view("admin/ajax_gallery",$data);	
	}

  public function addprod(){
	  	$data=array();///['cats']=$this->db->get("category")->result();  
		$this->load->view ($this->middle = 'admin/addprod',$data,true);
		$this->adminlayout(); 
  }
  
  public function list_products(){
	$data=array();///['cats']=$this->db->get("category")->result();  
	$this->load->view ($this->middle = 'admin/list_products',$data,true);
	$this->adminlayout(); 
  }
  
  public function products_nav(){
		//$data['ostatus']=$_POST['ostatus'];
//		if($_POST['ostatus']!=''){
//		$this->db->where("ostatus",$_POST['ostatus']);
//		}
		if($_POST['mid']!=''){$this->db->where("mid",$_POST['mid']);}
		if($_POST['cid']!=''){$this->db->where("cid",$_POST['cid']);}
		if($_POST['sid']!=''){$this->db->where("sid",$_POST['sid']);}
		if($_POST['brand']!=''){$this->db->where("brand",$_POST['brand']);}
		if($_POST['title']!=''){$this->db->like("title",$_POST['title']);}
		
		
		$data['navs']=$this->db->get("products")->num_rows();	
		//print_r($data);exit;
		$data['mid']=$_POST['mid'];
		$data['cid']=$_POST['cid'];
		$data['sid']=$_POST['sid'];
		$data['brand']=$_POST['brand'];
		$data['title']=$_POST['title'];
		$this->load->view("admin/navs",$data);
	}

  public function ajax_list_customers(){
		$this->db->select("*");
		$this->db->from('users');
		//$this->db->join("users","orders.userid=users.id");
//		//if($type==true && $type=="Completed"){
////		$this->db->where("orders.ostatus","Completed");
////		}
//		if($_POST['ostatus']!=''){
//		$this->db->where("ostatus",$_POST['ostatus']);
//		}
		$this->db->limit(10,$_POST['offset']);
		$this->db->order_by("users.id","desc");
		$data['customers']=$this->db->get()->result();
		//$data['page']=$_POST['offset'];
		$this->load->view("admin/ajax_list_customers",$data); 
  }
  
  public function ajax_list_product(){
		$this->db->select("*");
		$this->db->from('products');
		$this->db->join("brands","brands.brid=products.brand","left");
		$this->db->join("mcategory","mcategory.mid=products.mid","left");
//		//if($type==true && $type=="Completed"){
////		$this->db->where("orders.ostatus","Completed");
////		}
//		if($_POST['ostatus']!=''){
//		$this->db->where("ostatus",$_POST['ostatus']);
//		}
		if($_POST['mid']!=''){$this->db->where("products.mid",$_POST['mid']);}
		if($_POST['cid']!=''){$this->db->where("products.cid",$_POST['cid']);}
		if($_POST['sid']!=''){$this->db->where("products.sid",$_POST['sid']);}
		if($_POST['brand']!=''){$this->db->where("products.brand",$_POST['brand']);}
		if($_POST['title']!=''){$this->db->like("products.title",$_POST['title']);}
		
		$this->db->limit(10,$_POST['offset']);
		$this->db->order_by("products.pid","desc");
		$data['products']=$this->db->get()->result();
		$data['page']=$_POST['offset'];
		$this->load->view("admin/ajax_list_product",$data);
  }

  public function coupons(){
	 $this->db->select("*");
	 $this->db->from("coupons");
	 //$this->db->join("cities","cities.city_id=coupons.city_id","left");
	 $this->db->order_by("coupons.exp_date","desc");
	 $data['coupons']=$this->db->get()->result();
	 $this->load->view ($this->middle = 'admin/coupons',$data,true);
     $this->adminlayout();
  }  

  public function add_coupon($edit=false){

		  if($edit==true)

		  {

			 //print_r($_POST); 

		$cfile=$this->input->post("oldt");

		if(!empty($_FILES["cfile"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('cfile'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$cfile=$pic['file_name'];

				}

		}

	  

		 $data=array("code"=>$this->input->post("code"),"exp_date"=>$_POST['exp_date'],

	 			 "title"=>$this->input->post("title"),"min_order"=>$_POST['min_order'],

	 			 "desc"=>$this->input->post("desc"),

	 			 "distype"=>$this->input->post("type"),

				 "disvalue"=>$this->input->post("value"),

				 "image"=>$cfile,

				 "valid"=>date("Y-m-d"));

				 $this->db->where("id",$edit);

				 if($this->db->update('coupons',$data))

				 {

					$msg="Coupon Updated Successfully.";

				 }

				 else

				 {

					 $msg="Coupon Couldnot be Updated.";

				 }

	

		  }

	   else

	    {

	

		$cfile="coupon.jpg";

		if(!empty($_FILES["cfile"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('cfile'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$cfile=$pic['file_name'];

				}

		}

	  

	 $data=array("code"=>$this->input->post("code"),"exp_date"=>$_POST['exp_date'],

	 			 "title"=>$this->input->post("title"),"min_order"=>$_POST['min_order'],

	 			 "desc"=>$this->input->post("desc"),

	 			 "distype"=>$this->input->post("type"),

				 "disvalue"=>$this->input->post("value"),

				 "image"=>$cfile,

				 "valid"=>date("Y-m-d"));

				 if($this->db->insert('coupons',$data))

				 {

					$msg="New Coupon Added Successfully.";

				 }

				 else

				 {

					 $msg="Coupon Couldnot be Added.";

				 }

				

	

	  

	    }

	  redirect("admin/coupons");

  }
  
  public function c_enable(){
		if($_POST['st']=="Disable"){$st="Disable";}else{$st="";}
		$this->db->where("id",$_POST['id']);
		$this->db->update("coupons",array("status"=>$st));	
	}

  public function coupon_delete(){

	$this->db->delete('coupons', array('id' => $_POST['id']));

  }
  public function gallery_delete(){
	$this->db->delete('pgallery', array('pg_id' => $_POST['id']));
  }
  public function book_delete(){

	$this->db->delete('pre_booking', array('pre_bid' => $_POST['id']));

  }
  

  public function ajax_view_bank(){
		$bank=$this->db->get_where("agents",array("ag_id"=>$_POST['id']))->row();
		?><table class="table table-condensed table-bordered">
        	<tr><th>Bank</th><td><?php echo $bank->bank_name;?></td></tr>
        	<tr><th>Account Name</th><td><?php echo $bank->acc_no;?></td></tr>
        	<tr><th>Account No</th><td><?php echo $bank->acc_name;?></td></tr>
        	<tr><th>IFSC</th><td><?php echo $bank->ifsc_code;?></td></tr>
        	<tr><th>Branch</th><td><?php echo $bank->bank_branch;?></td></tr>
        </table>
        <?php   
  }

  public function edit_product_submit(){

 	 	  //echo "<pre>";print_r($_POST);print_r($_FILES);exit;

		//  $colors=implode(",",$this->input->post("colors"));

			$img=$this->input->post("oldimg");

			if(!empty($_FILES["profile_img"]["name"])){

				$config['upload_path'] = './assets/images/products/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('profile_img'))

				{

					echo $this->upload->display_errors();

				}

				else

				{	

					$pic = $this->upload->data();

					

					$img=$pic['file_name'];

				} 

			}

				

			$r2="";

			if(!empty($_FILES['test11']['name'])){//echo "asdf";

			$r2=array('No_Image_Available.jpg');

            $filesCount = count($_FILES['test11']['name']);

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

                $_FILES['userFile']['name'] = $_FILES['test11']['name'][$i];

                $_FILES['userFile']['type'] = $_FILES['test11']['type'][$i];

                $_FILES['userFile']['tmp_name'] = $_FILES['test11']['tmp_name'][$i];

                $_FILES['userFile']['error'] = $_FILES['test11']['error'][$i];

                $_FILES['userFile']['size'] = $_FILES['test11']['size'][$i];



                $uploadPath = './assets/images/products/';

                $config['upload_path'] = $uploadPath;

                $config['allowed_types'] = 'gif|jpg|png|jpeg';

                

                $this->upload->initialize($config);

                if($this->upload->do_upload('userFile')){

                    $fileData = $this->upload->data();

					array_push($r2,$fileData['file_name']);

                   // $uploadData[$i]['file_name'] = $fileData['file_name'];

                }if($i==0){array_shift($r2);}

            }

			$r2=implode(",",$r2);

        	}

			//echo $r2;exit;

			if($r2!="" && $this->input->post("oldimgs")!=""){

				$r2=$this->input->post("oldimgs").','.$r2;	

			}else if($this->input->post("oldimgs")!=""){

				$r2=$this->input->post("oldimgs");

			}

			//echo $r2;exit;	

			
		$this->db->where("pid",$this->input->post("proid"));

	

		$insert=$this->db->update("products",array("prod_slug"=>$_POST['prod_slug'],"mid"=>$_POST['mcat'],"tags"=>$this->input->post("tags"),"brand"=>$_POST['brand'],"sdesc"=>$this->input->post("editor1"),"title"=>$this->input->post("title"),"meta_title"=>$this->input->post("meta_title"),"meta_key"=>$this->input->post("meta_key"),"meta_desc"=>$this->input->post("meta_desc"),"og_title"=>$this->input->post("og_title"),"extimgs"=>$r2,"img"=>$img,"og_desc"=>$this->input->post("og_desc")));

		

		//$insert=$this->db->update("products",array("sdesc"=>$this->input->post("sdesc"),"qty"=>$this->input->post("qty"),"price"=>$this->input->post("price"),"oprice"=>$this->input->post("oprice"),"gender"=>$this->input->post("gender"),"tags"=>$this->input->post("tags"),"cid"=>$this->input->post("cat"),"sid"=>$this->input->post("subcat"),"title"=>$this->input->post("title"),"meta_title"=>$this->input->post("meta_title"),"meta_key"=>$this->input->post("meta_key"),"meta_desc"=>$this->input->post("meta_desc"),"og_title"=>$this->input->post("og_title"),"gallery"=>$r1,"extimgs"=>$r2,"img"=>$img,"og_desc"=>$this->input->post("og_desc")));

			if($insert==true){

				$this->session->set_flashdata('msg', '<div class="alert alert-success">Product has been updated to Stock successfully.</div>');

			}else{

				$this->session->set_flashdata('msg', '<div class="alert alert-danger">Product Could not be updated to stock. Please try later.</div>');

			}

			redirect('admin/add_product/'.$this->input->post("proid"));

  }
  
  public function ajax_pvariants(){
		$data['pid']=$_POST['pid'];
		$data['pvars']=$this->db->get_where("prod_variants",array("pid"=>$_POST['pid']))->result();  
		$this->load->view("admin/ajax_pvariants",$data);
  }
  
  public function variant_delete(){
		$this->db->delete("prod_variants",array("pvid"=>$_POST['id']));
  }

  public function ajax_update_form(){
	  	//parse_str($_POST['formdata'],$form);
		//print_r($_POST);exit;
		$this->db->where("pvid",$_POST['pvid']);
		$this->db->update("prod_variants",array("case_rate"=>$_POST['case_rate'],"unit_rate"=>$_POST['unit_rate'],"pmrp"=>$_POST['pmrp'],"pptype"=>$_POST['pptype'],"ppieces"=>$_POST['ppieces']));
		echo "Update Details";
  }
  
  public function ajax_add_form(){
		$this->db->insert("prod_variants",array("pid"=>$_POST['pid'],"pmrp"=>$_POST['pmrp'],"case_rate"=>$_POST['case_rate'],"unit_rate"=>$_POST['unit_rate'],"pptype"=>$_POST['pptype'],"ppieces"=>$_POST['ppieces']));
		echo "Variant Added";
  }

  public function store_products(){

	$this->db->select("*");

	$this->db->from("store_products");

	$this->db->join("products","products.pid=store_products.pid");

	$this->db->where("store_products.vid",$this->session->userdata("userid"));

	$this->db->group_by("store_products.pid");

	$data['products']=$this->db->get()->result();

	$this->template['middle'] = $this->load->view ($this->middle = 'admin/store_products',$data,true);

	$this->adminlayout();   

  }

  

  public function add_to_store_submit(){

		//echo "<pre>";

		//print_r($_POST);exit;

			$price=$oprice=$qty=$packs=$prices=$oprices=$qtys="";

			if($_POST['ptype']=="Normal"){

			$price=$_POST['nprice'];	

			$oprice=$_POST['noprice'];	

			$qty=$_POST['nqty'];	

			}else{

			$packs=implode(",",$_POST['pack']);	

			$prices=implode(",",$_POST['price']);

			if($_POST['oprice'][0]!=""){

			$oprices=implode(",",$_POST['oprice']);

			}

			$qtys=implode(",",$_POST['qty']);

			}

		//if($r1==""){$r1="No_Image_Available.jpg";}	

			foreach($_POST['stores'] as $st){

				$ids=explode("-",$st);

	  		$insert=$this->db->insert("store_products",array("city_id"=>$ids[1],"vid"=>$this->session->userdata("userid"),"store_id"=>$ids[1],"pid"=>$_POST['pid'],"price_type"=>$_POST['ptype'],"st_price"=>$price,"st_oprice"=>$oprice,"st_qty"=>$qty,"st_packs"=>$packs,"st_prices"=>$prices,"st_oprices"=>$oprices,"st_qtys"=>$qtys,"pro_title"=>$this->input->post("title")));

			if($insert==true){						

				$this->session->set_flashdata('msg', '<div class="alert alert-success">Product Added to Store successfully.</div>');

			}else{

				$this->session->set_flashdata('msg', '<div class="alert alert-danger">Product Could not be added to stock. Please try later.</div>');

			}}//exit;

			redirect('admin/store_products');	

	}

  public function add_to_store($id,$edit=false){

	  if($edit==true){

		$this->db->select("*");

		$this->db->from("store_products");

		$this->db->join("products","products.pid=store_products.pid");

		$this->db->where("store_products.vid",$this->session->userdata("userid"));

		$data['products']=$this->db->get()->result();

	  }else{

	    $data['prod']=$this->db->get_where("products",array("pid"=>$id))->row();

	  }

	  $this->db->select("*");

	  $this->db->from("stores");

	  $this->db->join("states","stores.st_state=states.state_id");

      $this->db->join("cities","stores.st_city=cities.city_id");

	  $this->db->where("stores.vid",$this->session->userdata("userid"));

	  $data['stores']=$this->db->get()->result();

	  $this->load->view ($this->middle = 'admin/add_to_store',$data,true);

      $this->adminlayout();

  }		

  

  public function all_products(){

		$this->db->select("*");

		$this->db->from('products');

		$this->db->order_by("products.pid","desc");

		$data['products']=$this->db->get()->result();

		$this->load->view ($this->middle = 'admin/all_products',$data,true);

      	$this->adminlayout();  

  }

  

  public function products(){

		$this->db->select("*");

		$this->db->from('products');

		//$this->db->join("brands","products.brand=brands.brid");

		//$this->db->join("vendors","vendors.vid=products.vendor");

		if($this->session->userdata("type")=="vendor"){

			$this->db->where("products.vendor",$this->session->userdata("userid"));

		}

		$this->db->order_by("products.pid","desc");

		$data['products']=$this->db->get()->result();

		$this->load->view ($this->middle = 'admin/products',$data,true);

      	$this->adminlayout();

	}

  

  public function add_banner(){
	  	//echo "<pre>";print_r($_POST);exit;

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  
//"banner_title"=>$this->input->post("banner_title"),"banner_desc"=>$this->input->post("banner_desc"),
			$data=array("banner_link"=>$this->input->post("banner_link"),"banner_title"=>$this->input->post("banner_title"),"banner_desc"=>$this->input->post("banner_desc"),"banner_img"=>$img);

			if($this->db->insert("banner",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Banner Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Banner Couldnot be Added.</div>");

			}

		redirect("admin");

  }

  public function delete_banner(){

		$this->db->where("banner_id",$_POST['id']);

		$this->db->delete("banner");

  	}

  public function update_banner(){
		
	  	//echo "<pre>";print_r($_POST);exit;
		$img=$this->input->post("oldimg");

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("banner_title"=>$this->input->post("banner_title"),"banner_desc"=>$this->input->post("banner_desc"),"banner_link"=>$this->input->post("banner_link"),"banner_img"=>$img);

			$this->db->where("banner_id",$this->input->post("bid"));

			if($this->db->update("banner",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Banner Updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Banner Couldnot be Updated.</div>");

			}

		redirect("admin");

  }

  



  public function add_predesigns($id=false){

  		$front='front.jpg';$back='back.jpg';$side1='side1.jpg';$side2="side2.jpg";

		if(!empty($_FILES["front"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('front'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$front=$pic['file_name'];

				}

		}  

		if(!empty($_FILES["back"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('back'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$back=$pic['file_name'];

				}

		}  

		if(!empty($_FILES["side1"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('side1'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$side1=$pic['file_name'];

				}

		}  

		if(!empty($_FILES["side2"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('side2'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$side2=$pic['file_name'];

				}

		}  

			$data=array("dtitle"=>$this->input->post("title"),"dprice"=>$this->input->post("price"),"front"=>$front,"back"=>$back,"side1"=>$side1,'side2'=>$side2);

			if($this->db->insert("pre_designs",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Category Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Category Couldnot be Added.</div>");

			}

		

		redirect("admin/pre_designs");



  }



  public function add_vendor($id=false){

	  	if($id==true){

		$img=$this->input->post("oldimg");

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("v_name"=>$this->input->post("name"),"v_email"=>$this->input->post("email"),"v_phone"=>$this->input->post("phone"),"v_address"=>$this->input->post("address"),"v_logo"=>$img,"vb_name"=>$_POST['bname'],"vcity"=>$_POST['city'],"vstate"=>$_POST['state'],"vpincode"=>$_POST['pincode'],"v_password"=>md5($_POST['password']));

			$this->db->where("vid",$id);

			if($this->db->update("vendors",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Vendor Details Updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Vendor Details Couldnot be Updated.</div>");

			}	

		}else{

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("v_name"=>$this->input->post("name"),"v_email"=>$this->input->post("email"),"v_phone"=>$this->input->post("phone"),"v_address"=>$this->input->post("address"),"v_logo"=>$img,"v_reg_date"=>date("Y-m-d"),"vb_name"=>$_POST['bname'],"vcity"=>$_POST['city'],"vstate"=>$_POST['state'],"vpincode"=>$_POST['pincode'],"v_password"=>md5($_POST['password']));

			if($this->db->insert("vendors",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Vendor Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Vendor Couldnot be Added.</div>");

			}

		}

		redirect("admin/vendors");

  }

  

  public function add_mcategory($id=false){

	  	if($id==true){

		$img=$this->input->post("oldimg");

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("mcat_name"=>$this->input->post("cat"),"shipping_amt"=>$_POST['shipping_amt'],"cat_slug"=>str_replace(" ","-",strtolower($_POST['cat_slug'])),"mtitle"=>$this->input->post("metatitle"),"mkey"=>$this->input->post("metakey"),"mdesc"=>$this->input->post("metadesc"),"mcat_image"=>$img);

			$this->db->where("mid",$id);

			if($this->db->update("mcategory",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Main Category Updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Main Category Couldnot be Updated.</div>");

			}	

		}else{

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("mcat_name"=>$this->input->post("cat"),"shipping_amt"=>$_POST['shipping_amt'],"cat_slug"=>str_replace(" ","-",strtolower($_POST['cat_slug'])),"mtitle"=>$this->input->post("metatitle"),"mkey"=>$this->input->post("metakey"),"mdesc"=>$this->input->post("metadesc"),"mcat_image"=>$img);

			if($this->db->insert("mcategory",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Main Category Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Main Category Couldnot be Added.</div>");

			}

		}

		redirect("admin/mcategory");

  }

  public function update_profile(){
	    $photo=$_POST['oldphoto'];

		if(!empty($_FILES["photo"]["name"])){

				$config['upload_path'] = './adminassets/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('photo'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$photo=$pic['file_name'];

				}

		}  
		
		$booking_banner=$_POST['oldbooking_banner'];

		if(!empty($_FILES["booking_banner"]["name"])){

				$config['upload_path'] = './adminassets/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('booking_banner'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$booking_banner=$pic['file_name'];

				}

		}  

			$data=array("photo"=>$photo,"booking_banner"=>$booking_banner,"email"=>$this->input->post("email"),"mobile"=>$this->input->post("mobile"),"comp_name"=>$this->input->post("comp_name"),"address"=>$this->input->post("address"),"city"=>$this->input->post("city"),"pincode"=>$this->input->post("pincode"));
			$this->db->where("id",1);
			if($this->db->update("admin",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Profile Updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Profile Couldnot be Updated.</div>");

			}

		redirect("admin/profile");
  }
  
  public function change_pass(){
		parse_str($_POST['formdata'],$form);
		if($form['npass']!=$form['cpass'])
		{
			echo "Your Passwords Doesnot match";exit;
		}
		
		//$this->db->where("ag_id",$this->session->userdata("userid"));
		if($this->db->update("admin",array("password"=>md5($form['npass'])))){echo "Password Changed Successfully.";}
		
	}
	
  public function customers(){
	 $data['customers']=$this->db->get("users")->num_rows();  
	 $this->load->view ($this->middle = 'admin/customers',$data,true);
	 $this->adminlayout();  
  }
  
  public function add_customer(){
		$this->db->insert("users",array("first_name"=>$_POST['name'],"email"=>$_POST['email'],"mobile"=>$_POST['phone'],"password"=>md5($_POST['password']),"created"=>date("Y-m-d")));
		redirect("admin/customers");
  }
  
  public function ajax_bank_details(){
	$data['bank']=$this->db->get_where("agents",array("ag_id"=>$_POST['id']))->row();
	
  }

  public function add_category($id=false){

	  	if($id==true){

		$img=$this->input->post("oldimg");

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("mid"=>$_POST['mcat'],"cat_name"=>$this->input->post("cat"),"metatitle"=>$this->input->post("metatitle"),"metakey"=>$this->input->post("metakey"),"metadesc"=>$this->input->post("metadesc"),"cat_image"=>$img);

			$this->db->where("cid",$id);

			if($this->db->update("category",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Category Updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Category Couldnot be Updated.</div>");

			}	

		}else{

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("mid"=>$_POST['mcat'],"cat_name"=>$this->input->post("cat"),"metatitle"=>$this->input->post("metatitle"),"metakey"=>$this->input->post("metakey"),"metadesc"=>$this->input->post("metadesc"),"cat_image"=>$img);

			if($this->db->insert("category",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Category Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Category Couldnot be Added.</div>");

			}

		}

		redirect("admin/category");

  }
  
  
  public function add_influs($id=false){

	  	if($id==true){ 

			//$data=array("influ_name"=>$_POST['influ_name'],);

			$this->db->where("influ_id",$id);

			if($this->db->update("influs",$_POST)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Influencer Updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Influencer Couldnot be Updated.</div>");

			}	

		}else{


			//$data=array("mid"=>$_POST['mcat'],"cat_name"=>$this->input->post("cat"),"metatitle"=>$this->input->post("metatitle"),"metakey"=>$this->input->post("metakey"),"metadesc"=>$this->input->post("metadesc"),"cat_image"=>$img);

			if($this->db->insert("influs",$_POST)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Influencer Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Influencer Couldnot be Added.</div>");

			}

		}

		redirect("admin/influs");

  }
  
  public function add_blog($id=false){

	  	if($id==true){

		$img=$this->input->post("oldimg");

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("blog_title"=>$_POST['blog_title'],"blog_link"=>$this->input->post("blog_link"),"blog_user"=>$this->input->post("blog_user"),"blog_img"=>$img);

			$this->db->where("blog_id",$id);

			if($this->db->update("blogs",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Blog Updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Blog Couldnot be Updated.</div>");

			}	

		}else{

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("blog_title"=>$_POST['blog_title'],"blog_link"=>$this->input->post("blog_link"),"blog_user"=>$this->input->post("blog_user"),"blog_date"=>date("Y-m-d"),"blog_img"=>$img);

			if($this->db->insert("blogs",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Blog Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Blog  Couldnot be Added.</div>");

			}

		}

		redirect("admin/blogs");

  }

  

  public function update_plan(){

	  $img=$_POST['oldimg'];

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{



				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

		

			$data=array("plname"=>$this->input->post("plname"),"feat_pro"=>$this->input->post("feat_pro"),"deal"=>$this->input->post("deal"),"pl_price"=>$this->input->post("pl_price"),"pl_desc"=>$this->input->post("pl_desc"),"pl_image"=>$img);

			$this->db->where("plid",$_POST['plid']);

			if($this->db->update("plans",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Plan updated Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Plan Couldnot be updated.</div>");

			}

		redirect("admin/plans");

  }

  public function add_plan(){

		$img="default.jpg";$backbimg="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  



			$data=array("plname"=>$this->input->post("plname"),"feat_pro"=>$this->input->post("feat_pro"),"deal"=>$this->input->post("deal"),"pl_price"=>$this->input->post("pl_price"),"pl_desc"=>$this->input->post("pl_desc"),"pl_image"=>$img);

			if($this->db->insert("plans",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>Plan Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>Plan Couldnot be Added.</div>");

			}

		redirect("admin/plans");

  }

  

  //Remove Subcategory

  public function subcatdelete(){

	if($this->db->delete("subcategory",array("sid"=>$_POST['id'])) && $_POST['img']!="default.png"){

		 unlink(base_url()."assets/images/category/".$_POST['img']);	

	}

  }

  //Manage Category Add/Edit

  public function Subcategory(){

	  	$this->load->library('pagination');



		$config['base_url'] = 'http://localhost/22kstreet/';

		$config['total_rows'] = $this->db->get("subcategory")->num_rows();

		$config['per_page'] = 1; 

		

		$this->pagination->initialize($config); 



	  	$data['cats']=$this->db->get("category")->result();  

		$data['subcats']=$this->db->get("subcategory")->result();  

		$this->load->view ($this->middle = 'admin/subcategory',$data,true);

      	$this->adminlayout();

  }

  //Add/Edit Category

  public function add_subcategory(){

		$img="default.jpg";

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("mid"=>$_POST['mcat'],"cid"=>$this->input->post("cat"),"metatitle"=>$this->input->post("metatitle"),"metakey"=>$this->input->post("metakey"),"metadesc"=>$this->input->post("metadesc"),"subcat_name"=>$this->input->post("subcat"),"subcat_image"=>$img);

			if($this->db->insert("subcategory",$data)==true){

				$this->session->set_flashdata("msg","<div class='alert alert-success'>SubCategory Added Successfully.</div>");

			}else{

				$this->session->set_flashdata("msg","<div class='alert alert-warning'>SubCategory Couldnot be Added.</div>");

			}

		redirect("admin/subcategory");

  }

  

  public function pack_search(){

		$this->db->like("title",$_POST['key']);

		$data['pro']=$this->db->get("products")->result();

		$this->load->view("admin/ajax_pro",$data);  

  }

  

  public function ajax_addtopack(){

		$this->db->where("pid",$_POST['id']);

		$data['pro']=$this->db->get("products")->row();

		$this->load->view("admin/ajax_added_packs",$data);  

  }

  //Ajax Show subcategory to update in modal box

  public function ajax_showsubcat(){

		$sub=$this->db->get_where("subcategory",array("sid"=>$_POST['id']))->row();

		echo json_encode($sub);  

  }

  public function ajax_showsubcat1(){

		  echo '<option value="">Select Subcategory</option>';

		$subcat=$this->db->get_where("category",array("mid"=>$this->input->post('cid')))->result();

		foreach($subcat as $subcat){?><option value="<?php echo $subcat->cid;?>"><?php echo $subcat->cat_name;?></option><?php }

	  }

	  public function ajax_mcat(){

		  echo '<option value="">Select Category</option>';

		$subcat=$this->db->get_where("category",array("mid"=>$this->input->post('cid')))->result();

		foreach($subcat as $subcat){?><option value="<?php echo $subcat->cid;?>"><?php echo $subcat->cat_name;?></option><?php }

	  }

  

  public function ajax_editzip(){

		$sub=$this->db->get_where("prozip",array("zid"=>$_POST['id']))->row();

		echo json_encode($sub);  

  }

  

  

  public function update_subcategory(){

	//print_r($_POST);

		$img=$this->input->post("oldimg");

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './assets/images/category/';

				$config['allowed_types'] = 'gif|jpg|png|jpeg|svg';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				//echo $this->upload->display_errors();

				}

				else

				{	

				$pic = $this->upload->data();

				$img=$pic['file_name'];

				}

		}  

			$data=array("mid"=>$this->input->post("mcat"),"subcat_name"=>$this->input->post("subcat"),"metatitle"=>$this->input->post("metatitle"),"metakey"=>$this->input->post("metakey"),"metadesc"=>$this->input->post("metadesc"),"subcat_image"=>$img,"cid"=>$_POST['cat']);

			$this->db->where("sid",$_POST['sid']);

			if($this->db->update("subcategory",$data)==true){

				$sub=$this->db->get_where("subcategory",array("sid"=>$_POST['sid']))->row();

				echo json_encode($sub);

				//$this->session->set_flashdata("msg","<div class='alert alert-success'>Category Updated Successfully");

			}else{

				//$this->session->set_flashdata("msg","<div class='alert alert-warning'>Category Couldnot be Updated");

			}  

  }

  

  public function removeprefile(){

	  $this->db->delete("prozip",array("zid"=>$_POST['id']));

  }

  

  public function update_prozip(){

	//print_r($_POST);

		$zip=$this->input->post("oldzip");

		$exts=$this->input->post("exts");

		if(!empty($_FILES["img"]["name"])){

				$config['upload_path'] = './adminassets/products/';

				$config['allowed_types'] = 'zip';

				$config['max_size']	= '1000000';

				$this->upload->initialize($config);

				if (!$this->upload->do_upload('img'))

				{

				//echo $this->upload->display_errors();

				}

				else

				{	

				$filename="";

				$pic = $this->upload->data();

				$data = array('upload_data' => $pic);

								//echo "<pre>";print_r($data);

				$full_path = $data['upload_data']['full_path'];

				$zip = new ZipArchive;

				if ($zip->open($full_path) === TRUE) 

				{

					for ($j = 0; $j < $zip->numFiles; $j++) {

							  $filename .= $zip->getNameIndex($j).',';

						 }

					$zip->extractTo(FCPATH.'./adminassets/products/');

					$zip->close();

				}

				$zip=$pic['file_name'];

				$exts=rtrim($filename,',');

				}

		}  

			$data=array("width"=>$this->input->post("width"),"height"=>$this->input->post("height"),"stitch"=>$this->input->post("stitch"),"price"=>$this->input->post("price"),"zip"=>$zip,"unzip"=>$exts);

			$this->db->where("zid",$_POST['zid']);

			if($this->db->update("prozip",$data)==true){

				echo "Zip updated.";

			}else{

				echo "Zip couldnot be updated.";

			}  

  }

	

	public function offerusers(){

		  $data['ad']=$this->db->get_where("ads",array("aid"=>$_POST['aid']))->row();

		  $data['users']=$this->db->get_where("offers",array("aid",$_POST['aid']))->result();

		  $this->load->view('admin/offer_users',$data);

	  }

	  

	public function userchat(){

		$offer= $this->db->get_where("offers",array("oid"=>$_POST['oid']))->row();  

		echo '  <h3 class="text-success">Offer Amount AED '.$offer->offer_amt.'</h3><hr/><div class="friend-msg-wrap">

                 <img class="user-img img-circle block pull-left" src="'.base_url().'assets/images/author/img-08.jpg" alt="user">

                                                   

													<div class="msg pull-left">'.$offer->msg.'

                                                        <div class="msg-per-detail mt-5">

                                                            <span class="msg-per-name txt-success">'.$offer->rname.'</span>

                                                            <span class="msg-time txt-grey">'.date('d M Y',strtotime($offer->rdate)).'</span>

                                                        </div>

                                                    </div>

                                                    <div class="clearfix"></div>

                                                </div>';

	  }  

	

	public function add_product($pid=false){

		if($pid==true){

		$this->db->select("*");

		$this->db->from('products');

		//$this->db->join("category","products.cid=category.cid");

		//$this->db->join("subcategory","products.sid=subcategory.sid");

		$this->db->where("pid",$pid);

		$data['pro']=$this->db->get()->row();	

		//$data['vars']=$this->db->get_where('prozip',array("pid"=>$pid))->result();	

		}

		$data['cats']=$this->db->get("category")->result();  

		$this->load->view ($this->middle = 'admin/add_product',$data,true);

      	$this->adminlayout();

	}

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	

	public function manage_expense_fields(){

		$data['types']=$this->db->get("expense_types")->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/manage_expense_fields',$data,true);

		$this->adminlayout(); 

	

	}


	

	public function store_pro_delete(){

		$this->db->delete("store_products",array("store_pid"=>$_POST['id']));

	}

	public function pro_delete(){

		$this->db->delete("products",array("pid"=>$_POST['id']));
		$this->db->delete("prod_variants",array("pid"=>$_POST['id']));

	}

	public function ajax_order_delete(){
		$this->db->delete("orders",array("oid"=>$_POST['id']));
		$this->db->delete("order_items",array("oid"=>$_POST['id']));
	}

	public function order_details($oid){
		$this->db->select('*');
		$this->db->from('orders');
		//$this->db->join('users','users.id=orders.userid');
		//$this->db->join("cities","orders.bcity=cities.city_id","left");
		//$this->db->join("states","states.state_id=agents.ag_state","left");
		//$this->db->join("city_stores","city_stores.city_id=cities.city_id");
		//$this->db->join("delivery_times","delivery_times.dtid=orders.del_time");
		$this->db->where("orders.oid",$oid);
		$orders=$this->db->get();
		$data['order']=$orders->row();
		//echo "<pre>";print_r($data);exit;
		//$this->db->select("*");
		//$this->db->from("order_items");
		$data['items']=$this->db->get_where("order_items",array("oid"=>$oid))->result();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/order_detail',$data,true);
		$this->adminlayout();  
    }
	
	public function ajax_cod_recd(){
		//print_r($_POST);exit;
		$this->db->where("oid",$_POST['id']);
	    $this->db->update("orders",array("pay_recd"=>$_POST['v']));	
	}

	public function  ostatus_change(){
		//print_r($_POST);exit;
	    $this->db->where("oid",$_POST['oid']);
	    if($this->db->update("orders",array("ostatus"=>$_POST['st'])))
	    {
			if($_POST['st']=='Completed'){
			$this->db->order_by("wid","desc");
			
			$chk=$this->db->get_where("wallet",array("did"=>$_POST['userid']));

			$order=$this->db->get_where("orders",array("oid"=>$_POST['oid']))->row();
			if($chk->num_rows()>0){

				$l=$chk->row();

				//print_r($l);

				$wallet=$l->wallet_amt;}else{$wallet=0;}

				
					$newbal=$wallet-$order->ototal;
					$tr_desc="Debit";

				

				$this->db->insert("wallet",array("order_no"=>'KAO00'.$order->oid,"wallet_staff_id"=>$order->order_staff,"wallet_state_id"=>$order->ord_state_id,"pay_month"=>date("M-y"),"pay_year"=>date("Y"),"trans_amt"=>$order->ototal,"trans_type"=>"Debit","trans_date"=>date("Y-m-d"),"wallet_amt"=>$newbal,"did"=>$_POST['userid']));
				
			}
	    }
	}

	public function userdel(){
		$this->db->delete("users",array("id"=>$_POST['id']));
		$this->db->delete("orders",array("userid"=>$_POST['id']));
	}

    public function login(){//print_r($_POST);

	$this->form_validation->set_rules('username', 'Username', 'required');

	$this->form_validation->set_rules('password', 'Password', 'required');  

	if($this->form_validation->run() == FALSE)

		{

			redirect("admin");

		}

		else

		{		

			$chk=$this->db->get_where("admin",array("username"=>$this->input->post("username"),"password"=>md5($this->input->post("password"))));

			if($chk->num_rows()>0)

			{

				$data=array("admin"=>"true",

							"user"=>"admin","userid"=>0);

							$this->session->set_userdata($data);

							redirect("admin");

			}

			else

			{

			$chk=$this->db->get_where("employees",array("eemail"=>$this->input->post("username"),"epass"=>md5($this->input->post("password"))));

			if($chk->num_rows()>0)

			{

				$u=$chk->row();

				$data=array("admin"=>"true",

							"user"=>"user","userid"=>$u->id,"username"=>$u->ename);

							$this->session->set_userdata($data);

							redirect("admin");

			}else{

			$this->session->set_flashdata('msg', 'Invalid Username or Password.');	

			redirect("admin");

			}}

		}

  }

  

  public function usercom($id){

		$data['cdata']=array();//$this->db->get_where("campaigns",array("id"=>$cid))->row();	

		$this->template['middle'] = $this->load->view($this->middle = 'admin/usercom',$data,true);

		$this->adminlayout();

  }

  

  public function logout(){

	$this->session->sess_destroy();

	$this->session->set_flashdata('msg', '<div class="alert alert-warning">You logged out successfully.</div>');

	if($this->session->userdata("type")=="vendor"){

	redirect("home/vlogin");

	}else{redirect("admin");}

  }

  

  

  public function users(){

	    $this->db->order_by("id","desc");

	  	$data['users']=$this->db->get("users")->result();

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/users',$data,true);

		$this->adminlayout(); 

  }

  

 

	public function ContactEnquiries(){$this->db->order_by("id","desc");

		$data['cons']=$this->db->get("contact")->result();

		$this->template['middle'] = $this->load->view($this->middle = 'admin/contacts',$data,true);

		$this->adminlayout(); 	

	}

	

	public function deletecon(){

		$this->db->delete("contact",array("id"=>$_POST['id']));	

	}

	

	public function newsletter(){

		$data['news']=$this->db->get("newsletter")->result();

		$data['users']=$this->db->get("users")->result();

		$this->template['middle'] = $this->load->view($this->middle = 'admin/email',$data,true);

		$this->adminlayout();	

	}

	

public function sendmails(){

		if($_POST['to']==""){

		$to = implode(",",$_POST['mails']);

}else{

$to =$_POST['to'];

}

		$subject = $_POST['subject'];

			

		$message = '<table border="0" cellspacing="0" cellpadding="0" class="table_width_100" width="100%" style="max-width: 680px; min-width: 300px;">

    <tr><td>

	</td></tr>

	<tr><td align="center" bgcolor="#ffffff">

		<table width="90%" border="0" cellspacing="0" cellpadding="0">

			<tr><td align="center">

			    		<a href="#" target="_blank" style="color: #596167; font-family: Arial, Helvetica, sans-serif; float:left; width:100%; padding:20px;text-align:center; font-size: 13px;">

									<font face="Arial, Helvetica, sans-seri; font-size: 13px;" size="3" color="#596167">

									<img src="'.base_url().'vector/img/logo/logo_dark.png" width="250" alt="Metronic" border="0"  /></font></a>

					</td>

					<td align="right">

				

	</td></tr>

	<tr><td align="center" bgcolor="#fbfcfd">

	    <font face="Arial, Helvetica, sans-serif" size="4" color="#57697e" style="font-size: 15px;">

		<table width="90%" border="0" cellspacing="0" cellpadding="10">

			<tr><td>

			    Hello There,

			</td></tr>

			<tr>

				<td colspan="2">'.$_POST['editor1'].'</td>

			</tr>

			



		</table>

		</font>

	</td></tr>

	<tr><td>



	</td></tr>

</table>

</td></tr>

</table>';

			$headers = "MIME-Version: 1.0" . "\r\n";

$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";



// More headers

$headers .= 'From: info@yaaraindia.com';



if(mail($to,$subject,$message,$headers)==true){

			$this->session->set_flashdata('msg', '<div class="alert alert-success">Your Enquiry Received Successfully. We will get back to you soon.</div>');

					redirect('admin/newsletter');

			}else{

			$this->session->set_flashdata('msg', '<div class="alert alert-danger">Your Enquiry couldnot be Received. Please try Later.</div>');

					redirect('admin/newsletter');

			}

		  	

	}



	public function orders(){
		if($this->session->userdata("type")=="dadmin"){redirect("admin/dorders");}
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/list_orders',$data,true);
   		$this->adminlayout();	
	}
	public function customer_orders($cid){
		if($this->session->userdata("type")=="dadmin"){redirect("admin/dorders");}
		$this->db->select("*");
		$this->db->from('orders');
		//$this->db->join("users","orders.userid=users.id");
		
		$this->db->join("emps","emps.uid=orders.admin_id","left");
		//$this->db->join("cities","cities.city_id=orders.bcity","left");
		//$this->db->join("delivery_times","delivery_times.dtid=orders.del_time");
		//if($type==true && $type=="Completed"){
		$this->db->where("orders.userid",$cid);	
		///$this->db->limit(10,$_POST['offset']);
		$this->db->order_by("orders.oid","desc");
		$data['orders']=$this->db->get()->result();
		//echo "<pre>";print_r($data);exit;
		//$data['page']=$_POST['offset'];
		
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/cust_orders',$data,true);
   		$this->adminlayout();	
	}
	public function dorders(){
		$data=array();
		$this->template['middle'] = $this->load->view ($this->middle = 'admin/list_orders',$data,true);
   		$this->adminlayout();	
	}
	
	public function order_nav(){
		//print_r($_POST);exit;
		$data['ostatus']=$_POST['ostatus'];
//		$data['uid']=$_POST['uid'];
//		if($_POST['ostatus']!=''){
//		$this->db->where("ostatus",$_POST['ostatus']);
//		$this->db->or_where("ostatus",'Pending');
//		}
//		if($_POST['uid']!=''){
//		$this->db->where("userid",$_POST['uid']);
//		}
		$data['navs']=$this->db->get_where("orders",array("ostatus"=>$_POST['ostatus']))->num_rows();	
		//print_r($data);exit;
		$this->load->view("admin/onavs",$data);
	}
	
	public function orders_ajax(){
		$this->db->select("*");
		$this->db->from('orders');
		//$this->db->join("agents","orders.userid=agents.ag_id");
		
		$this->db->join("emps","emps.uid=orders.admin_id","left");
		//$this->db->join("cities","cities.city_id=orders.bcity","left");
		//$this->db->join("delivery_times","delivery_times.dtid=orders.del_time");
		//if($type==true && $type=="Completed"){
		if($this->session->userdata("type")=="dadmin"){
		
		$this->db->where("orders.admin_id",$this->session->userdata("userid"));
		}else{
		$this->db->where("orders.ostatus",$_POST['ostatus']);	
		}
//		}
		//if($_POST['ostatus']!=''){
//		$this->db->where("ostatus",$_POST['ostatus']);
//		$this->db->or_where("ostatus",'Pending');
//		}
//		if($_POST['uid']!=''){
//		$this->db->where("userid",$_POST['uid']);
//		}
		$this->db->limit(10,$_POST['offset']);
		$this->db->order_by("orders.oid","desc");
		$data['orders']=$this->db->get()->result();
		//echo "<pre>";print_r($data);exit;
		$data['page']=$_POST['offset'];
		$this->load->view("admin/orders_ajax",$data);
	}

	public function other_orders(){

		//echo "<pre>";

		//print_r($this->session->all_userdata());exit;

		$this->db->select("*");

		$this->db->from('orders');

		$this->db->join("users","orders.userid=users.id");

		$this->db->where("orders.pay_status!=","Approved Successful");

		$this->db->order_by("orders.oid","desc");

		$data['orders']=$this->db->get()->result();

		

		$this->template['middle'] = $this->load->view ($this->middle = 'admin/orders',$data,true);

   		$this->adminlayout();	

	}

	

	public function vieworder(){

		$this->db->select("*");

		$this->db->from('order_items');

		$this->db->join("products","products.pid=order_items.pid");

		$this->db->where("order_items.oid",$_POST['id']);

		$imgs=$this->db->get()->result();

		//print_r($imgs);exit;

		foreach($imgs as $img){

		echo '<img style="border:2px solid black; margin:5px;" width="100px" src="'.base_url().'assets/images/products/'.$img->img.'"/>';	

		}

	}

  

  public function deleteAd($id){

	$this->db->delete("campaigns",array("id"=>$id));

	$this->db->delete("tasks",array("taskid"=>$id));

	$this->session->set_flashdata('msg', 'Ad deleted Successfully.');	

	redirect("admin/allCampaigns");

  }

  

  

}

?>