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

class Service extends CI_Controller {
	public function __construct(){
		parent::__construct();
	}

	public function registration()
	{
		$sorry = !empty(lang("sorry"))?lang("sorry"):"sorry";
		$success = !empty(lang("success"))?lang("success"):"success";
		$reg_success = !empty(lang("registration_successfull"))?lang("registration_successfull"):"Registration successfull";
		$invalid = !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!';

		$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');			
		$this->form_validation->set_rules('phone', 'phone', 'trim|required|xss_clean|is_unique[customer_list.phone]',array('is_unique'=>'The phone is already Exists'));	
		$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|min_length[3]');
		$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|xss_clean|matches[password]');
		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>
			<strong>Sorry ! </strong> '.validation_errors().'
			</div>';
			echo json_encode(array('st' => 0, 'msg'=> $msg,));
		}else{	

			$name = $this->input->post('name',true);
			$phone = $this->input->post('phone',true);
			$password = $this->input->post('password',true);
			$country_code = $this->input->post('country_code',true);
			$country_info = $this->admin_m->get_country_info($country_code);
			$data = array(
				'name' => $name,
				'phone' => $phone,
				'country_id' => !empty($country_info)?$country_info->id:0,
				'password' => md5($password),
				'created_at' => d_time(),
			);
			$insert = $this->common_m->insert($data,'customer_list');
			if($insert):
				$s_array = array(
					'customer_id' => $insert,
					'customer_name' => $name,
					'phone' => $phone,
					'is_customer' => TRUE,
				);
				$this->session->set_userdata($s_array);
				$msg = "<div class='alert alert-success alert-dismissible'>
					<a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>
					<strong>{$success} ! </strong> {$reg_success}  <i class='fa fa-smile-o'></i>

					</div>";
					echo json_encode(array('st' => 1, 'msg'=> $msg));
					exit();
				else:
					$msg = '<div class="alert alert-danger alert-dismissible">
					<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<strong>'.$sorry.'</strong> '.$invalid.' <i class="fa fa-frown-o" ></i>
					</div>';
					echo json_encode(array('st' =>0, 'msg'=> $msg));
			endif;

	} 
		//end validation 
}	

