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

class AdminAjax extends CI_Controller {

    protected $browserResponse;
    protected $user_id;
    
	public function __construct(){

        parent::__construct();
        checkLogin();
        checkIsAdmin();
		$this->browserResponse = array('status'=>'error','message'=>'Something went wrong! Please reload & try again','redirect'=>'');
		$this->user_id = $this->session->userdata('user_id');
    }

	private function checkValidAJAX(){
		if( !$this->input->is_ajax_request() )
			die('Unauthorize Access!!');
	}

	// Admin Create Update Users
	public function createUpdateUser(){
		$this->checkValidAJAX();

		$user_id = $this->input->post('pps_userid');

		/* Create User data */
		if( empty($this->input->post('pps_userid')) ){

			$this->form_validation->set_rules('pps_email', 'email', 'required|is_unique[usertbl.u_email]', array( 'required' => 'You have not provided %s.','is_unique' => 'This %s already exists.') ); 
			$this->form_validation->set_rules('pps_password_first', 'Password', 'required');
			$this->form_validation->set_rules('pps_password', 'Confirm Password', 'required|matches[pps_password_first]');
			
			if ($this->form_validation->run() == FALSE){
				$this->browserResponse['message'] = strip_tags(validation_errors()) ;
			}
			else{
				$data['u_name'] = $this->input->post('pps_name'); 
				$data['u_email'] = $this->input->post('pps_email'); 
				$data['u_password'] = md5($this->input->post('pps_password')); 
				$data['u_type'] = 2; 
				$data['u_status'] = 1; 
				$data['u_purchaseddate'] = date('Y-m-d H:i:s');
				$data['created_on'] = date('Y-m-d H:i:s'); 

				$res = $this->Qdb->insert_data('usertbl', $data);

				if( !empty($res) ){
					$user_id = $res;
					$this->browserResponse['status'] = 'success';
					$this->browserResponse['message'] = 'User account has been successfully created';
					$this->browserResponse['redirect'] = 'reload';
				}
        	}

		}
		/* Update User data */
		else {

			$this->form_validation->set_rules('pps_password_first', 'Password', 'trim');
			$this->form_validation->set_rules('pps_password', 'Confirm Password', 'trim|matches[pps_password_first]');
			
			if ($this->form_validation->run() == FALSE){
				$this->browserResponse['message'] = strip_tags(validation_errors()) ;
			}
			else{
				$data['u_name'] = $this->input->post('pps_name'); 
				$password = $this->input->post('pps_password');
				if( !empty( $password ) )
					$data['u_password'] = md5($this->input->post('pps_password')); 
				
				$res = $this->Qdb->update_data('usertbl', $data, array('u_id' => $this->input->post('pps_userid')));
				
				$this->browserResponse['status']   = 'success';
				$this->browserResponse['redirect'] = 'reload';
				$this->browserResponse['message']  = 'User updated Successfully';
				
			}
		}

		$plan_id = $this->input->post('user_plan');
		if( !empty( $plan_id ) ){
			$condition = true;
			$check_plan = checkPlanDetails( $user_id );
			if( $check_plan['status'] != 0 ){
				if($check_plan['plan_id'] == $plan_id)
					$condition = false;
			}

			if( $condition ){
				$date = date('Y-m-d H:i:s');
				$addPayInte = $this->Qdb->insert_data(
					'payment_info', [
						'type'          => '4',
						'customer_id'   => $user_id,
						'plan_id'       => $plan_id,
						'payment_data'  => 'Admin',
						'order_id'      => 'NA', 
						'payment_status'=> '1', 
						'created_on'    => $date,
						'updated_on'    => $date,
						'status'        => 1
					]
				);
			}
		}else{
			$res = $this->Qdb->update_data('payment_info', array( 'status' => 0 ), array('customer_id' => $user_id) );
		}

		if( isset($_POST['ppa_send_creds']) ){
			
			$contact = 'contact@example.com';
			$user_count = $this->Qdb->query("SELECT * FROM site_settings WHERE user_id='".$_SESSION['user_id']."'","num_rows");
	        if ($user_count > 0) {
	            $site_settings = $this->Qdb->select_data('*','site_settings',array('user_id'=>$_SESSION['user_id']),1);
	        } else {
	            $site_settings = $this->Qdb->select_data('*','site_settings','',1,'',array('id', 'desc'));
	        }
	        $site_name = (isset($site_settings[0]['site_name']) && !empty($site_settings[0]['site_name']))?$site_settings[0]['site_name']:$_SESSION['site_name'];
	        $supportEmail = (isset($site_settings[0]['support_email']) && !empty($site_settings[0]['support_email']))?$site_settings[0]['support_email']:$_SESSION['support_mail'];

			$body = "<p>Dear ". $this->input->post('pps_name') .",</p>";
			$body .= '<br>';
			$body .= "<p>We are thrilled to welcome you to ". $site_name ."! Thank you for choosing to be a part of our community. </p>";
			$body .= "<p>Your new account is all set up, we're exited to have you on board.</p>";
			$body .= "<p>To get started, simply log in to your account using the following link: ".base_url('login')."</p>";
			$body .= '<br>';
			$body .= "<p>Login Credentials are</p>";
			$body .= "<p>Email: ". $this->input->post('pps_email') ."</p>";
			$body .= "<p>Password: ". $this->input->post('pps_password') ."</p>";
			$body .= '<br>';
			$body .= "<p>If you have nay question, encounter any issues, or need assistance with anything related to your account, please don't hesitate to contact our customer support team at </p>";
			$body .= "<p>".$supportEmail.". </p>";
			$body .= '<br>';
			$body .= "<p>Thank you for choosing ". $site_name .". We look forward to serving you and providing you with an exceptional experience. </p>";
			$body .= '<br>';
			$body .= "<p>Warm regards,</p>";
			$body .= '<br>';
			$body .= "<p>". $site_name ."</p>";
			$body .= "<p>". base_url() ."</p>";
			$body .= "<p>". $supportEmail ."</p>";
            sendEmailToUser($this->input->post('pps_email'),'New Password ['.$site_name.']',$body);

			// $res = sendUserEmailMandrill($this->input->post('pps_email'),'Welcome to '.$_SESSION['site_name'].' - Your Account is Ready!',$body , $_SESSION['site_name']);

		}

        echo json_encode($this->browserResponse);
	}

