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

class Dashboard extends CI_Controller {

	public function __construct(){
		parent::__construct();
		check_login_user();
		//check expired function && call get_expired_users
		$this->get_expired_users();
		is_valid();
	}

	public function index()
	{
		
		if(check_code()==1 || check_code()==2){
			if(is_update()==1 && auth('user_type')==1):
				//$this->check_update_purchases();
				$this->dashboard();
			else:
				$this->dashboard();
			endif;
		}else{
			//$this->check_valid_purchases();
			$this->dashboard();
		}
	}


	public function dashboard()
	{
		$data = array();
		$data['page_title'] = "Dashboard";
		$data['pricing'] = $this->admin_m->get_user_pricing_by_id();
		$data['all_user'] = $this->admin_m->get_new_users(10);
		$data['features']=$this->admin_m->select('features');
		$data['user_type']=$this->admin_m->get_total_user_by_account_type();
		//$data['base_url'] = base_url('admin/dashboard/home');
		$data['main_content'] = $this->load->view('admin/dashboard/home', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function check_valid_purchases()
	{
		if(check_code()==1 || check_code()==2){
			if(is_update()==0):
				redirect('admin/dashboard');
			else:
			endif;
		}
		$data = array();
		$data['page_title'] = "Check Valid Purchase";
		$data['page'] = "Login";
        $data['user_type']=$this->admin_m->get_total_user_by_account_type();
		$data['main_content'] = $this->load->view('admin/dashboard/check_valid', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function check_update_purchases()
	{
		if(is_update()==0):
			redirect('admin/dashboard');
		endif;
		$data = array();
		$data['page_title'] = "Check Valid Purchase";
		$data['page'] = "Login";
        $data['user_type']=$this->admin_m->get_total_user_by_account_type();
		$data['main_content'] = $this->load->view('admin/dashboard/check_valid', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  *** Active site with purchase code
	**/ 
	public function active_site(){
		$this->form_validation->set_rules('code', 'Purchase code', 'trim|required|xss_clean');
		$data = array(
			'supported_until' => '10.10.2040',
			'active_code' => '******************',
			'purchase_code' => '******************',
			'site_url' => SITE_LINK,
			'active_key' => '******************',
			'is_update' => 0,
			'license' => 'valid',
			'site_info' => 'site_info',
		    'purchase_date' => '05.05.2022',
			'license_code' => '******************',
			'created_at' =>d_time(),
		);
		$insert = $this->admin_m->update_setting($data,$site_id,'setting');
		$this->session->set_flashdata('success','Thank you! Your site is active now');
		redirect(base_url('admin/dashboard/'));
	}

	public function check_vaild($code,$site_id){
		// check_valid_purchases
			$form_data = array(
				'code'  => $code,
				'site_id'  => $site_id,
				'site_link'  => SITE_LINK,
			);

			$form_data = json_encode($form_data);
			$ch = curl_init(URL."check-valid");  
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                     
			curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);                   
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
			curl_setopt($ch, CURLOPT_POST,1);                                    
			$result = curl_exec($ch);
			curl_close($ch);
			return $result = json_decode($result);
	}



	/**
	  *** resend verify mail
	**/ 
	public function resend_verify_mail($username){
		$send = $this->email_m->resend_verify_mail($username);
		if($send ==TRUE):
			$this->session->set_flashdata('success', 'your verification link send Successfully');
			redirect($_SERVER['HTTP_REFERER']);
		else:
			$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
			redirect($_SERVER['HTTP_REFERER']);
		endif;
	}
	 
	/**
	  ** Get Total users
	**/  

	public function total_user()
	{

		check_valid_auth();
		$data = array();
		$data['page_title'] = "Total User";
		$data['page'] = "Users";

		//pagination
		$config = [];
		$this->load->library('pagination');

		$per_page = isset($_GET['limit'])?$_GET['limit']:20;

		$page = $this->input->get('page');
		if (empty($page)) {
			$page = 0;
		}

		if ($page != 0) {
			$page = $page-1;
		}
		$offset = ceil($page * $per_page);
		$total = $this->admin_m->get_all_user(0,0,0,$is_total=1);
		$config['base_url'] = base_url('admin/dashboard/total_user');
		$config['total_rows'] = $total;
		$config['per_page'] =  $per_page;
		$this->pagination->initialize($config);



		$data['features_type']=$this->admin_m->select('features_type');
		$data['features']=$this->admin_m->select('features');
		$data['pricing']=$this->admin_m->get_pricing();
		$data['all_user'] = $this->admin_m->get_all_user(0,$per_page,$offset,0);
		$data['main_content'] = $this->load->view('admin/dashboard/total_user', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  **  select single user
	**/ 
	public function single_user_by_id($id)
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Edit User";
        $data['page'] = "Dashboard";
        $data['user']= $this->admin_m->single_select_by_id($id,'users');
		$data['main_content'] = $this->load->view('admin/dashboard/edit_user', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


	


	/**
	  **change  package with offline payment of by admin 
	**/ 
	public function change_packege($id)
	{
		is_test();
		check_valid_auth();
		$user_info = get_all_user_info_id($id);
		$package_id =  $this->input->post('package_id',TRUE);
		$package_info = get_package_info_by_id($package_id);
		$data = array(
			'account_type' => $this->input->post('package_id',TRUE),
			'start_date'=>d_time(),
			'end_date'=>add_year($package_info['type']),
			'is_payment'=>1,
			'is_verify'=>1,
			'is_expired'=>0,
		);	
		$edit = $this->admin_m->update($data,$id,'users');
		if($edit){
			
			$random_number = random_string('alnum',16);
			$data = array(
				'user_id' => $user_info['user_id'],
				'account_type' => $package_info['id'],
				'price' => $package_info['price'],
				'txn_id' => $random_number,
				'payment_type' => 0,
				'status' => 'Completed',
				'created_at' => d_time(),
			);
			$insert = $this->admin_m->insert($data,'payment_info');
			if($insert){
				$this->email_m->send_payment_paid_email($data,'Author');
			}
			
			$this->session->set_flashdata('success', 'Package Change Successfully');
			redirect($_SERVER['HTTP_REFERER']);
		}else{
			$this->session->set_flashdata('error', 'Somthing worng. Error!!');
			redirect($_SERVER['HTTP_REFERER']);
		}
		
	}


	/**
	  ** offline_payment by admin 
	**/
	public function offline_payment($username,$status){
		$user_info = get_all_user_info_slug($username);

		$data = array('is_payment'=>1,'is_verify'=>1,'is_expired'=>0,'is_request'=>0,'verify_time'=>d_time(),'start_date'=>d_time(),'end_date'=>add_year($user_info['type']));


		$edit = $this->admin_m->verify_mail($data, $username,'users'); //update payment/verify status

		if($edit):
			$random_number = random_string('alnum',16);
            $data = array(
                'user_id' => $user_info['user_id'],
                'account_type' => $user_info['account_type'],
                'price' => $user_info['price'],
                'txn_id' => $random_number,
                'payment_type' => 0,
                'status' => 'Completed',
                'created_at' => d_time(),
            );
            $insert = $this->admin_m->insert($data,'payment_info');
            if($insert){
            	$off_data = array(
            		'approve_time' => d_time(),
            		'status'=>1,
            	);
            	$this->admin_m->update_user($off_data,$user_info['user_id'],'offline_payment');
            	
            	$this->email_m->send_payment_paid_email($data,'Author');
            }
            $this->session->set_flashdata('success', $username.' \'s Payment successfull');
			redirect($_SERVER['HTTP_REFERER']);
        else:
			$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
			redirect($_SERVER['HTTP_REFERER']);
          endif;  

		
	}



	/**
	  ** email verify by admin (offline verify)
	**/
	public function verifiy($username,$status){
		$data = array('is_verify'=>$status,'verify_time'=>d_time());
		$this->admin_m->verify_mail($data, $username,'users');
		$this->session->set_flashdata('verify', ' Account verify successfully');
		redirect($_SERVER['HTTP_REFERER']);
	}


	/**
	  **change user status by admin 
	**/ 
	public function change_status($id,$is_active)
	{
		is_test();
		if($is_active==0):
			$data = array('is_active' => 1,);
		else:
			$data = array('is_active' => 0,);
		endif;	
		$edit = $this->admin_m->update($data,$id,'users');
		if($edit){
			if($is_active==0):
				$this->session->set_flashdata('success', 'User Account is Active Now');
			else:
				$this->session->set_flashdata('success', 'User Account is  Deactive Now ');
			endif;
			redirect($_SERVER['HTTP_REFERER']);
			}else{
			$this->session->set_flashdata('error', 'Somthing worng. Error!!');
			redirect($_SERVER['HTTP_REFERER']);
		}
		
	}



/**
  *** delete user by admin
**/ 
	public function delete($id)
	{
		is_test();
		$del= $this->admin_m->delete($id,"users");
		if($del){
			$this->session->set_flashdata('success', 'User Delete Successfully');
			redirect($_SERVER['HTTP_REFERER']);
		}else{
			$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
			redirect($_SERVER['HTTP_REFERER']);
		}
	}


/**
  ** site services
**/
	public function services()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Services";
    $data['page'] = "Dashboard";
    $data['data'] = false;
    $data['services'] = $this->admin_m->select('site_services');
		$data['main_content'] = $this->load->view('admin/dashboard/services', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  ** edit site services
	**/

	public function edit_services($id)
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Services";
        $data['page'] = "Dashboard";
        $data['data'] =$this->admin_m->single_select_by_id($id,'site_services');
        $data['services'] = $this->admin_m->select('site_services');
		$data['main_content'] = $this->load->view('admin/dashboard/services', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  *** site add_services
	**/ 
	public function add_services(){
		is_test();
		$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
		$this->form_validation->set_rules('details', 'Details', 'required|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			$this->services();
			}else{	
				$data = array(
					'title' => $this->input->post('title',true),
					'details' => $this->input->post('details'),
					'created_at' => d_time(),
				);
				$id = $this->input->post('id');
				if($id==0){
					$insert = $this->admin_m->insert($data,'site_services');
				}else{
					$insert = $this->admin_m->update($data,$id,'site_services');
				}

				if($insert){
					$this->upload_service_images($insert,'site_services');
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/services'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/services'));
				}	
		}
	}


	/**
	  *** site pricing
	**/ 
	public function features()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Features";
        $data['page'] = "Dashboard";
        $data['data'] = FALSE;
        $data['features_type']=$this->admin_m->select('features_type');
        $data['features']=$this->admin_m->select('features');
        $data['pricing']=$this->admin_m->get_pricing();
		$data['main_content'] = $this->load->view('admin/dashboard/features', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


	/**
	  *** site pricing
	**/ 
	public function add_package()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Packages";
    $data['page'] = "Packages";
    $data['data'] = FALSE;
    $data['features_type']=$this->admin_m->select('features_type');
    $data['features']=$this->admin_m->select('features');
    $data['pricing']=$this->admin_m->get_pricing();
		$data['main_content'] = $this->load->view('admin/dashboard/packages/create_package', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function edit_pricing($id)
	{
		$data = array();
		$data['page_title'] = "Pricing";
    $data['page'] = "Dashboard";
    $data['data'] = $this->admin_m->single_select_by_id($id,'features_type');
    $data['features_type']=$this->admin_m->select('features_type');
    $data['features']=$this->admin_m->select('features');
    $data['pricing']=$this->admin_m->get_pricing();
		$data['main_content'] = $this->load->view('admin/dashboard/pricing', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


	/**
	  *** add pricing
	**/ 
	public function add_pricing(){
			is_test();
			$this->form_validation->set_rules('type_id', 'Feature Type', 'required|trim|xss_clean|max_length[20]');
			$this->form_validation->set_rules('feature_id[]', 'Features', 'trim|xss_clean|required');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/pricing'));
			}else{	

				$feature_id = $this->input->post('feature_id',TRUE);
				if(isset($feature_id)){
					if($this->input->post('id')!=0){
						$this->admin_m->delete_pricing($this->input->post('id'),'pricing');
					}
					foreach ($feature_id as $value):
						$data = array(
							'type_id' => $this->input->post('type_id',TRUE),
							'feature_id' => $value,
							'created_at' => d_time(),
						);
						$insert = $this->admin_m->insert($data,'pricing');
					endforeach;
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/pricing'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/pricing'));
				}	
		}
	}


	/**
	  ***  Features
	**/ 
	public function packages()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Packages";
    $data['page'] = "Packages";
    $data['data'] = FALSE;
    $data['type_data'] = FALSE;
    $data['packages']=$this->admin_m->select('features_type');
    $data['features']=$this->admin_m->select('features');
		$data['main_content'] = $this->load->view('admin/dashboard/packages/packages', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  ** edit features type
	**/
	public function edit_features_type($id)
	{
		$data = array();
		$data['page_title'] = "Packages";
    $data['page'] = "Packages";
    $data['data'] = FALSE;
    $data['type_data'] = $this->admin_m->single_select_by_id($id,'features_type');
    $data['features_type']=$this->admin_m->select('features_type');
    $data['features']=$this->admin_m->select('features');
		$data['main_content'] = $this->load->view('admin/dashboard/packages/create_package', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  ** Edit features
	**/
	public function edit_features($id)
	{
		$data = array();
		$data['page_title'] = "Features";
    $data['page'] = "Dashboard";
    $data['data'] = $this->admin_m->single_select_by_id($id,'features');
    $data['type_data'] = FALSE;
    $data['features_type']=$this->admin_m->select('features_type');
    $data['features']=$this->admin_m->select('features');
		$data['main_content'] = $this->load->view('admin/dashboard/features', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  *** add add_features_type
	**/ 
	public function add_features_type(){
			is_test();
			$type = $this->input->post('type',TRUE);
			$this->form_validation->set_rules('type_name', 'Name', 'required|trim|xss_clean|max_length[20]');
			$this->form_validation->set_rules('slug', 'Slug', 'required|trim|xss_clean|callback_english_check');
			$this->form_validation->set_rules('type', 'Types', 'trim|xss_clean|required');
			$this->form_validation->set_rules('vcard_limit', 'vCard Limit', 'trim|xss_clean|required');
			$this->form_validation->set_rules('feature_id[]', 'Features', 'trim|xss_clean|required');

			if($type=='free' || $type=='trial'){
				$this->form_validation->set_rules('price', 'Price', 'trim|xss_clean');
				$price = 0;
			}else{
				$this->form_validation->set_rules('price', 'Price', 'required|xss_clean|trim|callback_number_check');
				$price = $this->input->post('price',TRUE);
			}
			
			$this->form_validation->set_rules('type_limit', 'Limit', 'trim|xss_clean|required');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/packages'));
			}else{	
				$data = array(
					'type_name' => $this->input->post('type_name',TRUE),
					'slug' => str_slug($this->input->post('slug',TRUE)),
					'price' => $price,
					'type' => $type,
					'type_limit' => $this->input->post('type_limit',TRUE),
					'vcard_limit' => $this->input->post('vcard_limit',TRUE),
					'card_limit' => $this->input->post('card_limit',TRUE),
					'created_at' => d_time(),
				);
				$id = $this->input->post('id',TRUE);
				if($id != 0):
					$insert = $this->admin_m->update($data,$id,'features_type');
				else:
					$insert = $this->admin_m->insert($data,'features_type');
				endif;

				if($insert){

					$feature_id = $this->input->post('feature_id',TRUE);
					if(isset($feature_id)){

						if($this->input->post('id')!=0){
							$this->admin_m->delete_pricing($this->input->post('id'),'pricing');
						}


						$is_profile = in_array(1,$feature_id);
						if(isset($is_profile) && $is_profile==1){
							$feature_id = $feature_id;
						}else{
							$ids = [1,2,3,4,5,6,7,8,9,10,11,12,13];
							$feature_id = array_diff($feature_id, $ids);
						}

						foreach ($feature_id as $value):
							$data = array(
									'type_id' => $insert,
									'feature_id' => $value,
									'created_at' => d_time(),
								);
							
							$add_features_id = $this->admin_m->insert($data,'pricing');
						endforeach;
					}


					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/packages'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/packages'));
				}	
		}
	}


	 public function number_check($val)
    {
        if (!preg_match('/^[0-9]+(\\.[0-9]+)?$/', $val)) {
            $this->form_validation->set_message('number_check', 'The {field} field must be a number or decimal.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

	

	/**
	  *** add features
	**/ 
	public function add_features(){
		is_test();
		$this->form_validation->set_rules('features', 'Feature name', 'required|trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/features'));
			}else{	
				$data = array(
					'features' => $this->input->post('features',TRUE),
					'created_at' => d_time(),
				);
				$id = $this->input->post('id',TRUE);
				if($id != 0):
					$insert = $this->admin_m->update($data,$id,'features');
				else:
					// $insert = $this->admin_m->insert($data,'features');
					$this->session->set_flashdata('error', 'You can only Update features name');
					redirect(base_url('admin/dashboard/features'));
				endif;

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/features'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/features'));
				}	
		}
	}



	public function social_sites()
	{
		$data = array();
		$data['page_title'] = "Social Sites";
        $data['page'] = "Dashboard";
        $data['data'] = false;
        $data['social_sites'] = $this->admin_m->select('social_sites');
		$data['main_content'] = $this->load->view('admin/dashboard/activities/social_names', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function edit_social($id)
	{
		$data = array();
		$data['page_title'] = "Social Sites";
        $data['page'] = "Dashboard";
        $data['data'] = $this->admin_m->single_select_by_id($id,'social_sites');
        $data['social_sites'] = $this->admin_m->select('social_sites');
		$data['main_content'] = $this->load->view('admin/dashboard/activities/social_names', $data, TRUE);
		$this->load->view('admin/index',$data);
	}
	
	/**
	  *** add setting
	**/ 
	public function add_social_sites(){
		is_test();
		$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('icon', 'Icon', 'required|trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/social_sites'));
			}else{
				$is_profile = $this->input->post('is_profile',TRUE);	
				$data = array(
					'name' => $this->input->post('name',TRUE),
					'type' => $this->input->post('type',TRUE),
					'is_profile' => isset($is_profile)?1:0,
					'icon' => $this->input->post('icon'),
					'created_at' => d_time(),
				);
				$id = $this->input->post('id');
				if($id==0){
					$insert = $this->admin_m->insert($data,'social_sites');
				}else{
					$insert = $this->admin_m->update($data,$id,'social_sites');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/social_sites'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/social_sites'));
				}	
		}
	}



	/**
	  ***  settings
	**/ 
	public function settings()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Settings";
		$data['page'] = "Settings";
		$data['setting']=$this->admin_m->single_select('setting');
		$data['languages']=$this->admin_m->select_with_status('languages');
		$data['currencies']=$this->admin_m->select('countries');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_settings/setting', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


	public function preferences()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Preferences";
		$data['page'] = "Settings";
		$data['settings']=$this->admin_m->single_select('setting');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_settings/preference', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


	/**
	  ***  Email Settings
	**/ 
	public function email_settings()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Email Settings";
		$data['page'] = "Settings";
		$data['settings']=$this->admin_m->single_select('setting');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_settings/email_setting', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


	public function payment_settings()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Payment Settings";
		$data['page'] = "Settings";
		$data['settings']=$this->admin_m->single_select('setting');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_settings/payment_settings', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function recaptcha_settings()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Recaptcha Settings";
		$data['page'] = "Settings";
		$data['settings']=$this->admin_m->single_select('setting');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_settings/recaptcha_settings', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  ***  Email Settings
	**/ 
	public function home_settings()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Home Settings";
    $data['c_page'] = "Settings";
    $data['data']=$this->admin_m->single_select('home_setting');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_settings/others_setting', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function add_home_setting(){
		is_test();
    	$id = $this->input->post('id');
		$this->form_validation->set_rules('facebook', 'Facebook', 'trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/home_settings'));
			}else{	
				$data = array(
					'facebook' => $this->input->post('facebook',TRUE),
					'whatsapp' => $this->input->post('whatsapp',TRUE),
					'instagram' => $this->input->post('instagram',TRUE),
					'linkedin' => $this->input->post('linkedin',TRUE),
				);
				
				if($id==0){
					$insert = $this->admin_m->insert($data,'home_setting');
				}else{
					$insert = $this->admin_m->update($data,$id,'home_setting');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/home_settings'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/home_settings'));
				}	
		}
	}



	/**
	  *** add setting
	**/ 
	public function add_settings(){
		  is_test();
			$this->form_validation->set_rules('site_name', 'Site Name', 'trim|xss_clean');
			$this->form_validation->set_rules('phone', 'Site Name', 'trim|xss_clean');
			$this->form_validation->set_rules('email', 'Email', 'trim|xss_clean|valid_email');
			$this->form_validation->set_rules('about_us', 'about_us', 'trim');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/settings'));
			}else{
				

				$check = $this->isValidTimezone($this->input->post('time_zone',TRUE));

				if($check!=1):
					$this->session->set_flashdata('error','Timezone is not correct! try with valid timezone');
					redirect(base_url('admin/dashboard/settings'));
				else:	
				$data = array(
					'site_name' => $this->input->post('site_name',TRUE),
					'phone' => $this->input->post('phone',TRUE),
					'language' => $this->input->post('language',TRUE),
					'time_zone' => $this->input->post('time_zone',TRUE),
					'currency' => $this->input->post('currency',TRUE),
					'title' => $this->input->post('title',TRUE),
					'description' => $this->input->post('description'),
					'analytics' => base64_encode($this->input->post('analytics')),
					'copyright' => $this->input->post('copyright',TRUE),
					'demo_username' => $this->input->post('demo_username',TRUE),
					'pricing_layout' => $this->input->post('pricing_layout',TRUE),
					'about_us' => $this->input->post('about_us'),
					'post_time' => d_time(),
				);
				$id = $this->input->post('id',TRUE);

				if($id != 0):
					$insert = $this->admin_m->update($data,$id,'setting');
				else:
					$insert = $this->admin_m->insert($data,'setting');
				endif;

				if($insert){
					$fav = $this->upload_logo($insert,'setting');
					$this->upload_favicon($insert);

					$this->session->unset_userdata('site_lang');
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/settings'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/settings'));
				}	
			endif;
		}
	}

	/**
	  ** check valid timezone
	**/
	public function isValidTimezone($timezone) {
	    return in_array($timezone, timezone_identifiers_list());
	} 

	/**
	  *** add setting
	**/ 
	public function add_email_settings(){
			is_test();
			$this->form_validation->set_rules('email', 'Admain Email', 'required|trim|xss_clean|valid_email');
			
			$setting = get_setting();
				if(isset($setting['email_type']) && $setting['email_type'] ==2){
					$this->form_validation->set_rules('smtp_port', 'SMTP PORT', 'trim|required|xss_clean|numeric');
					$this->form_validation->set_rules('smtp_host', 'SMTP HOST', 'trim|required|xss_clean');
					$this->form_validation->set_rules('password', 'SMTP Email Password', 'trim|required|xss_clean');
				}

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/email_settings'));
			}else{	
				$data = array(
					'email' => $this->input->post('email',TRUE),
					'smtp_host' => $this->input->post('smtp_host'),
					'smtp_port' => $this->input->post('smtp_port',TRUE),
					'password' => $this->input->post('password',TRUE),
					'email_type' => $this->input->post('email_type',TRUE),
					'reg_subject' => $this->input->post('reg_subject',TRUE),
					'paypal_subject' => $this->input->post('paypal_subject',TRUE),
					'recovery_subject' => $this->input->post('recovery_subject',TRUE),
					'post_time' => d_time(),
				);
				$id = $this->input->post('id',TRUE);

				if($id != 0):
					$insert = $this->admin_m->update($data,$id,'setting');
				else:
					$insert = $this->admin_m->insert($data,'setting');
				endif;

				if($insert){
					$this->session->set_flashdata('success',!empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/email_settings'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/email_settings'));
				}	
		}
	}