public function customer_login()
{
	$sorry = !empty(lang("sorry"))?lang("sorry"):"sorry";
	$welcome = !empty(lang("welcome"))?lang("welcome"):"Welcome";
	$login_success = !empty(lang("login_success"))?lang("login_success"):"Login successfull";
	$not_approve = !empty(lang("account_not_approve"))?lang("account_not_approve"):"Your account is not approved";
	$invalid = !empty(lang("invalid_login"))?lang("invalid_login"):"Login invalid";
		
	$this->form_validation->set_rules('phone', 'phone', 'trim|required|xss_clean');	
	$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
	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>
		<strong>Sorry ! </strong> '.validation_errors().'
		</div>';
		echo json_encode(array('st' => 0, 'msg'=> $msg,));
	}else{	

		$email = $this->input->post('phone',TRUE);
		$password = $this->input->post('password',TRUE);

		$query = $this->admin_m->check_customer_login($email,$password); //check email / user name and password
		if($query){
			$s_array= array();
			foreach($query as $row):
				$s_array = array(
					'customer_id' => $row->id,
					'customer_name' => $row->name,
					'phone' => $row->phone,
					'is_customer' => TRUE,
				);

				$this->session->set_userdata($s_array);
					$msg = '<div class="alert alert-success alert-dismissible">
					<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<strong>'.$welcome.' ! </strong> '.$login_success.'  <i class="fa fa-smile-o"></i>

					</div>';
					echo json_encode(array('st' => 1, 'msg'=> $msg));
					exit();
			endforeach;

		}else{
			
			
			$msg = '<div class="alert alert-danger alert-dismissible">
			<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
			<strong>'.$sorry.'</strong> '.$invalid.' <i class="fa fa-frown-o" ></i>
			</div>';
			echo json_encode(array('st' => 3, 'msg'=> $msg));
		} 
			//end login_info_check 

	} 
		//end validation 
}

 public function profile(){
    	if(empty(auth('is_customer'))){
        	redirect(base_url());
        }
    	$data= [];
    	$data['page_title'] = "Customer Profile";
    	$data['info'] = $this->admin_m->single_select_by_id(auth('customer_id'),'customer_list');
    	$data['countries'] = $this->admin_m->select('countries');
        $data['main_content'] = $this->load->view('customer/customer_profile', $data, TRUE);
		$this->load->view('customer/index',$data);

    }

    public function password(){
    	if(empty(auth('is_customer'))){
        	redirect(base_url());
        }
    	$data= [];
    	$data['page_title'] = "Customer Password";
    	$data['info'] = $this->admin_m->single_select_by_id(auth('customer_id'),'customer_list');
        $data['main_content'] = $this->load->view('customer/change_password', $data, TRUE);
		$this->load->view('customer/index',$data);

    }


    public function update_profile()
	{

		$sorry = !empty(lang("sorry"))?lang("sorry"):"sorry";
		$success = !empty(lang("success"))?lang("success"):"success";
		$reg_success = !empty(lang("registration_successfull"))?lang("registration_successfull"):"Registration successfull";
		$invalid = !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!';


		$phone = $this->input->post('phone',true);
		$active_phone = $this->input->post('active_phone',true);

		$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');	
		if($phone==$active_phone):		
			$this->form_validation->set_rules('phone', 'phone', 'trim|required|xss_clean');	
		else:
			$this->form_validation->set_rules('phone', 'phone', 'trim|required|xss_clean|is_unique[customer_list.phone]',array('is_unique'=>'The phone is already Exists'));
		endif;
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('service/profile'));
		}else{	

			$name = $this->input->post('name',true);
			$country_id = $this->input->post('country_id',true);
			$data = array(
				'name' => $name,
				'phone' => $phone,
				'email' => $this->input->post('email',true),
				'country_id' => $country_id,
			);
			$insert = $this->common_m->update($data,auth('customer_id'),'customer_list');
			if($insert):
				$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
				redirect(base_url('service/profile'));
			else:
				$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
				redirect(base_url('service/profile'));
			endif;

		} 
	}	

	public function change_password()
	{
		
		$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|min_length[3]');
		$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|xss_clean|matches[password]');
		
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('service/profile'));
		}else{	

			$data = array(
				'password' => md5($this->input->post('password',true)),
			);
			$insert = $this->common_m->update($data,auth('customer_id'),'customer_list');
			if($insert):
				$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Save Change Successful');
				redirect(base_url('service/profile'));
			else:
				$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
				redirect(base_url('service/profile'));
			endif;

		} 
	}	

	public function logout()
	{
        $this->session->unset_userdata('is_customer');
        $sdata = array();
        $sdata['msg'] = 'Successfully logout';
        $this->session->set_userdata($sdata);
        redirect('login','refresh');
    }

    public function order_list(){
    	if(empty(auth('is_customer'))){
        	redirect(base_url());
        }
    	$data= [];
    	$data['page_title'] = "Customer OrderList";
    	$data['info'] = $this->admin_m->single_select_by_id(auth('customer_id'),'customer_list');
    	$data['order_list'] = $this->admin_m->get_customer_order_list(auth('customer_id'));
        $data['main_content'] = $this->load->view('customer/order_list', $data, TRUE);
		$this->load->view('customer/index',$data);

    }


    public function change_status($status,$id){
    	$data = [
    		'status' => $status
    	];

    	$this->admin_m->update($data,$id,'service_order');
    	redirect($_SERVER['HTTP_REFERER']);
    }


    public function load_modal($slug){
    	$data = array();
    	$data['slug'] = $slug;
    	$data['user']=users($slug);
		$this->load->view("service_payment/userLogin", $data);
    }

/*----------------------------------------------
	Paypal Payment method
----------------------------------------------*/

