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

class Admin extends CI_Controller {
	function __Construct(){
		parent::__Construct();
		if(!isset($_SESSION['USERS_DATA'])){
			redirect(base_url("login"));
		}
		$this->load->library('ts_functions');
	}

	public function index(){

		$data['title'] ="Profile Update";
		$this->load->view('header',$data);
		$this->load->view('sidebar');
		$admin_data = $_SESSION['USERS_DATA'];
		if(!empty($admin_data)){

			$data['admin'] = $this->my_model->select_data('*' , 'users',array('userType !=' => 2, 'userId' =>$admin_data['userId']),'','');
		}

		$this->load->view('users/admin_profile',$data);
		$this->load->view('footer');
	}

	function upload_image($upPath , $name , $postFix = NULL){
		$this->CI = get_instance();
		$basePath = explode('application',dirname(__FILE__))[0];
		$uploadPath = $basePath.$upPath; 
		$config['upload_path'] = $uploadPath;
		$config['allowed_types'] = '*';
		$this->CI->load->library('upload', $config);
		if ($this->CI->upload->do_upload($name)){
			$uploaddata = $this->CI->upload->data();
			$imgName = $uploaddata['raw_name'];
			$imgExt = $uploaddata['file_ext'];
			$randomstr = substr(md5(microtime()), 0, 10);
			$uploadedImage = $randomstr.$postFix.$imgExt;
			rename($uploadPath.$imgName.$imgExt, $uploadPath.$uploadedImage);
			return $uploadedImage;
		}else{ 
			return '';
		}
	}