public function add_payment_settings(){
			is_test();
			
			$setting = get_setting();
			
			$this->form_validation->set_rules('is_live', 'Paypal Environment', 'trim|xss_clean');
			$this->form_validation->set_rules('paypal_email', 'Paypal Email', 'trim|required|xss_clean|valid_email');
			$this->form_validation->set_rules('public_key', 'Stripe Public Key', 'trim|xss_clean');
			$this->form_validation->set_rules('secret_key', 'Stripe Secret Key', 'trim|xss_clean');
			$this->form_validation->set_rules('key_id', 'Razorpay Key ID', 'trim|xss_clean');
			$this->form_validation->set_rules('razorpay_key', 'Razorpay Secret Key', 'trim|xss_clean');
	
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/payment_settings'));
			}else{	


				$mercado = array(
					'mercado_public_key' => $this->input->post('mercado_public_key',TRUE),
					'access_token' => $this->input->post('access_token',TRUE),
				);
				$paytm = array(
					'merchant_key' => $this->input->post('merchant_key',TRUE),
					'merchant_id' => $this->input->post('merchant_id',TRUE),
					'is_paytm_live' => $this->input->post('is_paytm_live',TRUE)!=1?0:1,
				);

				$flutterwave = array(
					'fw_public_key' => $this->input->post('fw_public_key',TRUE),
					'fw_secret_key' => $this->input->post('fw_secret_key',TRUE),
					'is_flutterwave_live' => $this->input->post('is_flutterwave_live',TRUE)!=1?0:1,
					'encryption_key' => $this->input->post('encryption_key',TRUE),
				);

				$data = array(
					'paypal_email' => $this->input->post('paypal_email',TRUE),
					'public_key' => $this->input->post('public_key',TRUE),
					'secret_key' => $this->input->post('secret_key',TRUE),
					'is_paypal_live' => $this->input->post('is_paypal_live',TRUE),
					'password' => $this->input->post('password',TRUE),
					'key_id' => $this->input->post('key_id',TRUE),
					'razorpay_key' => $this->input->post('razorpay_key',TRUE),
					'post_time' => d_time(),

					'is_paytm' => $this->input->post('is_paytm',TRUE)!=1?0:1,
					'is_mercado' => $this->input->post('is_mercado',TRUE)!=1?0:1,
					'mercado_config' => json_encode($mercado),
					'paytm_config' => json_encode($paytm),
					'is_flutterwave' => $this->input->post('is_flutterwave',TRUE)!=1?0:1,
					'flutterwave_config' => json_encode($flutterwave),


				);
				$id = $this->input->post('id',TRUE);

				if($id != 0):
					$insert = $this->admin_m->update($data,$id,'setting');
				else:
					$insert = $this->admin_m->insert($data,'setting');
				endif;

				if($insert){
					$this->session->set_flashdata('success',!empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/payment_settings'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/payment_settings'));
				}	
		}
	}