	// Admin get user details by id
	public function getUserInfoById(){
		$this->checkValidAJAX();
		if(!empty($this->input->post('user_id'))){
			$user_id = $this->input->post('user_id');
			$user_info = $this->Qdb->select_data( 'u_id,u_name,u_email,u_password,u_type,u_status' , 'usertbl', array('u_id' => $user_id));

			if( !empty($user_info) ){

				$output['pps_name'] = $user_info[0]['u_name'];
				$output['pps_email'] = $user_info[0]['u_email'];
				$output['pps_userid'] = $user_info[0]['u_id'];
				$user_plan = checkPlanDetails( $user_info[0]['u_id'] );
				if( $user_plan['status'] != 0 )
					$output['user_plan'] =  $user_plan['plan_id'];

				$this->browserResponse['status'] = 'success';
				$this->browserResponse['message'] = '';
				$this->browserResponse['formData'] = json_encode($output) ;
				$this->browserResponse['form'] = "#createupdateuser_form" ;
				$this->browserResponse['openModal'] = "#pxg_create_update_user_model" ;
			}
		}
        echo json_encode($this->browserResponse);
	}

	// Admin delete user by id
	public function deleteUserById(){
		$this->checkValidAJAX();
		if( !empty( $this->input->post('uniq_id') ) ){
			$user_id = $this->input->post('uniq_id');
			$user_data = $this->Qdb->select_data( 'u_pic' , 'usertbl', array('u_id' => $user_id));

			$res = $this->Qdb->delete_data('usertbl', array('u_id' => $user_id));
			if( !empty( $res ) ){

				if( !empty( $user_data ) )
					if( !empty($user_data[0]['u_pic']) ){
						$profile_path = getcwd().'/'.$user_data[0]['u_pic'];
						if( file_exists( $profile_path ) )
							unlink( $profile_path );
					}
				

				$res = $this->Qdb->delete_data('ar_form_data', array('user_id' => $user_id));
				$res = $this->Qdb->delete_data('payment_info', array('customer_id' => $user_id));
	
				
				$media_data = $this->Qdb->select_data( 'id,url,source' , 'imagelibrary', array('uid' => $user_id));
				foreach ($media_data as $key => $value) {
					if( $value['source'] == 'custom' )
						$furl = getcwd().'/uploads/medialibrary/'.$value['url'];
					else
						$furl = getcwd().'/uploads/pixaimages/'.$value['url'];
					if( file_exists( $furl ) )
						unlink( $furl );
				}
				$this->common->deleteDirectory( getcwd().'/uploads/template/user_'.$user_id );

				$res = $this->Qdb->delete_data('imagelibrary', array('uid' => $user_id));
				$res = $this->Qdb->delete_data('site_analytics', array('user_id' => $user_id));
				$res = $this->Qdb->delete_data('site_settings', array('user_id' => $user_id));
				$res = $this->Qdb->delete_data('user_campaigns', array('user_id' => $user_id));

			}

			$this->browserResponse['status'] = 'success';
			$this->browserResponse['message'] = 'User deleted Successfully';
			$this->browserResponse['redirect'] = 'reload';
		}
		echo json_encode($this->browserResponse);
	}