function paypal_payment($slug,$service_id){
	is_test();

	if(is_allow()!=1){
		redirect(base_url('error-404'));
	}

    $data = array();

	$id = get_id_by_slug($slug);
    if(empty($id)){
    	redirect(base_url('error-404'));
    }


 	//get payment data from paypal url
 	$paypalInfo = $this->input->get();

    $settings = get_setting();
    $service_info = single_select_by_id($service_id,'services'); //get package info by slug
    $u_info = get_all_user_info_slug($slug); //get user info by id from paypal url
    $customer_id = isset($_GET['customer_id'])?$_GET['customer_id']:auth('customer_id');
    $customer_info = single_select_by_id($customer_id,'customer_list');
    $order_id =  random_string('numeric',8);
    $data_info = array(
    	'user_id' => $u_info['user_id'],
    	'customer_id' => $customer_id,
    	'service_id' =>$service_id,
    	'order_id' =>$order_id,
    	'price' => $paypalInfo["amt"],
    	'currency_code' => $paypalInfo["cc"],
    	'payment_status' => $paypalInfo["st"],
    	'txn_id' => $paypalInfo["tx"],
    	'payment_by' => 'paypal',
    	'created_at' => d_time(),
    );
    $insert = $this->common_m->insert($data_info,'service_order');
    
    if($insert):
        if($service_info['price'] = $paypalInfo["amt"] && $paypalInfo["st"] == 'Completed'){

        	redirect(base_url('service/payment_success/'.$slug.'?txn_id='.$paypalInfo["tx"]).'&method=paypal&amount='.$paypalInfo["amt"]);
        }else{
        	redirect(base_url('service/payment_cancel/'.$slug.'&method=paypal'));
        }
    else:
    	redirect(base_url('service/payment_cancel/'.$slug.'&method=paypal'));
    endif;
    
 }






/*----------------------------------------------
	Payment success & Failed function
----------------------------------------------*/
 public function payment_success($slug){
 	$data= [];
        $u_info = get_all_user_info_slug($slug); //get user info by id from paypal url
        $id = get_id_by_slug($slug);
        $data['id']=$id;
        $data['slug']=$slug;
        $data['page_title']='Payment Successs';
        $data['type']='success';

        if(empty($id)){
        	redirect(base_url('error-404'));
        }
        $data['id'] = $u_info['user_id'];
        $data['slug'] = $u_info['username'];

        $data['service_settings'] = $this->admin_m->single_select_by_user($id,'service_settings');
        $data['main_content'] = $this->load->view(get_view_layouts_by_slug($slug).'/paymentStatus', $data, TRUE);
        $this->load->view(get_view_layouts_by_slug($slug).'/index', $data);

    }


    public function payment_failed($slug){
    	$data= [];
        $u_info = get_all_user_info_slug($slug); //get user info by id from paypal url
        $id = get_id_by_slug($slug);
        $data['id']=$id;
        $data['slug']=$slug;
        $data['page_title']='Payment Failed';
        $data['type']='failed';

        if(empty($id)){
        	redirect(base_url('error-404'));
        }
        $data['id'] = $u_info['user_id'];
        $data['slug'] = $u_info['username'];

        $data['service_settings'] = $this->admin_m->single_select_by_user($id,'service_settings');
        $data['main_content'] = $this->load->view(get_view_layouts_by_slug($slug).'/paymentStatus', $data, TRUE);
        $this->load->view(get_view_layouts_by_slug($slug).'/index', $data);

    }


   

    public function stripe_payment()
    {	
    	is_test();
    	if(is_allow()!=1){
			redirect(base_url('error-404'));
		}
		
    	if(!empty($this->input->post('stripeToken'))) {                                                             
    		$amount = $this->input->post('amount');
    		$service_id = $this->input->post('service_id');
    		$slug = $this->input->post('username');
    		$name = $this->input->post('stripe_name');
    		$email = $this->input->post('stripe_email');

    		$id = get_id_by_slug($slug);
		    if(empty($id)){
		    	redirect(base_url('error-404'));
		    }
		    $service_settings = $this->admin_m->single_select_by_user($id,'service_settings');
		    $stripe = json_decode($service_settings['stripe_config']);
		    $currency = my_currency($service_settings['country_id'],'currency_code');

    		$u_info = get_all_user_info_slug($slug);
    		$service_info = single_select_by_id($service_id,'services');
    		$customer_id = isset($_GET['customer_id'])?$_GET['customer_id']:auth('customer_id');
		    $customer_info = single_select_by_id($customer_id,'customer_list');
		    $order_id =  random_string('numeric',8);
		    if(empty($customer_info)){
		    	redirect(base_url('service/payment_cancel/'.$slug.'&method=stripe'));
		    }

    		$params = array(
    			'amount' => $amount * 100,
    			'currency' => strtoupper($currency),
    			'description' => 'Charge for '.$settings['site_name'].' Registrations',
    			'source' => $this->input->post('stripeToken'),
    			'metadata' => array( 
    				'product_id' => $package_id,
    			)
    		);
    		$jsonData = $this->get_curl_handle($params,$stripe);
    		$resultJson = json_decode($jsonData, true);
    		if($resultJson['amount_refunded'] == 0 && empty($resultJson['failure_code']) && $resultJson['paid'] == 1 && $resultJson['captured'] == 1){ 
            // Order details  
    			$transactionID = $resultJson['balance_transaction']; 
    			$currency = $resultJson['currency']; 
    			$payment_status = $resultJson['status'];


             // If the order is successful 
    			if($payment_status == 'succeeded') { 
    				$data_info = array(
				    	'user_id' => $u_info['user_id'],
				    	'customer_id' => $customer_id,
				    	'service_id' =>$service_id,
				    	'order_id' =>$order_id,
				    	'price' => $amount,
				    	'currency_code' => $currency,
				    	'payment_status' => $payment_status,
				    	'txn_id' => $transactionID,
				    	'payment_by' => 'stripe',
				    	'created_at' => d_time(),
				    );
				    $insert = $this->common_m->insert($data_info,'service_order');
    				if($insert):  
			         	redirect(base_url("service/payment_success/{$slug}?txn_id={$transactionID}&method=stripe&amount={$amount}"));
			         else:
			         	redirect(base_url('service/payment_cancel/'.$slug.'&method=stripe'));
			   		 endif;
			}else{
				$this->session->set_flashdata('error','Payment Faild');
				redirect(base_url('service/payment_cancel/'.$slug.'&method=stripe'));
			}
		}else{
			$this->session->set_flashdata('error',$resultJson['message']);
			redirect(base_url('service/payment_cancel/'.$slug.'&method=stripe'));
		} //enter stripe
	}
}