/**
   ** upload favicon
 **/ 
	public function upload_favicon($id)
	{

		if(!empty($_FILES['favicon']['name'])){

			$dir = "uploads/site_images/";
			$name = $_FILES['favicon']['name'];
			list($txt, $ext) = explode(".", $name);
			$image_name = md5(time()).".".$ext;
			$tmp = $_FILES['favicon']['tmp_name'];
		   if(move_uploaded_file($tmp, $dir.$image_name)){
			    $url = $dir.$image_name;
			    $data = array('favicon' => $url);
				$this->admin_m->update($data,$id,'setting');	
				return true;
		   }else{
		      echo "image uploading failed";
		   }
		}

	}


/**
   ** site service image uploader
 **/ 
	public function upload_service_images($id=0,$table)
	{
		
		if(!empty($_FILES['images']['name'])){
			$directory = 'uploads/site_services/';
			$dir = $directory;
			$name = $_FILES['images']['name'];
			list($txt, $ext) = explode(".", $name);
			$image_name = md5(time()).".".$ext;
			$tmp = $_FILES['images']['tmp_name'];
		   if(move_uploaded_file($tmp, $dir.$image_name)){
			    $url = $dir.$image_name;
			    $data = array('images' => $url);
				$this->admin_m->update($data,$id,$table);	
		   }else{
		      echo "image uploading failed";
		   }
		}

	}