	// Admin Change User status
	public function updateUserActiveStatus(){
		$this->checkValidAJAX();
		$user_id = $this->input->post('user_id');
		if( !empty( $user_id ) ){
			$u_status = $this->input->post('user_status');
			$res = $this->Qdb->update_data('usertbl', array('u_status' => ($u_status == 'true' ? 1 : 2) ) ,array('u_id' => $user_id));

			$this->browserResponse['status'] = 'success';
			$this->browserResponse['message'] = ($u_status == 'true') ? 'User is Active' : 'User is In-Active';
		}
		echo json_encode($this->browserResponse);
	}
	
	/* Plan Ajax Starts */
	public function createUpdatePlan(){
		$this->checkValidAJAX();
		
		$this->form_validation->set_rules('plan_currency', 'Plan Currency', 'required|trim');
		$this->form_validation->set_rules('plan_price', 'Plan Price', 'required|trim');
		$this->form_validation->set_rules('plan_interval', 'Plan Interval', 'required|trim');
		$this->form_validation->set_rules('plan_description', 'Plan Description', 'required|trim');


		if ($this->form_validation->run() == FALSE){
			$this->browserResponse['message'] = strip_tags(validation_errors()) ;
		}else{
			/* Create Plan */

			$data['p_name'] = $this->input->post('plan_name'); 
			$data['p_price'] = $this->input->post('plan_price'); 
			$data['p_currency'] = $this->input->post('plan_currency'); 
			$data['p_interval'] = $this->input->post('plan_interval');
			$data['p_description'] = $this->input->post('plan_description'); 
			$data['p_sites'] = $this->input->post('sites_allowed'); 
			// $data['p_templates'] =  base64_decode( $this->input->post('plan_templates') ); 
			$data['p_templates'] =  (empty( $this->input->post('plan_templates1[]') )? '[]': json_encode($this->input->post('plan_templates1[]'))); 

			if($data['p_price']==0){
				$count_price = $this->db->where(['p_price'=>0])->from("plans_list")->count_all_results();
				if($count_price>0){
					$this->browserResponse['message']  = 'Free plan already exists';
					echo json_encode($this->browserResponse);die;
				}
			}

			if( empty($this->input->post('plan_id')) ){
	
				$this->form_validation->set_rules('plan_name', 'Plan Name', 'required|is_unique[plans_list.p_name]', array( 'required' => 'You have not provided %s.','is_unique' => 'This %s already exists.') ); 
				
				if ($this->form_validation->run() == FALSE){
					$this->browserResponse['message'] = strip_tags(validation_errors()) ;
				}
				else{
					$res = $this->Qdb->insert_data('plans_list', $data);
	
					if( !empty($res) ){
						$this->browserResponse['status'] = 'success';
						$this->browserResponse['message'] = 'Plan has been successfully created';
						$this->browserResponse['redirect'] = 'reload';
					}
				}
			}
			/* Update Plan */
			else {
				
				$res = $this->Qdb->update_data('plans_list', $data, array('id' => $this->input->post('plan_id')));
				if( !empty($res) ){
					$this->browserResponse['status']   = 'success';
					$this->browserResponse['redirect'] = 'reload';
					$this->browserResponse['message']  = 'Plan updated Successfully';
				}else{
					$this->browserResponse['status']   = 'success';
					$this->browserResponse['redirect'] = 'close';
					$this->browserResponse['message']  = 'No changes detected';
				}
				
			}
		}

        echo json_encode($this->browserResponse);
	}