// get curl handle method
private function get_curl_handle($data,$stripe) {
	$url = 'https://api.stripe.com/v1/charges';
	$key_secret = $stripe->secret_key;
        //cURL Request
	$ch = curl_init();
        //set the url, number of POST vars, POST data
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_USERPWD, $key_secret);
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	curl_setopt($ch, CURLOPT_POST, 1);
	$params = http_build_query($data);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
	$output = curl_exec ($ch);
	return $output;
}


private function curl_handler($payment_id, $data, $keys)  {
	$url            = 'https://api.razorpay.com/v1/payments/'.$payment_id.'/capture';
	$key_id         = $keys['key_id'];
	$key_secret     = $keys['secret_key'];
	$params = http_build_query($data);
        //cURL Request
	$ch = curl_init();
        //set the url, number of POST vars, POST data
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_USERPWD, $key_id.':'.$key_secret);
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
	return $ch;
}   
        
    // callback method
    public function razorpay_payment() { 
    	is_test();
    	if(is_allow()!=1){
			redirect(base_url('error-404'));
		}


    	$data = array();    
    	if (!empty($this->input->post('razorpay_payment_id'))) {



    		$price = $this->input->post('totalAmount');
    		$service_id = $this->input->post('product_id');
    		$slug = $this->input->post('username');
    		$name = $this->input->post('name');
    		$email = $this->input->post('email');

    		$id = get_id_by_slug($slug);
		    if(empty($id)){
		    	redirect(base_url('error-404'));
		    }

		    $service_settings = $this->admin_m->single_select_by_user($id,'service_settings');
		    $razorpay = json_decode($service_settings['razorpay_config'],true);

		    $currency = my_currency($service_settings['country_id'],'currency_code');

    		$u_info = get_all_user_info_slug($slug);
    		$service_info = single_select_by_id($service_id,'services');

    		$customer_id = isset($_GET['customer_id'])?$_GET['customer_id']:auth('customer_id');
		    $customer_info = single_select_by_id($customer_id,'customer_list');

		    $order_id =  random_string('numeric',8);



		    if(empty($customer_info)){
		    	redirect(base_url('service/payment_cancel/'.$slug.'&method=razorpay'));
		    }
		    
    		$razorpay_payment_id = $this->input->post('razorpay_payment_id');
    		$currency_code = $currency;

    		$keys = array(
			    'key_id' => $razorpay['key_id'],
			    'secret_key' => $razorpay['secret_key'],
			);


    		$data = array(
    			'amount' => $price,
    			'currency' => $currency_code,
    		);

    		$success = false;
    		$error = '';
    		try {                
    			$ch = $this->curl_handler($razorpay_payment_id, $data,$keys);
                //execute post
    			$result = curl_exec($ch);

    			$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    			if ($result === false) {
    				$success = false;
    				$error = 'Curl error: '.curl_error($ch);
    			} else {
    				$response_array = json_decode($result, true);
                        //Check success response
    				if ($http_status === 200 and isset($response_array['error']) === false) {
    					$success = true;
    				} else {
    					$success = false;
    					if (!empty($response_array['error']['code'])) {
    						$error = $response_array['error']['code'].':'.$response_array['error']['description'];
    					} else {
    						$error = 'RAZORPAY_ERROR:Invalid Response <br/>'.$result;
    					}
    				}
    			}
                //close curl connection
    			curl_close($ch);
    		} catch (Exception $e) {
    			$success = false;
    			$error = 'Request to Razorpay Failed';
    			$url = base_url('service/payment_cancel/'.$slug.'&method=razorpay');
    			echo json_encode(['st'=>0,'url'=>$url,'msg'=>$$error]);
    		}

    		if ($success === true) {
    			$amount = $price/100;
    			$data_info = array(
    				'user_id' => $u_info['user_id'],
    				'customer_id' => $customer_id,
    				'service_id' =>$service_id,
    				'order_id' =>$order_id,
    				'price' => $amount,
    				'currency_code' => $response_array['currency'],
    				'payment_status' => $response_array['status'],
    				'txn_id' => $response_array['id'],
    				'payment_by' => 'razorpay',
    				'created_at' => d_time(),
    			);
				$insert = $this->common_m->insert($data_info,'service_order');
    			$url = base_url("service/payment_success/{$slug}?txn_id={$razorpay_payment_id}&method=razorpay&amount={$amount}");
    			echo json_encode(['st'=>1,'url'=>$url,'msg'=>'']);

    		} else {
    			$msg = 'Payment Canceled';
    			$url = base_url('service/payment_cancel/'.$slug.'&method=razorpay');
    			echo json_encode(['st'=>0,'url'=>$url,'msg'=>$msg]);
    		}
    	} else {
    		$msg = 'An error occured. Contact site administrator, please!';
    		$url = base_url('service/payment_cancel/'.$slug.'&method=razorpay');
    		echo json_encode(['st'=>0,'url'=>$url,'msg'=>$msg]);
    		
    	}
    } 