/**
   ** site service image uploader
 **/ 
	public function upload_logo($id=0,$table)
	{
		
		if(!empty($_FILES['images']['name'])){
			$directory = 'uploads/site_images/';
			$dir = $directory;
			$name = $_FILES['images']['name'];
			list($txt, $ext) = explode(".", $name);
			$image_name = md5(time()).".".$ext;
			$tmp = $_FILES['images']['tmp_name'];
		   if(move_uploaded_file($tmp, $dir.$image_name)){
			    $url = $dir.$image_name;
			    $data = array('logo' => $url);
				$this->admin_m->update($data,$id,$table);	
		   }else{
		      echo "image uploading failed";
		   }
		}

	}

	


	/**
	  ** registration and email verify status changer
	**/

	public function setting_status($type,$value)
	{
		if($value==0){
			$data_value = 1;
		}else{
			$data_value = 0;
		}

		$data = array(
			$type => $data_value,
		);

		$this->admin_m->update($data,1,'setting');
		echo json_encode(array('st' => 1,'value'=>$data_value));
	}


	public function features_toggle($id,$value)
	{
		if($value==0){
			$data_value = 1;
		}else{
			$data_value = 0;
		}

		$data = array(
			'status' => $data_value,
		);

		$this->admin_m->update_feature($data,$id,'users_features');
		echo json_encode(array('st' => 1,'value'=>$data_value));
	}


	/**
	  ** change status for all section (common function)
	**/

	public function change_content_status($id,$status,$table)
	{
		if($status==1){
			$data_status =0;
		}else{
			$data_status =1;
		}
		$data = array(
			'status' => $data_status,
		);

		$this->admin_m->update($data,$id,$table);
		echo json_encode(array('st' => 1));
	}



/**
  *** user profile 
**/  	
	public function profile()
	{
		$data = array();
		$data['page_title'] = "Profile";
		$data['page'] = "vCard";
    $data['u_info']=$this->admin_m->get_user_info();
    $data['countries']=$this->admin_m->select('countries');
    $data['my_cards']=$this->admin_m->get_my_all_vcard(auth('id'));
    if(auth('user_type')==1):
			$data['main_content'] = $this->load->view('admin/dashboard/admin_profile', $data, TRUE);
    else:
			$data['main_content'] = $this->load->view('admin/dashboard/profile', $data, TRUE);
		endif;
		$this->load->view('admin/index',$data);
	}	

	public function edit_profile()
	{
		$data = array();
		$data['page_title'] = "Profile";
    $data['u_info']=$this->admin_m->get_user_info();
    $data['countries']=$this->admin_m->select('countries');
    $data['my_cards']=$this->admin_m->get_my_all_vcard(auth('id'));
		$data['main_content'] = $this->load->view('admin/dashboard/edit_profile', $data, TRUE);
		$this->load->view('admin/index',$data);
	}	

	public function addons()
	{
		$data = array();
		$data['page_title'] = "Addons";
    $data['addons']=$this->admin_m->select('addons');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/addons', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

/**
  *** update profile action
**/ 

	public function update_profile()
	{
		is_test();
		$info = user_info();
		if($info->username == $this->input->post('username')){
			$this->form_validation->set_rules('username', 'Username', 'trim|xss_clean|callback_english_check');
		}else{
			$this->form_validation->set_rules('username', 'username', 'trim|xss_clean|required|callback_english_check|is_unique[users.username]',array('is_unique'=>'Sorry This username already exits'));
		}

		if($info->email == $this->input->post('email')){
			$this->form_validation->set_rules('email', 'Email', 'trim|xss_clean|valid_email');
		}else{
			$this->form_validation->set_rules('email', 'Email', 'trim|xss_clean|required|valid_email|is_unique[users.email]',array('is_unique'=>'Sorry This email already exits'));
		}
		$this->form_validation->set_rules('name', 'name', 'trim|xss_clean');
		$this->form_validation->set_rules('gender', 'Gender', 'trim|xss_clean');
		$this->form_validation->set_rules('designation', 'Designation', 'trim|xss_clean');
		$this->form_validation->set_rules('website', 'Website', 'trim|xss_clean');
		$this->form_validation->set_rules('address', 'Address', 'trim|xss_clean');
		$this->form_validation->set_rules('dial_code', 'Dial Code', 'trim|xss_clean|required');
		$this->form_validation->set_rules('country', 'Country', 'trim|xss_clean');
		$this->form_validation->set_rules('full_name', 'Display Name', 'trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			$this->edit_profile();
			}else{	

				$country_code = $this->input->post('country',true);
				$country_info = $this->admin_m->single_select_by_id($country_code,'countries');
				if($info->country==$country_code){
					if(!empty($this->input->post('dial_code',TRUE)) && $info->dial_code == $this->input->post('dial_code',TRUE)):
							$dial_code = $info->dial_code;
						else:
							$dial_code = $this->input->post('dial_code',TRUE);
						endif;
				}else{
					$dial_code = $country_info['dial_code']; 
						
				}

				$data = array(
					'username' => str_slug($this->input->post('username',TRUE)),
					'name' => $this->input->post('name',TRUE),
					'email' => $this->input->post('email',TRUE),
					'gender' => $this->input->post('gender',TRUE),
					'designation' => $this->input->post('designation',TRUE),
					'website' => $this->input->post('website',TRUE),
					'address' => $this->input->post('address',TRUE),
					'phone' => $this->input->post('phone',TRUE),
					'whatsapp' => $this->input->post('whatsapp',TRUE),
					'dial_code' => $dial_code,
					'country' => $this->input->post('country',TRUE),
					'full_name' => $this->input->post('full_name',TRUE),
				);
				$insert = $this->admin_m->update_profile($data,'users');
				if($insert){
					if($info->user_type == 1){
						$this->admin_m->update(array('email' =>$this->input->post('email',TRUE)),1,'setting');
					}
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/profile'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/edit_profile'));
				}	
		}
	}

	public function english_check($string){
		if (preg_match('/[^A-Za-z0-9]/', $string))  {
		    //string contains only letters from the English alphabet
		     $this->form_validation->set_message('english_check', 'The {field} field contains only letters from the English alphabet.');
            return FALSE;
		}else{
			return true;
		}
	}

/**
    *** Change password 
 **/   
	public function change_pass()
	{	
		is_test();
		$this->form_validation->set_rules('old_pass', 'Old Password', 'trim|required|min_length[3]|xss_clean');		
		$this->form_validation->set_rules('new_pass', 'New Password', 'trim|required|min_length[3]|xss_clean');
		$this->form_validation->set_rules('c_pass', 'Confirm Password', 'trim|required|min_length[3]|xss_clean|matches[new_pass]');
		if ($this->form_validation->run() == FALSE) {
			$msg = '<div class="alert alert-danger alert-dismissible">
					  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					  '.validation_errors().'
					</div>';
			echo json_encode(array('st' => 0, 'msg'=> $msg));
		}else{	
			$pass = $this->input->post('old_pass');

			$check = $this->admin_m->check_pass($pass);

			if($check){
				$data = array(
					'password' => md5($this->input->post('new_pass')),
				);	
				$insert = $this->admin_m->update($data,auth('id'),'users');
				if($insert){
					$msg = '<div class="alert alert-success alert-dismissible">
					  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					  <strong>Thank You ! </strong> Your password change successfully <i class="fa fa-smile-o"></i>
					</div>';
					
					echo json_encode(array('st' => 1, 'msg'=> $msg));
					
				}else{
					$msg = '<div class="alert alert-danger alert-dismissible">
					  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					  <strong>Sorry </strong> Try again later
					</div>';
					
					echo json_encode(array('st' => 2, 'msg'=> $msg));
				}
			}else{
				$msg = '<div class="alert alert-danger alert-dismissible">
					  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					  <strong>Sorry </strong> Your Old password was wrong
					</div>';
					
					echo json_encode(array('st' => 3, 'msg'=> $msg));
			}	

		}
	}


public function subscription()
{
	$data = array();
	$data['page_title'] = "Subscription";
    $data['page'] = "Dashboard";
    $data['all_features'] = $this->common_m->select_with_status('features');
    $data['all_packages'] = $this->admin_m->get_subscripe_pricing();
    $data['active_package']=$this->admin_m->get_active_package();
	$data['main_content'] = $this->load->view('admin/dashboard/subscription', $data, TRUE);
	$this->load->view('admin/index',$data);
}

public function transactions()
{
	$data = array();
	$data['page_title'] = "Transactions";
    $data['page'] = "Admin Activities";
    $data['transactions']=$this->admin_m->select_desc('payment_info');
	$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/transactions', $data, TRUE);
	$this->load->view('admin/index',$data);
}


