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

class Vcards extends CI_Controller {
	public function __construct(){
		parent::__construct();
		check_login_user();
		check_valid_user();
		is_valid();
	}

	public function index()
	{
		$data = array();
		$data['page_title'] = "Create Profile";
		$data['page'] = "vCard";
		if(isset($_GET['_user_token']) && !empty($_GET['_user_token'])){
			$data['data'] = $this->admin_m->get_my_vcard($_GET['_user_token']);
			$data['user_id'] = isset($data['data']['id']) && !empty($data['data']['id'])?$data['data']['id']:0;
			$data['sites']=$this->admin_m->get_my_vcard_info($data['user_id']);
			$data['social_sites'] = $this->admin_m->get_social_icon(0);
			$data['settings'] = $this->common_m->get_user_settings($data['user_id']);

		}else{
			$data['data'] = FALSE;
		}
		$data['u_info']=$this->admin_m->get_user_info();
		$data['countries']=$this->admin_m->select('countries');
		if(isset($_GET['_user_token']) && isset($_GET['p']) && $_GET['p']==1):
			$data['main_content'] = $this->load->view('admin/vcard/create_1', $data, TRUE);
		elseif(isset($_GET['_user_token']) && $_GET['p']==2):
			$data['main_content'] = $this->load->view('admin/vcard/create_2', $data, TRUE);
		elseif(isset($_GET['_user_token']) && $_GET['p']==3):
			$data['main_content'] = $this->load->view('admin/vcard/create_3', $data, TRUE);
		elseif(isset($_GET['_user_token']) && $_GET['p']==4):
			$data['main_content'] = $this->load->view('admin/vcard/create_4', $data, TRUE);
		elseif(isset($_GET['_user_token']) && $_GET['p']=='pwa'):
			$data['main_content'] = $this->load->view('admin/vcard/vcard_pwa', $data, TRUE);
		elseif(isset($_GET['_user_token']) && $_GET['p']=='settings'):
			$data['main_content'] = $this->load->view('admin/vcard/vcard_settings', $data, TRUE);
		else:
			$data['main_content'] = $this->load->view('admin/vcard/create_1', $data, TRUE);
		endif;

		
		$this->load->view('admin/index',$data);
	}

	public function create_vcard(){
		is_test();
		$id = $_POST['id'];
		$this->form_validation->set_rules('username', 'Label', 'trim|required|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			echo json_encode(['st'=>0,'msg'=>validation_errors()]);
		}else{
			$u_info = single_select_by_id($id,'users');
			if(isset($u_info['is_payment']) && $u_info['is_payment']==1 && $u_info['is_active']==1):
				$data = array(
					'username' => str_slug($this->input->post('username',true)),
					'ref_id' => auth('id'),
				);
			else:
				$data = array(
					'username' => str_slug($this->input->post('username',true)),
					'is_active' => 0,
					'is_payment' => 0,
					'is_verify' => 0,
					'ref_id' => auth('id'),
				);
			endif;
			if(isset($id) && $id !=0){
				$insert = $this->admin_m->update($data,$id,'users');
			}else{
				$insert = $this->admin_m->insert($data,'users');
			}
				
			if($insert){
				$url = base_url('admin/vcards/?_user_token='.md5($insert).'&p=2');
				$msg = !empty(lang('success_text'))?lang('success_text'):'Save Change Successful';
				echo json_encode(['st'=>1,'msg'=>$msg,'url'=>$url]);
			}else{
				$msg = !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!';
				echo json_encode(['st'=>0,'msg'=>$msg,'url'=>'']);
			}	
		}
	}