	public function getPlanInfoById(){
		$this->checkValidAJAX();
		$plan_id = $this->input->post('plan_id');
		if(!empty( $plan_id )){
			$plan = $this->Qdb->select_data( '*' , 'plans_list', array('id' => $plan_id));

			if( !empty($plan) ){
				
				$output['plan_name'] = $plan[0]['p_name'];
				$output['plan_price'] = $plan[0]['p_price'];
				$output['plan_currency'] = $plan[0]['p_currency'];
				$output['plan_interval'] = $plan[0]['p_interval'];
				$output['plan_description'] = $plan[0]['p_description'];
				$output['sites_allowed'] = $plan[0]['p_sites'];
				// $output['plan_templates'] = base64_encode( $plan[0]['p_templates']);
				$output['plan_templates1[]'] = json_decode($plan[0]['p_templates'], true);
				$output['plan_id'] = $plan[0]['id'];
				
				$this->browserResponse['data']['elm_'] = '#selected_templates_num';
				$this->browserResponse['data']['txt_'] = 'Selected Templates - '.count( json_decode( $plan[0]['p_templates'], true) );

				$this->browserResponse['status'] = 'success';
				$this->browserResponse['message'] = '';
				$this->browserResponse['formData'] = json_encode($output) ;
				$this->browserResponse['form'] = "#createupdateplan_form" ;
				$this->browserResponse['openModal'] = "#pxg_create_update_plan_model" ;
			}
		}
        echo json_encode($this->browserResponse);
	}
	
	public function updatePlanActiveStatus(){
		$this->checkValidAJAX();
		$plan_id = $this->input->post('plan_id');
		if( !empty( $plan_id ) ){
			$p_status = $this->input->post('plan_status');
			$res = $this->Qdb->update_data('plans_list', array('p_status' => ($p_status == 'true' ? 1 : 0) ) ,array('id' => $plan_id));

			$this->browserResponse['status'] = 'success';
			$this->browserResponse['message'] = ($p_status == 'true') ? 'Plan is visible to users' : 'Plan is not visible to users';
		}
		echo json_encode($this->browserResponse);
	}
	
	public function deletePlanById(){
		$this->checkValidAJAX();
		$plan_id = $this->input->post('uniq_id');
		if( !empty( $plan_id ) ){
			$res = $this->Qdb->delete_data('plans_list', array('id' => $plan_id));

			$this->browserResponse['status'] = 'success';
			$this->browserResponse['message'] = 'Plan removed Successfully';
			$this->browserResponse['redirect'] = 'reload';
		}
		echo json_encode($this->browserResponse);
	}

	public function getTemplateByKeyword(){
		$keyword = $this->input->post('term');
		$templates = $this->Qdb->select_data( 'id,template_name' , 'dfy_templates', '', '', '', '', array('template_name', $keyword));
		echo json_encode($templates);

	}

	public function loadTemplatesForPlanAdd(){
		$this->checkValidAJAX();

        $offset 		= $this->input->post('offset');
        $search 		= $this->input->post('search');
        $limit 			= $this->input->post('limit');
        $filter 		= $this->input->post('filter');
        $plan_id 		= $this->input->post('plan_id');
        $selected 		= !empty( $this->input->post('selected') )? explode(',' ,$this->input->post('selected')): [];
		$p_templates 	= $this->Qdb->select_data( 'id,p_templates' , 'plans_list', array('id' => $plan_id));
		$selected_temps = !empty( $p_templates[0]['p_templates'] )? json_decode($p_templates[0]['p_templates'], true): [];

        $search_data = $html  = '';
        if( !empty( $search ) )
            $search_data = array('template_name', $search);

		if( $filter == 1 ){
			$where_in = 'id IN ('.implode(',', (!empty($selected_temps)? $selected_temps : [0]) ).')';
			$templates_list = $this->Qdb->select_data( '*' , 'dfy_templates', $where_in, array($limit, $offset), '', array('id','desc'), $search_data);
		}
		else if( $filter == 2 ){

			$where_in = 'id IN ('.implode(',', (!empty($selected)? $selected : [0]) ).')';
			$templates_list = $this->Qdb->select_data( '*' , 'dfy_templates', $where_in, array($limit, $offset), '', array('id','desc'), $search_data);
		}
		else{
			$templates_list = $this->Qdb->select_data( '*' , 'dfy_templates', '', array($limit, $offset), '', array('id','desc'), $search_data);
		}
        

        foreach ($templates_list as $key => $value) {
			$html .= $this->common->dfyTempElementAdminForPlan($value, in_array($value['id'], (empty($selected)? [] : $selected)));
			/* if( !$filter )
            	$html .= $this->common->dfyTempElementAdminForPlan($value, in_array($value['id'], (empty($selected)? [] : $selected)));
            else
				$html .= $this->common->dfyTempElementAdminForPlan($value, in_array($value['id'], (empty($selected_temps)? [] : $selected_temps))); */
            $offset ++;
        }
        
       $this->browserResponse['status']  = 'success';
       $this->browserResponse['count']  = count( $templates_list );
       $this->browserResponse['html']    = $html;
       $this->browserResponse['message'] = '';
       $this->browserResponse['offset']  = $offset;
       echo json_encode( $this->browserResponse );die;
	}
	/* Plan Ajax Ends   */