public function offline_payment($slug,$service_id)
{
	is_test();
	$data = array();
	$data['slug'] = $slug;
	$id = get_id_by_slug($slug);
	if(empty($id)){
		redirect(base_url('error-404'));
	}

	$txn_id = 'op-'.random_string('alnum',4).'-'.random_string('numeric',4);
	$u_info = get_all_user_info_slug($slug);
	$service_info = single_select_by_id($service_id,'services');
	$customer_id = isset($_GET['customer_id'])?$_GET['customer_id']:auth('customer_id');
    $customer_info = single_select_by_id($customer_id,'customer_list');
    $order_id =  random_string('numeric',8);
    $service_settings = $this->admin_m->single_select_by_user($id,'service_settings');
	$currency = my_currency($service_settings['country_id'],'currency_code');
    
	if(!empty($customer_info)){
		$data_info = array(
			'user_id' => $u_info['user_id'],
			'customer_id' => $customer_id,
			'service_id' =>$service_id,
			'order_id' =>$order_id,
			'price' => $service_info['price'],
			'currency_code' => $currency,
			'payment_status' => 'pending',
			'txn_id' => $txn_id,
			'payment_by' => 'offline',
			'created_at' => d_time(),
		);
		$insert = $this->common_m->insert($data_info,'service_order');
		if($insert):
			redirect(base_url("service/payment_success/{$slug}?txn_id={$txn_id}&method=offline&amount={$service_info['price']}"));
		else:
			redirect(base_url('service/payment_cancel/'.$slug.'&method=offline'));
		endif;

	}else{
		redirect(base_url('service/payment_cancel/'.$slug.'&method=offline'));
	}
	
}



}