public function offline_payments()
{
	$data = array();
	$data['page_title'] = "Offline Payments";
    $data['page'] = "Admin Activities";
    $data['offline']=$this->admin_m->select_desc('offline_payment');
	$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/offline_payments', $data, TRUE);
	$this->load->view('admin/index',$data);
}

public function languages()
{
	$data = array();
	$data['page_title'] = "Language";
    $data['page'] = "Languages";
    $data['data']=FALSE;
    $data['languages']=$this->admin_m->select('languages');
	$data['main_content'] = $this->load->view('admin/dashboard/language/home', $data, TRUE);
	$this->load->view('admin/index',$data);
}

public function edit_languages($id)
{
	$data = array();
	$data['page_title'] = "Language";
    $data['page'] = "Languages";
    $data['data']=$this->admin_m->single_select_by_id($id,'languages');
    $data['languages']=$this->admin_m->select('languages');
	$data['main_content'] = $this->load->view('admin/dashboard/language/home', $data, TRUE);
	$this->load->view('admin/index',$data);
}

public function fontend_languages()
{
	$data = array();
	$data['page_title'] = "Fontend Language";
    $data['page'] = "Languages";
    $data['data']=FALSE;
    $data['fontend_languages']=$this->admin_m->get_language_data('home',$status='*');
    $data['label_languages']=$this->admin_m->get_language_data('label',$status=1);
	$data['main_content'] = $this->load->view('admin/dashboard/language/fontend_language', $data, TRUE);
	$this->load->view('admin/index',$data);
}
public function dashboard_languages()
	{

		//pagination
		$config = [];
		$this->load->library('pagination');
		$per_page = isset($_GET['limit'])?$_GET['limit']:20;

		$page = $this->input->get('page');
		if (empty($page)) {
			$page = 0;
		}

		if ($page != 0) {
			$page = $page-1;
		}
		$offset = ceil($page * $per_page);

		$total = $this->admin_m->get_all_language_data(0,0,$is_total=1);
		$config['base_url'] = base_url('admin/dashboard/dashboard_languages');
		$config['total_rows'] = $total;
		$config['per_page'] =  $per_page;
		$this->pagination->initialize($config);




		$data = array();
		$data['page_title'] = "Dashboard Language";
		$data['page'] = "Languages";
		$data['data']=FALSE;
		$data['admin_languages']=$this->admin_m->get_all_language_data($per_page,$offset,0);
		$data['languages']=$this->admin_m->get_language($status=1);
		$data['main_content'] = $this->load->view('admin/dashboard/language/dashboard_language', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

public function add_value($type=1)
{	
	if($type==1):
			$data = array(
				'511' =>"Nombre de fuente de Google",
				'510' =>"JS personalizado",
				'509' =>"CSS personalizado",
				'508' =>"Extras",
				'507' =>"Cambiar Dominio",
			);
			foreach ($data as $key => $value) {
				$d = array(
					'spainsh' => $value,
				);
			  $this->common_m->update($d,$key,'language_data');
			}
			echo "done";
			exit();
		else:
				$data = [];
				$lan = $this->common_m->select_desc('language_data');
				foreach ($lan as $key => $value) {
				   //echo  "'".$value['id']."' =>" , '"'.$value['english'].'",'.'<br>';
				  echo  "('{$value['keyword']}','{$value['details']}','{$value['english']}'),"."<br>";
				    
				}
			exit();
		endif;
	
}

	
public function add_keyword(){
	$this->form_validation->set_rules('keyword', 'Keyword', 'required|trim|xss_clean|is_unique[language_data.keyword]');
	$this->form_validation->set_rules('value', 'Value', 'required|trim|xss_clean');
	$this->form_validation->set_rules('types', 'Types', 'required|trim|xss_clean');

	if ($this->form_validation->run() == FALSE) {
		$this->session->set_flashdata('error', validation_errors());
		redirect($_SERVER['HTTP_REFERER']);
	}else{	
		$data = array(
			'keyword' => $this->input->post('keyword',TRUE),
			'english' => $this->input->post('value',TRUE),
			'details' => $this->input->post('value',TRUE),
			'type' => $this->input->post('types',TRUE),
		);
		$insert = $this->admin_m->insert($data,'language_data');

		if($insert){
			$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
			redirect($_SERVER['HTTP_REFERER']);
		}else{
			$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
			redirect($_SERVER['HTTP_REFERER']);
		}	
	}
}

public function add_languages(){
	is_test();
	$id = $this->input->post('id');
	$this->form_validation->set_rules('direction', 'Text Direction', 'required|trim|xss_clean');
	if($id==0):
		$this->form_validation->set_rules('lang_name', 'Language Name', 'required|trim|xss_clean|is_unique[languages.lang_name]',array('is_unique'=>'Sorry This language is already exits'));

		$this->form_validation->set_rules('slug', 'Language Slug', 'required|trim|alpha|xss_clean|callback_english_check|is_unique[languages.slug]',array('is_unique'=>'Sorry This language slug already exits!'));
	else:
		$this->form_validation->set_rules('lang_name', 'Language Name', 'required|trim|xss_clean');
		$this->form_validation->set_rules('slug', 'Language Slug', 'required|trim|xss_clean');
	endif;

	if ($this->form_validation->run() == FALSE) {
		$this->session->set_flashdata('error', validation_errors());
		redirect(base_url('admin/dashboard/languages'));
		}else{	
			$slug = str_slug($this->input->post('slug',TRUE));
			$data = array(
				'lang_name' => $this->input->post('lang_name',TRUE),
				'slug' => $slug,
				'direction' => $this->input->post('direction',TRUE),
				'created_at' => d_time(),
			);
			$id = $this->input->post('id');
			if($id==0){
				$this->create_folder($slug);
				$insert = $this->admin_m->insert($data,'languages');
			}else{
				$insert = $this->admin_m->update($data,$id,'languages');
			}

			if($insert){
				$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
				redirect(base_url('admin/dashboard/languages'));
			}else{
				$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
				redirect(base_url('admin/dashboard/languages'));
			}	
	}
}

public function create_folder($lang_name){
	$data = array();
	$directory = FCPATH . 'application/language/';

	if (!file_exists($directory.'/'.$lang_name)) {

		$st_1 = $this->db->query('ALTER TABLE language_data ADD ('.$lang_name.' TEXT NOT NULL)') or print json_encode(array('st'=>0,'msg'=>$this->db->error()));
		if($st_1){
			$create =  mkdir($directory . '/' . $lang_name, 0777);

			if($create){
				$write =	$this->write($lang_name);

				if($write==TRUE){
					return true;
				}else{
					return false;
				}

			}
		}


	} else {

		$this->session->set_flashdata('success', 'The folder ' . $lang_name . ' already Exists');
		return false;
	}

}

function write($lang_name) {

		// Config path
	$name = $lang_name;
	$template_path 	= FCPATH . 'application/hooks/lang.php';
	$output_path 	= FCPATH . 'application/language/'.$lang_name.'/content_lang.php';

		// Open the file
	$database_file = file_get_contents($template_path);
	$new_data  = str_replace("%my%",$name,$database_file);
		// Write the new database.php file
	$handle = fopen($output_path,'w+');

		// Chmod the file, in case the user forgot
	@chmod($output_path,0777);

		// Verify file permissions
	if(is_writable($output_path)) {

			// Write the file
		if(fwrite($handle,$new_data)) {
			return true;
		} else {
			return false;
		}

	} else {
		return false;
	}
}



// check expired users	
public function get_expired_users()
{
	$all_users = $this->admin_m->get_all_users(d_time());
	$total = $this->admin_m->get_total_expired_users(d_time());
	if($total > 0){
		foreach ($all_users as $users) {
			$data = array('is_expired' =>1);
			$this->admin_m->update($data,$users['id'],'users');
		}
	}
	
}


// check expired users	
public function check_expired_users()
{
	$all_users = $this->admin_m->get_all_active_users();
	if(count($all_users) > 0){
		foreach ($all_users as $users) {
			 $day_left = day_left(d_time(),$users['end_date']);
			if($day_left['date'] == 4):
				$this->email_m->expire_reminder_mail($users['username'],$day_left['day_left']);

			elseif($day_left['date'] == 3):
				$this->email_m->expire_reminder_mail($users['username'],$day_left['day_left']);

			elseif($day_left['date'] == 1):
				$this->email_m->expire_reminder_mail($users['username'],$day_left['day_left']);

			elseif($day_left['date'] < 0):
				$data = array('is_expired' =>1);
				$update = $this->admin_m->update($data,$users['id'],'users');
				if($update){
					$this->email_m->account_expire_mail($users['username']);
				}
			endif;
		}
	}
	
}

public function add_languages_value($lang_name){
	$this->form_validation->set_rules('lang_name', 'Name', 'trim|xss_clean');
	if ($this->form_validation->run() == FALSE) {
		$this->session->set_flashdata('error', validation_errors());
		redirect(base_url('admin/dashboard/languages'));
		}else{	
			ini_set('memory_limit', '-1');
			$i=0;
			$keyword = $this->input->post('keyword',TRUE);
			foreach ($_POST[$lang_name] as $key => $value) {
				$data = array(
					$lang_name => ucfirst($value),
					'details' => ucfirst($_POST['details'][$i]),
				);
				  $insert = $this->admin_m->update_language($data,$keyword[$i],'language_data');
				$i++;
			}
		
			if($insert){
				$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
				redirect($_SERVER['HTTP_REFERER']);
			}else{
				$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
				redirect($_SERVER['HTTP_REFERER']);
			}	
	}
}


/**
  *** FAQS
**/  	
	public function faq()
	{
		$data = array();
		$data['page_title'] = "FAQ";
		$data['page'] = "Dashboard";
		$data['data'] = false;
        $data['faq']=$this->admin_m->select('faq');
		$data['main_content'] = $this->load->view('admin/dashboard/faq', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function edit_faq($id)
	{
		$data = array();
		$data['page_title'] = "FAQ";
		$data['page'] = "Dashboard";
		$data['data'] = $this->admin_m->single_select_by_id($id,'faq');
        $data['faq']=$this->admin_m->select('faq');
		$data['main_content'] = $this->load->view('admin/dashboard/faq', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function add_recaptcha(){
		is_test();
		$this->form_validation->set_rules('g_site_key', 'Site Key', 'trim|required|xss_clean|required');
		$this->form_validation->set_rules('g_secret_key', 'Secret Key', 'required|trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/recaptcha_settings'));
			}else{	
				$data = array(
					'g_site_key' => $this->input->post('g_site_key',TRUE),
					'g_secret_key' => $this->input->post('g_secret_key',TRUE),
				);
				$id = $this->input->post('id');
				if($id==0){
					$insert = $this->admin_m->insert($data,'setting');
				}else{
					$insert = $this->admin_m->update($data,$id,'setting');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/recaptcha_settings'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/recaptcha_settings'));
				}	
		}
	}




	/**
	  *** add faq
	**/ 
	public function add_faq(){
		is_test();
		$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
		$this->form_validation->set_rules('details', 'Details', 'required|trim');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/faq'));
			}else{	
				$data = array(
					'title' => $this->input->post('title',TRUE),
					'details' => $this->input->post('details',TRUE),
					'created_at' => d_time(),
				);
				$id = $this->input->post('id');
				if($id==0){
					$insert = $this->admin_m->insert($data,'faq');
				}else{
					$insert = $this->admin_m->update($data,$id,'faq');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/faq'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/faq'));
				}	
		}
	}


 	