	public function admin_edit(){
		if(isset($_POST['admin_name']) && !empty($_POST['admin_name'])){
			$update_Arr =  array();
			if(!empty($_POST['admin_name'])){
				$update_Arr['userName'] = $_POST['admin_name'];
			}

			if(!empty($_POST['admin_email'])){
				$update_Arr['userEmail'] = $_POST['admin_email'];
			} 

			if(!empty($_POST['admin_mobile'])){
				$update_Arr['userMobile'] = $_POST['admin_mobile'];
			}

			if(!empty($_POST['admin_dis'])){
				$District = $_POST['admin_dis'];
				if(!empty($_POST['admin_wn'])){
					$WordNumber = $_POST['admin_wn'];
				}else{
					$WordNumber =0;
				}
				if(!empty($_POST['admin_hn'])){
					$HouseNumber = $_POST['admin_hn'];
				}else{
					$HouseNumber =0;
				}
				if(!empty($_POST['admin_town'])){
					$Town = $_POST['admin_town'];
				}else{
					$Town =0;
				}
				$update_Arr['address'] = $District."|".$WordNumber."|".$Town."|".$HouseNumber;
			} 

			if(!empty($_POST['admin_pwd'])){
				$update_Arr['userPassword'] = md5($_POST['admin_pwd']);
			}

			if(isset($_FILES['admin_pic']['name']) && !empty($_FILES['admin_pic']['name'])){
				$ItemImage = $this->upload_image('/assets/uploads/users/' , 'admin_pic' );	
				$update_Arr['userImage'] = $ItemImage; 
			}
			
			if(!empty($_POST['AadharNumber'])){
		          
		          $update_Arr['aadharNumber'] = $_POST['AadharNumber'];
		      }
		      
		      if(!empty($_POST['PanNumber'])){
		          
		          $update_Arr['panNumber'] = $_POST['PanNumber'];
		      }
		      
		      if(!empty($_POST['GSTNumber'])){
		          
		          $update_Arr['GSTNumber'] = $_POST['GSTNumber'];
		      }
		      
		    
		    if(isset($_FILES['ShopImage']['name']) && !empty($_FILES['ShopImage']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'ShopImage' );	
				$update_Arr['shopImage'] = $usersImage; 
		    	}
		    	
	    	if(isset($_FILES['AadharImage']['name']) && !empty($_FILES['AadharImage']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'AadharImage' );	
				$update_Arr['aadharImage'] = $usersImage; 
		    	}
		    	
		    if(isset($_FILES['PanImage']['name']) && !empty($_FILES['PanImage']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'PanImage' );	
				$update_Arr['panImage'] = $usersImage; 
		    	}
			if(isset($_POST['admin_id']) && !empty($_POST['admin_id'])){
				$where = array(
							'userId !='    => $_POST['admin_id'],
							'userMobile'    => $_POST['admin_mobile']
						);
				$userData = $this->my_model->select_data('*','users', $where);
				if($userData){
					$resp = array('status' => 0 , 'error' => 'Mobile number already exists.');
				}else{   
					$this->my_model->update_data_limit('users' ,$update_Arr,array('userId' => $_POST['admin_id']), 1); 
					$resp = array('status' => 1 ,'redirect' => 'admin','msg'=>'Successfully updated');
				}	
			}else{ 
				$where = array(
							'userMobile'    => $_POST['admin_mobile']
						);
				$userData = $this->my_model->select_data('*','users', $where);
				if($userData){
					$resp = array('status' => 0 , 'error' => 'Mobile number already exists.');
				}else{
					$update_Arr['status'] = 1;
					$this->my_model->insert_data('users' ,$update_Arr); 
					$resp = array('status' => 1 ,'redirect' => 'admin','msg'=>'Successfully created');
				}
			}  
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}

	public function general_setting(){
	    if(!empty($_SESSION['USERS_DATA']) && $_SESSION['USERS_DATA']['userType'] !=1){
	        	redirect(base_url("dashboard"));
	    }
		$data['title'] ="General Setting";
		$data['activ'] ="general_setting";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$data['logoData'] = $this->my_model->select_data('*' , 'logo_settings','','','');
		$data['apiData'] = $this->my_model->select_data('*' , 'rt_settings',array('key_text'=> 'msg91_key'),'1');
		$this->load->view('general_setting',$data);
		$this->load->view('footer');
	}
    public function create_general(){
        if(!empty($_SESSION['USERS_DATA']) && $_SESSION['USERS_DATA']['userType'] !=1){
	        	redirect(base_url("dashboard"));
	    }
		if(isset($_POST['logoTitle']) && !empty($_POST['logoTitle'])){
			
			$update_Arr =  array('logoTitle' =>$_POST['logoTitle']
			);
			if(isset($_FILES['LogoImage']['name']) && !empty($_FILES['LogoImage']['name'])){
				$LogoImage = $this->upload_image('/assets/uploads/' , 'LogoImage' );	
				$update_Arr['logoImage'] = $LogoImage; 
			}
            
			if(!empty($_POST['ThemeColor'])){
			  $update_Arr['themeColor'] = $_POST['ThemeColor'];
			}
			if(isset($_FILES['LoginBoxImage']['name']) && !empty($_FILES['LoginBoxImage']['name'])){
				$LoginBoxImage = $this->upload_image('/assets/uploads/' , 'LoginBoxImage' );	
				$update_Arr['loginBoxImg'] = $LoginBoxImage; 
			}
			if(!empty($_POST['LoginBgColor'])){
				$update_Arr['loginBoxColor']= $_POST['LoginBgColor'];
			}
            if(isset($_FILES['LoginBgImage']['name']) && !empty($_FILES['LoginBgImage']['name'])){
				$LoginBgImage = $this->upload_image('/assets/uploads/' , 'LoginBgImage' );	
				$update_Arr['loginImg'] = $LoginBgImage; 
			}
			if(isset($_FILES['HeaderLogo']['name']) && !empty($_FILES['HeaderLogo']['name'])){
				$HeaderLogo = $this->upload_image('/assets/uploads/' , 'HeaderLogo' );	
				$update_Arr['headerLogo'] = $HeaderLogo; 
			}
			if(isset($_POST['Loginid']) && !empty($_POST['Loginid'])){
				$where = array(
							'logoTitle'=>$_POST['logoTitle'],
							'logoId !=' => $_POST['Loginid']
						);
				$itemData = $this->my_model->select_data('*','logo_settings', $where);

				if(empty($itemData)){
					$this->my_model->update_data_limit('logo_settings' ,$update_Arr,array('logoId' => $_POST['Loginid']), 1); 
					$resp = array('status' => 1 ,'redirect' => 'dashboard/logo_title','msg'=>'Successfully updated');
				}else{
					$resp = array('status' => 0 , 'error' => 'Site title already exists1.');
				}

			}else{ 

				$where = array(
					'logotitle'=>$_POST['logoTitle']
					);
				$itemData = $this->my_model->select_data('*','logo_settings', $where);
				if(empty($itemData)){
					$this->my_model->insert_data('logo_settings' ,$update_Arr); 
					$resp = array('status' => 1 ,'redirect' => 'dashboard/logo_title','msg'=>'Successfully created');
				}else{
					$resp = array('status' => 0 , 'error' => 'Site title already exists2.');
				}
			}
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try1.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
    public function create_api(){
		  if(isset($_POST['smsApi']) && !empty($_POST['smsApi'])){
		      
		     $update_Arr =  array('value_text' =>$_POST['smsApi']
		                          );
 			 
		    if(isset($_POST['ApiUpdateId']) && !empty($_POST['ApiUpdateId'])){
			     
			    $where = array(
			               'value_text'=>$_POST['smsApi'],
			               'uniq_id !=' => $_POST['ApiUpdateId']
						   );
		        $itemData = $this->my_model->select_data('*','rt_settings', $where);
		       
		        if(empty($itemData)){
    				
    				$this->my_model->update_data_limit('rt_settings' ,$update_Arr,array('uniq_id' => $_POST['ApiUpdateId']), 1); 
    				$resp = array('status' => 1 ,'redirect' => 'admin/api_setting','msg'=>'Successfully updated');
			    }else{
			        
			        $resp = array('status' => 0 , 'error' => 'Api key already exists.');
			    }
		        
			}else{ 
			    
			    $where = array(
			               'value_text'=>$_POST['smsApi']
						   );
		        $itemData = $this->my_model->select_data('*','rt_settings', $where);
			    if(empty($itemData)){
				$this->my_model->insert_data('rt_settings' ,$update_Arr); 
				$resp = array('status' => 1 ,'redirect' => 'admin/api_setting','msg'=>'Successfully created');
			    }else{
			        $resp = array('status' => 0 , 'error' => 'Api key already exists.');
			    }
			}
		}else{ 
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
    public function payment_notification(){
	    if(!empty($_SESSION['USERS_DATA']) && $_SESSION['USERS_DATA']['userType'] ==1){
	        	redirect(base_url("dashboard"));
	    }
	    $vendor_id = $_SESSION['USERS_DATA']['userId'];
		$data['title'] ="Payment Notification";
		$data['activ'] ="payment_notification";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$notification = $this->my_model->select_data('*' , 'refund_notification',array('vendorId'=> $vendor_id),'',array('notificationDate','DESC'));
		$i=0;
		foreach($notification as $key =>$value){
		    $user_id =$value['userId'];
		    $orderId =$value['orderId'];
    		$userData = $this->my_model->select_data('*' , 'users',array('userType' => 2,'userId'=> $user_id),'');
    		if(!empty($userData)){
    		    $notification[$key]['userName']    = $userData[0]['userName'];
    		    $notification[$key]['userEmail']   = $userData[0]['userEmail'];
    		    $notification[$key]['userMobile']  = $userData[0]['userMobile'];
    		    $notification[$key]['address'] = $userData[0]['address'];
    		}
    		
			$oderData = $this->my_model->select_data('*' , 'wholesale_item_invoice',array('id'=> $orderId),'');
            if(!empty($oderData)){
                $notification[$key]['paymentType'] = $oderData[0]['paymentType'];
                $notification[$key]['transactionId'] = $oderData[0]['transactionId'];
                $notification[$key]['deliveryStatus'] = $oderData[0]['deliveryStatus'];
                $notification[$key]['saleDate'] = $oderData[0]['saleDate'];
                $notification[$key]['totalAmount'] = $oderData[0]['totalAmount'];
            }

		$i++;   
		}

		$data['notification'] = $notification;
		$this->load->view('payment_notification',$data);
		$this->load->view('footer');
	}
	
	public function refundStatus(){
		
		if(isset($_POST['refundId']) && !empty($_POST['refundId']))
		{  
	        $userEmail = $_POST['userEmail'];
	        $refundId = $_POST['refundId'];
			
    		    $where = array(
    			               'refundId'    => $refundId
    						   );
    		$userData = $this->my_model->select_data('*','refund_notification', $where);
    		    
			if(!empty($userData))
			{   
			   
			    $data = array(
			              'refundStatus'=>1
			            );
			    $this->my_model->update_data('refund_notification' ,$data, array('refundId'=>$refundId));	
			    $resp = array('status' => 1 , 'msg' => 'Successfully updated.');
			    
			    $orderId = $userData[0]['orderId'];
			    $data = array(
			              'deliveryStatus'=>4
			            );
			    $this->my_model->update_data('wholesale_item_invoice' ,$data, array('id'=>$orderId));
			    if(!empty($userEmail)){
    			    $to ="$userEmail";
    			    $party_name = $userData[0]['holderName'];
    			    $invoice_date = date('Y-m-d');
    			    $msg=str_replace("[order_number]",$orderId,str_replace("[username]",$party_name,str_replace("[break]","<br />",$this->ts_functions->getsettings('arefundpay','text'))));
            		$msg=str_replace("[order_date]",$invoice_date,$msg);
            		$this->ts_functions->email2('arefundpay',$to,$msg);
			    }
			    
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try1.');
			}
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try2.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function language_option(){
	    if(!empty($_SESSION['USERS_DATA']) && $_SESSION['USERS_DATA']['userType'] !=1){
	        	redirect(base_url("dashboard"));
	    }
		$data['title'] ="Language Option";
		$data['activ'] ="language_option";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('language_option',$data);
		$this->load->view('footer');
	}
	
	/**** Function to update main language settings ****/
    public function updatelanguages() {
	    if(isset($_POST['weblanguage_text'])) {

            $this->my_model->access_database('rt_settings','update',array('value_text'=>$_POST['weblanguage_text']),array('key_text'=>'weblanguage_text'));

			redirect($_SERVER['HTTP_REFERER']);
	    }
	    elseif( trim(!empty($_POST['addnewlanguage']))) {
	            $existingLang = $this->ts_functions->getsettings('languageoption','text');
	            $this->my_model->access_database('rt_settings','update',array('value_text'=>$existingLang.','.$_POST['addnewlanguage']),array('key_text'=>'languageoption_text'));

	            $this->load->dbforge();
	            $k = 'language_'.$_POST['addnewlanguage'];
	            $fields = array(
                    $k => array('type' => 'TEXT')
                );
                $this->dbforge->add_column('language', $fields);
                redirect($_SERVER['HTTP_REFERER']);
	        }else{
	        redirect(base_url('admin/general_setting'));
	    }
	    die();
	}
	
	/******************** Delete Language STARTS ********************/

	function delete_selected_language($langname=''){
		if( $langname != '' ) {
			$existingLang = $this->ts_functions->getsettings('languageoption','text');;
			$lan_arr = explode(',',$existingLang);
			$current_lan = $this->ts_functions->getsettings('weblanguage','text');
			
			$lan_str = '';
			$f_lan = '';
			for($i=0;$i<count($lan_arr);$i++) {
				if( $lan_arr[$i] != $langname ) {
					$lan_str .= $lan_arr[$i].',';
					$f_lan = $lan_arr[$i];
				}
			}
			if( $current_lan == $langname ) {
				$this->my_model->access_database('rt_settings','update',array('value_text'=>$f_lan),array('key_text'=>'weblanguage_text'));
			}
			
			$lan_str = rtrim($lan_str,',');
			$this->my_model->access_database('rt_settings','update',array('value_text'=>$lan_str),array('key_text'=>'languageoption_text'));

			$this->load->dbforge();
			$k = 'language_'.$langname;
			$this->dbforge->drop_column('language', $k);
			
		}
		redirect($_SERVER['HTTP_REFERER']);
	}

	/******************** Delete Language ENDS ********************/
	
	/**** Function to update main language settings ****/
    public function language_msg_update() {
	    
           if(isset($_POST['langKey']) && !empty($_POST['langKey'])){
			$langKey = explode('#',$_POST['langKey']);
            $lang_Key = $langKey[0];
            $lang_type = $langKey[1];
            $lang_msg_l = $langKey[2];
            
            $msgkey ='language_'.$lang_msg_l;
			$langData = $this->my_model->select_data('*' , 'language' , array('language_key' => $lang_Key),'1');
			if(!empty($langData)){
				$resp = array('status' => 1 , 'langData' => $langData[0][$msgkey],'langType'=>$lang_msg_l,'langId'=>$_POST['langKey']);
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			} 
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	
	}
	
	public function update_msg() {
	    
           if(isset($_POST['langKey']) && !empty($_POST['langKey'])){
			$langKey = explode('#',$_POST['langKey']);
            $lang_Key = $langKey[0];
            $lang_type = $langKey[1];
            $lang_msg_l = $langKey[2];
            
            $msgkey ='language_'.$lang_msg_l;
        
		
		    $data = array(
		              $msgkey=>$_POST['msgName']
		            );
		   $langData = $this->my_model->update_data('language' ,$data, array('language_key'=>$lang_Key));	
		    
			if($langData){
				$resp = array('status' => 1 , 'msg' => 'Successfully updated.');
			}else{
				$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
			} 
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	
	}

	
}	