	/* Admin Template Ajax Starts   */
	public function updateAdminTemplate(){
		$this->checkValidAJAX();
		$template_id   = $this->input->post('template_id');
		$html          = $this->input->post('html');
		
		$template_data = $this->Qdb->select_data( '*' , 'dfy_templates', array('id' => $template_id));
		if( !empty( $template_data ) ){
			$temp_url = getcwd().'/'.$template_data[0]['zip_path'].'/index.html';
			// $template_content = '<!DOCTYPE html><html lang="en">'.$html.'</html>';
			$template_content = '<!DOCTYPE html>'. PHP_EOL .'<html lang="en">'.preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $html). PHP_EOL .'</html>';
            if (strpos($template_content, '<head>') === false) {
                $template_content = str_replace(['<html lang="en">','</html>'], ['<html lang="en">'. PHP_EOL .'<head>','</body>'. PHP_EOL .'</html>'], $template_content);
                $template_content = preg_replace('/<(div|section|header)/', '</head>'. PHP_EOL .'<body>'. PHP_EOL .'<$1', $template_content, 1);
            }
			$res = file_put_contents($temp_url, $template_content);
			if( $res ){
				$this->browserResponse['status']  = 'success';
				$this->browserResponse['message'] = 'Template updated successfully';
			}
		}
		echo json_encode( $this->browserResponse );die;

	}
	/* Admin Template Ajax Ends   */

	/* Email Settings Ajax Starts */
	public function addMandrillSettings(){
		$this->checkValidAJAX();
		
		$data['m_email'] = $this->input->post('m_email');
		$data['m_key']   = $this->input->post('m_key');

		$currentSiteData = $this->Qdb->select_data( 'id,mandrill_settings' , 'site_settings', array( 'user_id' => $this->user_id ));
		$data = json_encode($data);

        sendUserEmailMandrill('support@pixelpages.net', 'Checking Mandrill', 'test', true);

		if( empty( $currentSiteData ) )
			$res = $this->Qdb->insert_data('site_settings' , array('mandrill_settings' => $data, 'user_id' => $this->user_id));
		else
			$res = $this->Qdb->update_data('site_settings', array('mandrill_settings' => $data, 'date_updated' => date('Y-m-d H:i:s')), ['user_id' => $this->user_id]);
		
		if( $res ){
		    $this->browserResponse['status'] = 'success';
			$this->browserResponse['message']  = 'Settings saved successfully';
			$this->browserResponse['redirect'] = 'reload';
		}
		else
			$this->browserResponse['message'] = 'No changes detected';
		
		echo json_encode( $this->browserResponse );die;

	}
	public function addSmtpSettings(){
		$this->checkValidAJAX();

		$data['s_host']     = $this->input->post('s_host');
		$data['s_port']     = $this->input->post('s_port');
		$data['s_username'] = $this->input->post('s_username');
		$data['s_password'] = $this->input->post('s_password');
		$data['s_encryption'] = $this->input->post('s_encryption');

		$currentSiteData = $this->Qdb->select_data( 'id,site_logo' , 'site_settings', array( 'user_id' => $this->user_id ));
		$data_ar = $data;
		$data = json_encode($data);

		sendUserEmailSmtp( 'test', ['email' => 'praveen.upadhyay@pixelnx.com', 'subject' => 'Checking smtp'], $data_ar, true );

		if( empty( $currentSiteData ) )
			$res = $this->Qdb->insert_data('site_settings' , array('smtp_settings' => $data, 'user_id' => $this->user_id));
		else
			$res = $this->Qdb->update_data('site_settings', array('smtp_settings' => $data, 'date_updated' => date('Y-m-d H:i:s')), ['user_id' => $this->user_id]);
		
		$this->browserResponse['status'] = 'success';
		if( $res ){
			$this->browserResponse['message']  = 'Settings saved successfully';
			$this->browserResponse['redirect'] = 'reload';
		}
		else
			$this->browserResponse['message'] = 'No changes detected';
		
		echo json_encode( $this->browserResponse );die;

	}

	public function disconnectEmailSetting($type){
		$this->checkValidAJAX();

		if( $type == 1 )
			$res = $this->Qdb->update_data('site_settings', array('mandrill_settings' => '', 'date_updated' => date('Y-m-d H:i:s')), ['user_id' => $this->user_id]);
		else if( $type == 2 )
			$res = $this->Qdb->update_data('site_settings', array('smtp_settings' => '', 'date_updated' => date('Y-m-d H:i:s')), ['user_id' => $this->user_id]);

		$this->browserResponse['status'] = 'success';
		if( $res ){
			$this->browserResponse['message']  = 'Email settings disconnected.';
			$this->browserResponse['redirect'] = 'reload';
		}
		else
			$this->browserResponse['message'] = 'No changes detected';
		echo json_encode( $this->browserResponse );die;

	}
	/* Email Settings Ajax Ends   */

	public function addSiteSettings() {
	    $this->checkValidAJAX();
	    $this->form_validation->set_rules('site_title', 'Site title', 'required');
	    $this->form_validation->set_rules('meta_keywords', 'Meta keywords', 'required');
	    $this->form_validation->set_rules('meta_author', 'Meta author', 'required');
	    $this->form_validation->set_rules('meta_description', 'Meta description', 'required');
	    $this->form_validation->set_rules('site_copyright', 'Site copyright', 'required');
	    if ($this->form_validation->run() == FALSE) {
	        $this->browserResponse['message'] = strip_tags(validation_errors());
	    } else {
	        $frontend_settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	        $get_img = json_decode($frontend_settings[0]['site_settings']);
	        $img_path = getcwd() . '/uploads/frontend/';
	        if (!empty($_FILES["site_logo"]["name"])) {
	            $config["upload_path"] = $img_path;
	            $config["allowed_types"] = "jpg|jpeg|png|gif";
	            $config['max_size'] = '1024';
	            $config["file_name"] = substr(md5(microtime()), 0, 10) . "_" . $_SESSION['user_id'];
	            $this->load->library("upload", $config);
	            $this->upload->initialize($config);
	            if ($this->upload->do_upload("site_logo")) {
	                if (!empty($get_img->site_logo) && file_exists($img_path . basename($get_img->site_logo))) {
	                    unlink($img_path . basename($get_img->site_logo));
	                }
	                $uploadData = $this->upload->data();
	                $site_logo = "uploads/frontend/" . $uploadData["file_name"];
	            } else {
	                $this->browserResponse['message'] = strip_tags($this->upload->display_errors());
	                $this->browserResponse['status'] = 'error';
	                $this->browserResponse['redirect'] = '';
	                echo json_encode($this->browserResponse);
	                exit;
	            }
	        } else {
	            $site_logo = $this->input->post('old_site_logo');
	        }
	        if (!empty($_FILES["site_favicon"]["name"])) {
	            $config["upload_path"] = $img_path;
	            $config["allowed_types"] = "jpg|jpeg|png|gif";
	            $config['max_size'] = '1024';
	            $config["file_name"] = substr(md5(microtime()), 0, 10) . "_" . $_SESSION['user_id'];
	            $this->load->library("upload", $config);
	            $this->upload->initialize($config);
	            if ($this->upload->do_upload("site_favicon")) {
	                if (!empty($get_img->site_favicon) && file_exists($img_path . basename($get_img->site_favicon))) {
	                    unlink($img_path . basename($get_img->site_favicon));
	                }
	                $uploadData = $this->upload->data();
	                $site_favicon = "uploads/frontend/" . $uploadData["file_name"];
	            } else {
	                $this->browserResponse['message'] = strip_tags($this->upload->display_errors());
	                $this->browserResponse['status'] = 'error';
	                $this->browserResponse['redirect'] = '';
	                echo json_encode($this->browserResponse);
	                exit;
	            }
	        } else {
	            $site_favicon = $this->input->post('old_site_favicon');
	        }
	        if (!empty($_FILES["site_preloader"]["name"])) {
	            $config["upload_path"] = $img_path;
	            $config["allowed_types"] = "jpg|jpeg|png|gif";
	            $config['max_size'] = '1024';
	            $config["file_name"] = substr(md5(microtime()), 0, 10) . "_" . $_SESSION['user_id'];
	            $this->load->library("upload", $config);
	            $this->upload->initialize($config);
	            if ($this->upload->do_upload("site_preloader")) {
	                if (!empty($get_img->site_preloader) && file_exists($img_path . basename($get_img->site_preloader))) {
	                    unlink($img_path . basename($get_img->site_preloader));
	                }
	                $uploadData = $this->upload->data();
	                $site_preloader = "uploads/frontend/" . $uploadData["file_name"];
	            } else {
	                $this->browserResponse['message'] = strip_tags($this->upload->display_errors());
	                $this->browserResponse['status'] = 'error';
	                $this->browserResponse['redirect'] = '';
	                echo json_encode($this->browserResponse);
	                exit;
	            }
	        } else {
	            $site_preloader = $this->input->post('old_site_preloader');
	        }
	        $data['site_settings'] = json_encode(array(
	        	'site_title' 		=> $this->input->post('site_title'), 
	        	'meta_keywords' 	=> $this->input->post('meta_keywords'), 
	        	'meta_author' 		=> $this->input->post('meta_author'), 
	        	'meta_description' 	=> $this->input->post('meta_description'), 
	        	'site_logo' 		=> $site_logo, 
	        	'site_favicon' 		=> $site_favicon, 
	        	'site_preloader' 	=> $site_preloader, 
	        	'site_copyright' 	=> $this->input->post('site_copyright'),
	        ));
	        $settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	        $res = $this->Qdb->update_data('frontend_settings', $data, array('id' => $settings[0]['id']));
	        if ($res) {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'reload';
	            $this->browserResponse['message'] = 'Site Settings updated Successfully';
	        } else {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'close';
	            $this->browserResponse['message'] = 'No changes detected';
	        }
	    }
	    echo json_encode($this->browserResponse);
	}

	public function addAboutUs() {
	    $this->checkValidAJAX();
	    $this->form_validation->set_rules('about_heading', 'Site title', 'required');
	    $this->form_validation->set_rules('about_sub_heading', 'Meta keywords', 'required');
	    $this->form_validation->set_rules('about_description', 'Meta description', 'required');
	    if ($this->form_validation->run() == FALSE) {
	        $this->browserResponse['message'] = strip_tags(validation_errors());
	    } else {
	        $frontend_settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	        $get_img = json_decode($frontend_settings[0]['about_us']);
	        $img_path = getcwd() . '/uploads/frontend/';
	        if (!empty($_FILES["about_image"]["name"])) {
	            $config["upload_path"] = $img_path;
	            $config["allowed_types"] = "jpg|jpeg|png|gif";
	            $config['max_size'] = '1024';
	            $config["file_name"] = substr(md5(microtime()), 0, 10) . "_" . $_SESSION['user_id'];
	            $this->load->library("upload", $config);
	            $this->upload->initialize($config);
	            if ($this->upload->do_upload("about_image")) {
	                if (!empty($get_img->about_image) && file_exists($img_path . basename($get_img->about_image))) {
	                    unlink($img_path . basename($get_img->about_image));
	                }
	                $uploadData = $this->upload->data();
	                $about_image = "uploads/frontend/" . $uploadData["file_name"];
	            } else {
	                $this->browserResponse['message'] = strip_tags($this->upload->display_errors());
	                $this->browserResponse['status'] = 'error';
	                $this->browserResponse['redirect'] = '';
	                echo json_encode($this->browserResponse);
	                exit;
	            }
	        } else {
	            $about_image = $this->input->post('old_about_image');
	        }
	        $data['about_us'] = json_encode(array(
	        	'about_heading' 		=> $this->input->post('about_heading'), 
	        	'about_sub_heading' 	=> $this->input->post('about_sub_heading'),
	        	'about_description' 	=> $this->input->post('about_description'), 
	        	'about_image' 	=> $about_image,
	        ));
	        $settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	        $res = $this->Qdb->update_data('frontend_settings', $data, array('id' => $settings[0]['id']));
	        if ($res) {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'reload';
	            $this->browserResponse['message'] = 'About Us updated Successfully';
	        } else {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'close';
	            $this->browserResponse['message'] = 'No changes detected';
	        }
	    }
	    echo json_encode($this->browserResponse);
	}

	public function valid_url($str) {
        return (filter_var($str, FILTER_VALIDATE_URL) !== FALSE);
    }

	public function addPrivacyPolicy() {
	    $this->checkValidAJAX();
	    $this->form_validation->set_rules('privacy_policy', 'Privacy Policy', 'required');
	    if ($this->form_validation->run() == FALSE) {
	        $this->browserResponse['message'] = strip_tags(validation_errors());
	    } else {
	        $data['privacy_policy'] = $this->input->post('privacy_policy');
	        $settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	        $res = $this->Qdb->update_data('frontend_settings', $data, array('id' => $settings[0]['id']));
	        if ($res) {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'reload';
	            $this->browserResponse['message'] = 'Privacy Policy updated Successfully';
	        } else {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'close';
	            $this->browserResponse['message'] = 'No changes detected';
	        }
	    }
	    echo json_encode($this->browserResponse);
	}
	
	public function addTermsConditions() {
	    $this->checkValidAJAX();
	    $this->form_validation->set_rules('terms_conditions', 'Terms & Conditions', 'required');
	    if ($this->form_validation->run() == FALSE) {
	        $this->browserResponse['message'] = strip_tags(validation_errors());
	    } else {
	        $data['terms_conditions'] = $this->input->post('terms_conditions');
	        $settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	        $res = $this->Qdb->update_data('frontend_settings', $data, array('id' => $settings[0]['id']));
	        if ($res) {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'reload';
	            $this->browserResponse['message'] = 'Terms & Conditions updated Successfully';
	        } else {
	            $this->browserResponse['status'] = 'success';
	            $this->browserResponse['redirect'] = 'close';
	            $this->browserResponse['message'] = 'No changes detected';
	        }
	    }
	    echo json_encode($this->browserResponse);
	}

	public function addTestimonialSettings() {
	    $testimonial_image = [];
	    $img_path = getcwd() . '/uploads/frontend/';
	    foreach ($_FILES['testimonial_image']['name'] as $key => $image) {
	        if (!empty($image)) {
	            $_FILES['img']['name'] = $_FILES['testimonial_image']['name'][$key];
	            $_FILES['img']['type'] = $_FILES['testimonial_image']['type'][$key];
	            $_FILES['img']['tmp_name'] = $_FILES['testimonial_image']['tmp_name'][$key];
	            $_FILES['img']['error'] = $_FILES['testimonial_image']['error'][$key];
	            $_FILES['img']['size'] = $_FILES['testimonial_image']['size'][$key];
	            $config['upload_path'] = $img_path;
	            $config['allowed_types'] = 'jpeg|jpg|png|gif|avif';
	            $config['max_size'] = '1024';
	            $this->load->library('upload', $config);
	            if ($this->upload->do_upload('img')) {
	                $frontend_settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	                $get_ans_img = json_decode($frontend_settings[0]['testimonials']);
	                if (!empty($get_ans_img->testimonial_image[$key]) && file_exists($img_path . basename($get_ans_img->testimonial_image[$key]))) {
	                    unlink($img_path . basename($get_ans_img->testimonial_image[$key]));
	                }
	                $fileData = $this->upload->data();
	                array_push($testimonial_image, "uploads/frontend/" . $fileData['file_name']);
	            } else {
	                $this->browserResponse['message'] = strip_tags($this->upload->display_errors());
	                $this->browserResponse['status'] = 'error';
	                $this->browserResponse['redirect'] = '';
	                echo json_encode($this->browserResponse);
	                exit;
	            }
	        } else {
	            array_push($testimonial_image, $_POST['old_testimonial_image'][$key]);
	        }
	    }
	    if (!empty($_POST['unlink_testimonial_img'])) {
	        foreach ($_POST['unlink_testimonial_img'] as $unlink_ti) {
	            if (!empty($unlink_ti) && file_exists($img_path . basename($unlink_ti))) {
	                unlink($img_path . basename($unlink_ti));
	            }
	        }
	    }
	    $data['testimonials'] = json_encode(array(
	    	'testimonial_title' => $_POST['testimonial_title'], 
	    	'testimonial_type' => $_POST['testimonial_type'], 
	    	'testimonial_description' => $_POST['testimonial_description'], 
	    	'testimonial_image' => $testimonial_image,
	    ));
	    $settings = $this->Qdb->select_data('*', 'frontend_settings', '', '', '', array('id', 'desc'));
	    $res = $this->Qdb->update_data('frontend_settings', $data, array('id' => $settings[0]['id']));
	    if ($res) {
	        $this->browserResponse['status'] = 'success';
	        $this->browserResponse['redirect'] = 'reload';
	        $this->browserResponse['message'] = 'Testimonial updated Successfully';
	    } else {
	        $this->browserResponse['status'] = 'success';
	        $this->browserResponse['redirect'] = 'close';
	        $this->browserResponse['message'] = 'No changes detected';
	    }
	    echo json_encode($this->browserResponse);
	}
	

}