/**
   ** site service image uploader
 **/ 
	public function add_home_banner($type)
	{
		is_test();
		$setting = get_setting();
		if($type=='home'){
			$type_name = 'home_banner';
		}else if($type == 'home_small'){
			$type_name = 'home_small_image';
		}else if($type=="faq_banner"){
			$type_name = 'faq_banner';
		}
		
		if(!empty($_FILES['images']['name'])){
			$directory = 'uploads/site_images/';
			$dir = $directory;
			$name = $_FILES['images']['name'];
			list($txt, $ext) = explode(".", $name);
			$image_name = md5(time()).".".$ext;
			$tmp = $_FILES['images']['tmp_name'];
		   if(move_uploaded_file($tmp, $dir.$image_name)){
			    $url = $dir.$image_name;
			    $data = array($type_name => $url);
				$this->admin_m->update($data,$setting['id'],'setting');	
				redirect($_SERVER['HTTP_REFERER']);
		   }else{
		      echo "image uploading failed";
		   }
		}

	}


	/**
	  ** user Team
	**/

	public function team()
	{
		$data = array();
		$data['page_title'] = "Team Members";
        $data['page'] = "Dashboard";
        $data['data'] = false;
        $data['team'] = $this->admin_m->select_all_by_user('home_team');
		$data['main_content'] = $this->load->view('admin/dashboard/meet_team', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function edit_team($id)
	{
		$data = array();
		$data['page_title'] = "Reviews";
        $data['page'] = "Dashboard";
        $data['data'] =$this->admin_m->single_select_by_id($id,'home_team');
        $data['team'] = $this->admin_m->select_all_by_user('home_team');
		$data['main_content'] = $this->load->view('admin/dashboard/meet_team', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	/**
	  *** add_reviews
	**/ 
	public function add_team(){
		is_test();
		$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('designation', 'Designation', 'trim|required|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			$this->team();
		}else{	
			$data = array(
				'name' => $this->input->post('name',true),
				'user_id' => auth('id'),
				'designation' => $this->input->post('designation',true),
				'created_at' => d_time(),
			);
			$id = $this->input->post('id');
			if($id==0){
				$insert = $this->admin_m->insert($data,'home_team');
			}else{
				$insert = $this->admin_m->update($data,$id,'home_team');
			}

			if($insert){
				$this->upload_images($insert,'home_team');
				$this->session->set_flashdata('success', 'Save change Successfull');
				redirect(base_url('admin/dashboard/team'));
			}else{
				$this->session->set_flashdata('error', 'Somethings were wrong');
				redirect(base_url('admin/dashboard/team'));
			}	
		}
	}

/**
   ** default Image Upload for services and reviews
 **/ 
	public function upload_images($id=0,$table)
	{
		
		if(!empty($_FILES['images']['name'])){
			if($table=='services'){
				$directory = 'uploads/services/';
			}elseif($table=='reviews'){
				$directory = 'uploads/reviews/';
			}else{
				$directory = 'uploads/';
			}
			$dir = $directory;
			$name = $_FILES['images']['name'];
			list($txt, $ext) = explode(".", $name);
			$image_name = md5(time()).".".$ext;
			$tmp = $_FILES['images']['tmp_name'];
		   if(move_uploaded_file($tmp, $dir.$image_name)){
			    $url = $dir.$image_name;
			    $data = array('images' => $url);
				$this->admin_m->update($data,$id,$table);	
		   }else{
		      echo "image uploading failed";
		   }
		}

	}

/**
  *** Backup database by admin
**/ 
	public function db_backup()
    {
    	is_test();
     $this->load->dbutil();
		$prefs = array(     
		    'format'      => '.sql',             
		    'filename'    => 'my_db_backup.sql'
		    );
		$backup =$this->dbutil->backup($prefs);
		$project = explode('/', $_SERVER['REQUEST_URI'])[1];
		$db_name =$project.'-'. date("d-m-Y-H-i-s") .'.sql';
		$save = 'database/'.$db_name;
		$this->load->helper('file');
		write_file($save, $backup); 
		$this->session->set_flashdata('success', 'Database backup Successfully');
		redirect($this->agent->referrer());
    }

	public function item_delete($id,$table){
		is_test();
		$del=$this->admin_m->delete($id,$table);
		if($del){
			$this->session->set_flashdata('success', 'Item Deleted');
			redirect($_SERVER['HTTP_REFERER']);
		}else{
			$this->session->set_flashdata('error', 'Somthing worng. Error!!');
			redirect($_SERVER['HTTP_REFERER']);
		}
	}


	public function delete_language($id){
		is_test();
		$ln =  $this->admin_m->single_select_by_id($id,'languages');
		$del=$this->admin_m->delete($id,'languages');
		if(!empty($ln['slug'])):
			$this->db->query("ALTER TABLE language_data DROP COLUMN {$ln['slug']}");
		endif;

		if($del){
			$this->session->set_flashdata('success', 'Item Deleted');
			redirect($_SERVER['HTTP_REFERER']);
		}else{
			$this->session->set_flashdata('error', 'Somthing worng. Error!!');
			redirect($_SERVER['HTTP_REFERER']);
		}
	}

	public function terms(){
        $data = array();
        $data['page_title'] = "Terms & Conditions";
        $data['page'] = "Pages";
        $data['data']=$this->admin_m->single_select('terms');
        $data['main_content'] = $this->load->view('admin/dashboard/admin_activities/terms', $data, TRUE);
        $this->load->view('admin/index', $data);
    }

    /**
	  *** add terms
	**/ 
	public function add_terms(){
		is_test();
		$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
		$this->form_validation->set_rules('details', 'Details', 'required|trim');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/terms'));
			}else{	
				$data = array(
					'title' => $this->input->post('title',TRUE),
					'details' => $this->input->post('details'),
					'status' => $this->input->post('status',TRUE),
				);
				$id = $this->input->post('id');
				if($id==0){
					$insert = $this->admin_m->insert($data,'terms');
				}else{
					$insert = $this->admin_m->update($data,$id,'terms');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/terms'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/terms'));
				}	
		}
	}

		public function test_mail(){
        $data = array();
        $send = $this->email_m->test_mail();
        echo "<pre>";print_r($send);exit();
    }

    public function privacy(){
        $data = array();
        $data['page_title'] = "Cookies & Privacy";
        $data['page'] = "Pages";
        $data['data']=$this->admin_m->single_select('privacy');
        $data['main_content'] = $this->load->view('admin/dashboard/admin_activities/privacy', $data, TRUE);
        $this->load->view('admin/index', $data);
    }

    /**
	  *** add terms
	**/ 
	public function add_privacy(){
		is_test();
		$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
		$this->form_validation->set_rules('details', 'Details', 'required|trim');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/privacy'));
			}else{	
				$data = array(
					'title' => $this->input->post('title',TRUE),
					'details' => $this->input->post('details',TRUE),
					'status' => $this->input->post('status',TRUE),
				);
				$id = $this->input->post('id');
				if($id==0){
					$insert = $this->admin_m->insert($data,'privacy');
				}else{
					$insert = $this->admin_m->update($data,$id,'privacy');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/privacy'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/privacy'));
				}	
		}
	}

	public function pages(){
        $data = array();
        $data['page_title'] = "Create Pages";
        $data['page'] = "Pages";
        $data['data']=false;
        $data['pages']=$this->admin_m->select('pages');
        $data['main_content'] = $this->load->view('admin/dashboard/admin_activities/create_pages', $data, TRUE);
        $this->load->view('admin/index', $data);
    }

    public function edit_page($id){
        $data = array();
        $data['page_title'] = "Create Pages";
        $data['page'] = "Pages";
        $data['data']=$this->admin_m->single_select_by_id($id,'pages');
        $data['pages']=$this->admin_m->select('pages');
        $data['main_content'] = $this->load->view('admin/dashboard/admin_activities/create_pages', $data, TRUE);
        $this->load->view('admin/index', $data);
    }

    public function create_page(){
    	is_test();
    	$id = $this->input->post('id');
		$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
		if($id==0):
		$this->form_validation->set_rules('slug', 'Slug', 'trim|required|xss_clean|is_unique[pages.slug]');
		else:
			$this->form_validation->set_rules('slug', 'Slug', 'trim|required|xss_clean');
		endif;
		$this->form_validation->set_rules('details', 'Details', 'required');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/pages'));
			}else{	
				$data = array(
					'title' => $this->input->post('title',TRUE),
					'slug' => str_slug($this->input->post('slug',TRUE)),
					'details' => $this->input->post('details'),
					'status' => $this->input->post('status',TRUE),
					'created_at' => d_time(),
				);
				// echo "<pre>";print_r($data);exit();
				if($id==0){
					$insert = $this->admin_m->insert($data,'pages');
				}else{
					$insert = $this->admin_m->update($data,$id,'pages');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/pages'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/pages'));
				}	
		}
	}


	/**
	  *** add new user by admin
	**/ 
	public function add_user()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Add User";
        $data['page'] = "Users";
        $data['features'] = $this->admin_m->select_with_status('features_type');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/add_user', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