	public function step_2(){
		is_test();
		$id = $_POST['id'];
		$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('country', 'country', 'trim|required|xss_clean');
		$this->form_validation->set_rules('designation', 'designation', 'trim|xss_clean');
		$this->form_validation->set_rules('dial_code', 'dial code', 'trim|xss_clean|required');
		$this->form_validation->set_rules('phone', 'phone', 'trim|xss_clean|required');
		$this->form_validation->set_rules('email', 'email', 'trim|xss_clean|required');
		if ($this->form_validation->run() == FALSE) {
			echo json_encode(['st'=>0,'msg'=>validation_errors()]);
		}else{


			$data = array(
				'name' => $this->input->post('name',true),
				'country' => $this->input->post('country',true),
				'designation' => $this->input->post('designation',true),
				'dial_code' => $this->input->post('dial_code',true),
				'phone' => $this->input->post('phone',true),
				'whatsapp' => $this->input->post('whatsapp',true),
				'email' => $this->input->post('email',true),
				'about_me_short' => $this->input->post('about_me_short',true),
				'about_me_long' => $this->input->post('about_me_long'),
			);
			if(isset($id) && $id !=0){
				$insert = $this->admin_m->update($data,$id,'users');
			}else{
				$msg = !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!';
				echo json_encode(['st'=>0,'msg'=>$msg,'url'=>'']);
			}
				
			if($insert){
				$url = base_url('admin/vcards/?_user_token='.md5($insert).'&p=3');
				$msg = !empty(lang('success_text'))?lang('success_text'):'Save Change Successful';
				echo json_encode(['st'=>1,'msg'=>$msg,'url'=>$url]);
			}else{
				$msg = !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!';
				echo json_encode(['st'=>0,'msg'=>$msg,'url'=>'']);
			}	
		}
	}


	public function add_vcard_icon(){
		is_test();
		check_login_user();
		$this->form_validation->set_rules('label[]', 'Label', 'trim|required|xss_clean');
		$this->form_validation->set_rules('value[]', 'Value', 'trim|required|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			echo json_encode(['st'=>0,'msg'=>validation_errors()]);
		}else{
			$id = $_POST['id'];	
			if(isset($_POST['site_id']) && !empty($_POST['site_id'])):
				$i=1;
				foreach ($_POST['site_id'] as $key => $site) {
					$user_site = $this->admin_m->get_vcard_social_sites($site,$id);
					$data = array(
						'site_id' => $site,
						'orders' => $i,
						'label' => $this->input->post('label',true)[$site],
						'value' => $this->input->post('value',true)[$site],
						'user_id' => $id,
					);
					$i++;
					if(isset($user_site['site_id']) && $user_site['site_id']==$site){
						$insert = $this->admin_m->update($data,$user_site['id'],'vcard_social_sites');
					}else{
						$insert = $this->admin_m->insert($data,'vcard_social_sites');
					}
				}
			endif;

			if($insert){
				$url = base_url('admin/vcards/?_user_token='.md5($id).'&p=4');
				$msg = !empty(lang('success_text'))?lang('success_text'):'Save Change Successful';
				echo json_encode(['st'=>1,'msg'=>$msg,'url'=>$url]);
			}else{
				$msg = !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!';
				echo json_encode(['st'=>0,'msg'=>$msg,'url'=>'']);
			}	
		}
	}

	public function add_vcard_color($id)
	{


		$u_info = $this->admin_m->user_info_by_id(auth('id'));
		$my_info = $this->admin_m->user_info_by_id($id);
		$icon_color = substr($this->input->post('vcard_icon_color'), 1);
		$bg_color = substr($this->input->post('vcard_bg_color'), 1);
		$c_data = array(
			'vcard_bg_color' => $bg_color,
			'vcard_icon_color' => $icon_color,
			'vcard_layouts' => $this->input->post('vcard_layouts',true),
			'vcard_header_style' => $this->input->post('vcard_header_style',true),
			'is_active' =>$u_info->is_active,
			'is_payment' =>$u_info->is_payment,
			'is_verify' =>$u_info->is_verify,
			'is_expired' =>$u_info->is_expired,
			'account_type' =>$u_info->account_type,
			'vcard_status' =>$my_info->ref_id !=0?1:$u_info->vcard_status,
			'active_vcard' =>$my_info->ref_id !=0?1:$u_info->active_vcard,
		);
		$url = $_SERVER['HTTP_REFERER'];
		$this->admin_m->update($c_data,$id,'users');
		$this->qr_code($id);
		$msg = !empty(lang('success_text'))?lang('success_text'):'Save Change Successful';
		echo json_encode(['st'=>1,'msg'=>$msg,'url'=>$url]);

	}


	public function add_pwa(){
		is_test();
		if(is_allow() !=1):
			exit();
		endif;
		$id = $this->input->post('id');
		$this->form_validation->set_rules('title', 'Title', 'trim|xss_clean|required');
		$this->form_validation->set_rules('theme_color', 'Theme Color', 'trim|xss_clean');
		$this->form_validation->set_rules('background_color', 'background Color', 'trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect($_SERVER['HTTP_REFERER']);
		}else{	
			$old_img = $this->input->post('old_img');
			$logo = $this->upload_logo($old_img);
			$is_pwa_active = $this->input->post('is_pwa_active');

			$pwaData = array(
				'title' => $this->input->post('title',TRUE),
				'theme_color' => substr($this->input->post('theme_color',TRUE),1),
				'background_color' => substr($this->input->post('background_color',TRUE),1),
				'is_pwa_active' => isset($is_pwa_active)?$is_pwa_active :0,
				'logo' => !empty($logo)?$logo:$old_img,

			);
			$data = array(
				'pwa_config' => json_encode($pwaData),
				'user_id' =>$this->input->post('user_id'),
			);


			if($id==0){
				$insert = $this->admin_m->insert($data,'user_settings');
			}else{
				$insert = $this->admin_m->update($data,$id,'user_settings');
			}

			if($insert){
				$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($_SERVER['HTTP_REFERER']);
			}	
		}
	}


	public function add_vcard_settings(){
		is_test();
		
		$id = $this->input->post('id');
		$this->form_validation->set_rules('is_value', lang('hide_vcard_value'), 'trim|xss_clean|required');
		$this->form_validation->set_rules('is_clickable', lang('turn_on_vcard_click'), 'trim|xss_clean');
		$this->form_validation->set_rules('share_this_key', lang('share_this_key'), 'trim|xss_clean');
		$this->form_validation->set_rules('is_share_this', lang('share_this_key'), 'trim|xss_clean');
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect($_SERVER['HTTP_REFERER']);
		}else{	
			$is_value = $this->input->post('is_value');
			$is_clickable = $this->input->post('is_clickable');
			$is_share_this = $this->input->post('is_share_this');

			$vcard_settings = array(
				'share_this_key' => $this->input->post('share_this_key',TRUE),
				'is_value' => isset($is_value)?$is_value :0,
				'is_clickable' => isset($is_clickable)?$is_clickable :0,
				'is_share_this' => isset($is_share_this)?$is_share_this :0,

			);
			$data = array(
				'vcard_settings' => json_encode($vcard_settings),
				'user_id' =>$this->input->post('user_id'),
			);

			if($id==0){
				$insert = $this->admin_m->insert($data,'user_settings');
			}else{
				$insert = $this->admin_m->update($data,$id,'user_settings');
			}

			if($insert){
				$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($_SERVER['HTTP_REFERER']);
			}	
		}
	}


	public function upload_profile_image($id,$type)
	{
		is_test();
		ini_set('memory_limit', '-1');
		$data = array();
		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/vcard/';


				$config['upload_path'] = $uploadPath;
	              // Specifying the file formats that are supported.
				$config['allowed_types'] = 'jpg|jpeg|png';
				$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'            => 250
						);
					$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(
						'image' => $uploadPath.$value['file_name'],
						'thumb' => $uploadPath.'thumb/'.$value['file_name'],
					);
		          	//insert image into database query
		          	if($type==1){
		          		$this->admin_m->update(array('thumb' => $data['thumb']),$id,'users');
		          	}else{
		          		$this->admin_m->update(array('cover_photo' => $data['image']),$id,'users');
		          	}
					
				}
				echo json_encode(array('st'=>1,'img'=>$data['image'],'type'=>$type));
			}else{
				$msg = 'Please insert an image';
				echo json_encode(array('st'=>0,'msg'=>$msg,));
			}

		}
	}

	public function qr_code($id){

		$check = get_user_info_by_id($id);
		$username = $check['username'];
		if(empty($check['qr_code']) || !file_exists($check['qr_code'])):
			$this->load->library('ciqrcode');
			$qr_image=$username.'_'.rand().'.png';
			$params['data'] = base_url($username);
			$params['level'] = 'H';
			$params['size'] = 8;
			$params['savename'] =FCPATH."uploads/qrcode/".$qr_image;
			if($this->ciqrcode->generate($params))
			{
				$data = array(
					'qr_code' =>'uploads/qrcode/'.$qr_image,
				);
				$update = $this->admin_m->update_by_username($data,$username,'users');
				return true;
			}
		endif;
		return true;
	}

	public function upload_logo()
	{
		is_test();
		if(!empty($_FILES['images']['name'])){
			$directory = 'uploads/pwa/';
			$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);
				return $url;
			}else{
				echo "image uploading failed";
			};
		}

	}

}