/**
  *** Add user 
**/ 
	public function new_user(){
		is_test();
		check_valid_auth();
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|is_unique[users.username]',array(
            'is_unique'=> 'This '.$this->input->post('username').' already exists.'
        ));		
		
		$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|is_unique[users.email]',array(
            'is_unique'=> 'This '.$this->input->post('email').' already exists.'
        ));	

		$this->form_validation->set_rules('package', 'Package', 'trim|required');

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			$this->add_user();
		}else{	

			$settings = get_setting();
			$length = 6;
			$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);

			if($this->input->post('is_password')==1):
				$password = $this->input->post('password');
			else:
				$password = $randomString;
			endif;

			$package = $this->admin_m->get_price_type_by_id($this->input->post('package'));
			$data = array(
				'username' => str_slug($this->input->post('username')),
				'email' => $this->input->post('email'),
				'account_type' => $this->input->post('package'),
				'password' => md5($password),
				'is_active' => 1,
				'is_verify' => 1,
				'is_payment' => 1,
				'verify_time'=>d_time(),
				'start_date'=>d_time(),
				'end_date'=>add_year($package['type']),
				'post_time' => d_time(),
			);
			$insert = $this->admin_m->insert($data,'users');
			if($insert){
				
				$this->insert_features($insert);
				
				if(isset($_POST['is_mail']) && $_POST['is_mail']==1):
					$this->email_m->send_new_user_by_admin_mail($data,$package,$password);
				endif;
				$this->session->set_flashdata('success', 'New User Added Successfull');
				redirect(base_url('admin/dashboard/total_user'));
			}else{
				$this->session->set_flashdata('error', 'Somethings were wrong');
				redirect(base_url('admin/dashboard/add_user'));
			}
		}
	}

	public function insert_features($user_id){
		$fetaures = $this->admin_m->select('features');
		foreach ($fetaures as $key => $row) {
			$data =  array(
				'feature_id' => $row['id'],
				'user_id' => $user_id,
				'status' => 1
			);
			$this->admin_m->insert($data,'users_features');
		}
		return true;
	}


	public function reset_password($id){
		$data =  array(
				'password' => md5(1234),
			);
		$update = $this->admin_m->update($data,$id,'users');
		if($update){
			echo json_encode(array('st'=>1));
		}else{
			echo json_encode(array('st'=>0));
		}
	}


	/**
	  *** add new user by admin
	**/ 
	public function ads()
	{
		check_valid_auth();
		$data = array();
		$data['page_title'] = "Ads";
        $data['page'] = "ADS";
        $data['images'] = $this->admin_m->single_select_by_user(auth('id'),'ads_images');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/ads', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


    public function upload_ads($type_id)
	{
		is_test();
	    $data = array();
	    $id = $this->input->post('id');
	    if (!empty($_FILES['file']['name'])) {
	        $filesCount = count($_FILES['file']['name']);
	        for ($i = 0; $i < $filesCount; $i++) {
	              $_FILES['uploadFile']['name'] = str_replace(",","_",$_FILES['file']['name'][$i]);
	              $_FILES['uploadFile']['type'] = $_FILES['file']['type'][$i];
	              $_FILES['uploadFile']['tmp_name'] = $_FILES['file']['tmp_name'][$i];
	              $_FILES['uploadFile']['error'] = $_FILES['file']['error'][$i];
	              $_FILES['uploadFile']['size'] = $_FILES['file']['size'][$i];

	              //Directory where files will be uploaded
	              $uploadPath = 'uploads/site_images/';


	              $config['upload_path'] = $uploadPath;
	              // Specifying the file formats that are supported.
	              $config['allowed_types'] = 'jpg|jpeg|png|gif';
	              $config['overwrite'] = TRUE;
				  			$config['encrypt_name'] = TRUE;
	              $this->load->library('upload', $config);
	              $this->upload->initialize($config);
	              // resize library
	              $this->load->library('image_lib');

	              if ($this->upload->do_upload('uploadFile')) {
	                  $fileData = $this->upload->data();
	                  $uploadData[$i]['file_name'] = $fileData['file_name'];
	                  // resize
			            $config = array(
						    'source_image'      => $fileData['full_path'], 
						    'new_image'         => $uploadPath.'/thumb', //path to
						    'maintain_ratio'    => true,
						    'width'             => 250,
						    'height'            => 150
						);
						    $this->image_lib->initialize($config);
						    $this->image_lib->resize();
						// resize
						    
	              }else{
	              	$error = array('error' => $this->upload->display_errors());
                    foreach ($error as $value) {
                    	$msg = $value;
                    }
                    echo json_encode(array('st'=>0,'msg'=>$msg,));
                    exit();
	              }

	        }
	          
	        if (!empty($uploadData)) {
	          $list=array();
	          	foreach ($uploadData as $value) {
		          	$data = array(
		          		'ads_'.$type_id => $uploadPath.$value['file_name'],
		          		'ads_thumb_'.$type_id => $uploadPath.'thumb/'.$value['file_name'],
		          		'user_id' => auth('id')
		          	);

		          	//insert image into database query
		          	if($id!=0):
			          	$this->admin_m->update($data,$id,'ads_images');
			        else:
			        	$this->admin_m->insert($data,'ads_images');
			        endif;
	          	}
	    		echo json_encode(array('st'=>1,'img'=>$uploadPath.'thumb/'.$value['file_name']));
		  	}else{
		    	$msg = 'Please insert an image';
		    	echo json_encode(array('st'=>0,'msg'=>$msg,));
		    }

	    }
	}


	public function delete_ads($id,$type_id)
	{
		is_test();
		$img = single_select_by_id($id,'ads_images');
		$data = array(
			'ads_'.$type_id => "",
			'ads_thumb_'.$type_id => "",
		);
		$up= $this->admin_m->update($data,$id,"ads_images");
		if($up):
			delete_image_from_server($img['ads_'.$type_id]);
			delete_image_from_server($img['ads_thumb_'.$type_id]);
			$this->session->set_flashdata('success', 'Item Deleted Successfully!');
			redirect(base_url('admin/dashboard/ads'));
		endif;
	}

	public function optimize()
	{
	    $path = $this->config->item('cache_path');

	    $cache_path = ($path == '') ? APPPATH.'cache/' : $path;

	    $handle = opendir($cache_path);
	    while (($file = readdir($handle))!== FALSE) 
	    {
	        //Leave the directory protection alone
	        if ($file != '.htaccess' && $file != 'index.html')
	        {
	           @unlink($cache_path.'/'.$file);
	        }
	    }

	    closedir($handle);  
	    redirect($_SERVER['HTTP_REFERER']);     
	}


	public function seo_settings()
	{
		
		$data = array();
		$data['page_title'] = "Seo Settings";
		$data['page'] = "Settings";
		$data['settings'] = $this->admin_m->single_select('setting');
		$data['main_content'] = $this->load->view('admin/dashboard/admin_settings/seo_settings', $data, TRUE);
		$this->load->view('admin/index',$data);
	}


	
	public function add_seo_settings(){
		is_test();
    	$id = $this->input->post('id');
		$this->form_validation->set_rules('title', 'Title', 'trim|xss_clean|required');
		$this->form_validation->set_rules('description', 'Description', 'trim|xss_clean|required');
		$this->form_validation->set_rules('keywords', 'keywords', 'trim|xss_clean|required');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('admin/dashboard/seo_settings'));
			}else{	
				$social = array(
					'title' => $this->input->post('title',TRUE),
					'description' => $this->input->post('description',TRUE),
					'keywords' => $this->input->post('keywords',TRUE),
				);

				$data = array(
					'seo_settings' => json_encode($social),
				);
				if($id==0){
					$insert = $this->admin_m->insert($data,'setting');
				}else{
					$insert = $this->admin_m->update($data,$id,'setting');
				}

				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/seo_settings'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/seo_settings'));
				}	
		}
	}

	
public function upgrade()
{
	check_valid_auth();
	$data = array();
	$data['page_title'] = "Upgrade";
	$data['c_page'] = "Settings";
	$data['settings'] = $this->admin_m->single_select('setting');
	$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/upgrade', $data, TRUE);
	$this->load->view('admin/index',$data);
}

public function apply_upgrade(){
	is_test();
	$this->form_validation->set_rules('purchase_code', 'Purchases Code', 'trim|required|xss_clean');
	$this->form_validation->set_rules('site_id', 'Site Id Code', 'trim|required|xss_clean');
	$this->form_validation->set_rules('old_code', 'Old Code', 'trim|required|xss_clean');
	if ($this->form_validation->run() == FALSE) {
		$this->session->set_flashdata('error', validation_errors());
		redirect(base_url('admin/dashboard/upgrade'));
		}else{	
			
			$purchase_code = $this->input->post('purchase_code',true);
			$old_code = $this->input->post('old_code',true);
			$site_id = $this->input->post('site_id',true);
			$site_url = $this->input->post('site_url',true);

			$site_data = array(
				'purchase_code' => $purchase_code,
				'old_code' => $old_code,
				'site_id' => $site_id,
				'site_url' => $site_url,
			);


			$check_valid = $this->check_vaild_license($site_data);
			if($check_valid->st ==1):
				$data = array(
					'supported_until' => $check_valid->supported_until,
					'active_code' => $check_valid->active_code,
					'purchase_code' =>$purchase_code,
					'site_info' =>$check_valid->li,
					'license' =>$check_valid->license,
					'site_url' => SITE_LINK,
					'active_key' => $check_valid->active_key,
					'license_code' => $check_valid->li_code,
					'created_at' =>d_time(),
				);
				$insert = $this->admin_m->update_setting($data,$site_id,'setting');
				redirect(base_url('admin/dashboard'));
			else:
				$this->session->set_flashdata('error', 'Invalid Purchases Code / PUrchase code already used');
				redirect(base_url('admin/dashboard/upgrade'));
			endif;
				
	}
}


	public function check_vaild_license($data){
		// check_valid_purchases
		$form_data = array(
			'purchase_code' => $data['purchase_code'],
			'old_code' => $data['old_code'],
			'site_id' => $data['site_id'],
			'site_url' => $data['site_url'],
		);

		$form_data = json_encode($form_data);
		$ch = curl_init(URL."site_api/upgrade_phplime_license/");  
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                     
		curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);                   
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
		curl_setopt($ch, CURLOPT_POST, 1);                                    
		$result = curl_exec($ch);

		curl_close($ch);
		return $result = json_decode($result);
	}

  public function install_payment($field,$status){
		$settings = get_setting();
		$data = [$field => $status];
		$this->admin_m->update($data,$settings['id'],'setting');
		$this->session->set_flashdata('success',!empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
		redirect(base_url('admin/dashboard/payment_settings'));
	}

	public function import_json($slug){
		$csvMimes = array('application/json','text/json','text/json','text/json');
		if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
			if(is_uploaded_file($_FILES['file']['tmp_name'])){
				$string = file_get_contents($_FILES['file']['tmp_name']);
				$json_a = json_decode($string, true);
				foreach ($json_a as $key => $value) {
					$data[] = array(
							'id' => $value['id'],
							$slug => $value[$slug],
					);
				}
				$this->db->update_batch('language_data',$data, 'id'); 
				$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
			}else{
				$this->session->set_flashdata('error', lang('error_text'));
			}
		}else{
			$this->session->set_flashdata('error', "Invalid File");
		}
		
		redirect(base_url('admin/dashboard/dashboard_languages'));
	}


	public function exportjson($slug){ 
   // file name 
		$filename = $slug.'_'.date('Ymd').'.json'; 
		header("Content-Description: File Transfer"); 
		header("Content-Disposition: attachment; filename=$filename"); 
		header("Content-Type: application/json; charset=UTF-8");
		header('content-type:text/html;charset=utf-8');

   // get data 
		$usersData = $this->admin_m->get_cvs_data();
		$data = array();

		foreach ($usersData as $key => $row) {
			$data[] = array(
				'id' => $row['id'],
				'keyword' => $row['keyword'],
				'english' => $row['english'],
				$slug => !empty($row[$slug])?$row[$slug]:'',
			);
		}


		$fp = fopen('php://output', 'w');
		fwrite($fp, json_encode($data,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE ));
		fclose($fp);


	}

	public function summernote_image_upload() {
		if ($_FILES['file']['name']) {
					if (!$_FILES['file']['error']) {
						$name = md5(rand(100, 200));
						$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
						$filename = $name.'.'.$ext;
		    $destination = 'uploads/'.$filename; //change this directory
		    $location = $_FILES["file"]["tmp_name"];
		    move_uploaded_file($location, $destination);
		    echo base_url('uploads/'.$filename); //change this URL
		  } else {
		  	echo $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
		  }
		}
	}


public function change_domain()
{
	check_valid_auth();
	$data = array();
	$data['page_title'] = "Change Domain";
	$data['c_page'] = "Settings";
	$data['settings'] = $this->admin_m->single_select('setting');
	$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/change_domain', $data, TRUE);
	$this->load->view('admin/index',$data);
}

public function extras()
{
	check_valid_auth();
	$data = array();
	$data['page_title'] = "Extras";
	$data['c_page'] = "Settings";
	$data['settings'] = $this->admin_m->single_select('setting');
	$data['main_content'] = $this->load->view('admin/dashboard/admin_activities/extras', $data, TRUE);
	$this->load->view('admin/index',$data);
}

public function add_extras(){
		is_test();
    	$id = $this->input->post('id');
		$this->form_validation->set_rules('g_font_name', 'Google Font Name', 'trim|xss_clean');
		$this->form_validation->set_rules('custom_css', 'Custom Css', 'trim');
		$this->form_validation->set_rules('custom_js', 'Custom Js', 'trim');
		if ($this->form_validation->run() == FALSE) {
			 $this->session->set_flashdata('error', validation_errors());
			 redirect(base_url('admin/dashboard/extras'));
			}else{	
				$data = array(
					'g_font_name' => $this->input->post('g_font_name',TRUE),
					'custom_css' => $this->input->post('custom_css'),
					'custom_js' => $this->input->post('custom_js'),
				);

				
				if($id==0){
					$insert = $this->admin_m->insert($data,'setting');
				}else{
					$insert = $this->admin_m->update($data,$id,'setting');
				}
				if($insert){
					$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
					redirect(base_url('admin/dashboard/extras'));
				}else{
					$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
					redirect(base_url('admin/dashboard/extras'));
				}	
		}
	}



public function request_change_domain(){
	is_test();
		$this->form_validation->set_rules('code', 'Purchase code', 'trim|required|xss_clean');
		$this->form_validation->set_rules('site_url', 'New Url', 'trim|required|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
				redirect($_SERVER['HTTP_REFERER']);
			}else{	
				$code = $this->input->post('code',true);
				$site_id = $this->input->post('site_id',true);
				$site_url = get_domain($this->input->post('site_url',true));
				$check_valid = $this->check_vaild_pruchase_code($code,$site_id,$site_url);
	
				if($check_valid->st ==1):
					$data = array(
						'supported_until' => $check_valid->supported_until,
						'active_code' => $check_valid->active_code,
						'purchase_code' =>$code,
						'site_url' => $site_url,
						'active_key' => $check_valid->active_key,
						'is_update' => 0,
						'license' => $check_valid->license,
						'site_info' => $check_valid->li,
						'license_code' => $check_valid->li_code,
						'purchase_date' => $check_valid->sold_at,
						'created_at' =>d_time(),
					); 
					$insert = $this->admin_m->update_setting($data,$site_id,'setting');
					$this->session->set_flashdata('success','Thank you! Your URL changed Successfully');
					if($insert){
						// $this->reset_qr();
					}
					redirect($_SERVER['HTTP_REFERER']);
				else:
					$this->session->set_flashdata('error', $check_valid->msg);
					redirect($_SERVER['HTTP_REFERER']);
				endif;	
		}
	}

	public function check_vaild_pruchase_code($code,$site_id,$site_url){
		// check_valid_purchases
			$form_data = array(
				'code'  => $code,
				'site_id'  => $site_id,
				'site_link'  => $site_url,
				'is_exchange'  => 1,
			);

			$form_data = json_encode($form_data);
			$ch = curl_init(URL."check-valid");  
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                     
			curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);                   
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
			curl_setopt($ch, CURLOPT_POST,1);                                    
			$result = curl_exec($ch);
			curl_close($ch);
			return $result = json_decode($result);
	}






}
