<?php
/*
  $Id: paypal_smc.php,v 1.4 2020/03/05 00:36:42 ccwjr Exp $

  LoadedCommerce, Open Source E-Commerce Solutions
  https://www.loadedcommerce.com

  Copyright (c) 2003 LoadedCommerce

 */

  class paypal_smc {
    var $code, $title, $description, $enabled, $sort_order;
    var $accepted_cc, $card_types, $allowed_types;

// class constructor
  function __construct() {
    global $order;
    $this->pci = TRUE;
    $this->code = 'paypal_smc';
    $this->title = lc_defined_constant('MODULE_PAYMENT_PAYPAL_SMC_TEXT_TITLE');
    $this->description = lc_defined_constant('MODULE_PAYMENT_PAYPAL_SMC_TEXT_DESCRIPTION');
    $this->sort_order = lc_defined_constant('MODULE_PAYMENT_PAYPAL_SMC_SORT_ORDER');
    $this->enabled = (lc_check_constant_val('MODULE_PAYMENT_PAYPAL_SMC_STATUS', 'True') ? true : false);
    $this->accepted_cc = lc_defined_constant('MODULE_PAYMENT_PAYPAL_SMC_ACCEPTED_CC');

    if (lc_defined_constant_int('MODULE_PAYMENT_PAYPAL_SMC_ORDER_STATUS_ID') > 0) {
        $this->order_status = MODULE_PAYMENT_PAYPAL_SMC_ORDER_STATUS_ID;
    }
    $this->requestdata = '';
    if(lc_check_constant_val('MODULE_PAYMENT_PAYPAL_SMC_TESTMODE','Test')) {
     $this->url = 'https://api.sandbox.paypal.com/';
    }else{
      $this->url = 'https://api.paypal.com/';
    }

    if (is_object($order)) $this->update_status();

    //array for credit card selection
    $this->card_types = array('Amex' => 'Amex',
        'Mastercard' => 'Mastercard',
        'Discover' => 'Discover',
        'Visa' => 'Visa');
    $this->allowed_types = array();

    // Credit card pulldown list
    $cc_array = explode(', ', lc_defined_constant('MODULE_PAYMENT_PAYPAL_SMC_ACCEPTED_CC'));
	foreach($cc_array as $key=>$value) {
      $this->allowed_types[$value] = $this->card_types[$value];
    }

    // Processing via Paypal Smart checkout AIM
    $filename_checkout_process = (defined('FILENAME_CHECKOUT_PROCESS') && FILENAME_CHECKOUT_PROCESS != '')?FILENAME_CHECKOUT_PROCESS:'checkout_process.php';
    $this->form_action_url = tep_href_link($filename_checkout_process, '', 'SSL', false);
    //Set the select action
    $this->setPageCode();
  }

// class methods
  function update_status() {
    global $order;
    if ( ($this->enabled == true) && (lc_defined_constant_int('MODULE_PAYMENT_PAYPAL_SMC_ZONE') > 0) ) {
      $check_flag = false;
      $check_query = tep_db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_PAYPAL_SMC_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
      while ($check = tep_db_fetch_array($check_query)) {
        if ($check['zone_id'] < 1) {
          $check_flag = true;
          break;
        } elseif ($check['zone_id'] == $order->billing['zone_id']) {
          $check_flag = true;
          break;
        }
      }
      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }


	//concatenate to get CC images
	function get_cc_images() {
	  $cc_images = '';
	  reset($this->allowed_types);
  	  foreach($this->allowed_types as $key=>$value) {
		$cc_images .= tep_image(DIR_WS_ICONS . $key . '.gif', $value);
	  }
	  return $cc_images;
	}

	function javascript_validation() {
		  return '';
	}
	function selection() {
		global $order;
		reset($this->allowed_types);
  	    foreach($this->allowed_types as $key=>$value) {
			$card_menu[] = array('id' => $key, 'text' => $value);
		}
		$selection = array('id' => $this->code,
		'module' => $this->title,
		'fields' => array(array('title' => '', 'field' => '<input type="hidden" id="smsbtn_chk" name="smsbtn_chk" value="0"/><input type="hidden" id="authorizationid" name="authorizationid" value="0"/><input
					type="hidden" id="smc_transaction_id" name="smc_transaction_id" value="0"/><input type="hidden" id="smc_payerid" name="smc_payerid" value="0"/>')));
		return $selection;
    }

    function pre_confirmation_check() {
        return false;
    }

	function confirmation() {
		return false;
	}
    function process_button() {
     // Change made by using ADC Direct Connection
      $process_button_string = tep_draw_hidden_field('x_Card_Code', str_replace('_','',$_POST['paypal_smc_cc_checkcode'])) .
                               tep_draw_hidden_field('x_Card_Num', $this->cc_card_number) .
                                tep_draw_hidden_field('x_Exp_Date', $this->cc_expiry_year.'-'.$this->cc_expiry_month);

      $process_button_string .= tep_draw_hidden_field(tep_session_name(), tep_session_id());
      return $process_button_string;
    }

    function before_process() {
		global $response,$insert_id,$order, $messageStack;
	
	   if(isset($_POST['authorizationid']) && $_POST['authorizationid'] != ''){
		$authorizationid = $_POST['authorizationid'];		   
		$approval_code = $_POST['smc_payerid'];
		$token_id =  $_SESSION['token_id'];
		$returndata = $this->SMCprocess('','v2/payments/authorizations/'.$authorizationid.'/capture', $token_id);
		$returndata = json_decode($returndata,true);
		if($returndata['status'] == 'COMPLETED' || $returndata['status'] == 'PENDING'){
			 $trasnaction_id = $returndata['id'];
			 $sql_data = array('payment_type' => 'paypal_smc',
			  'payment_status' => 'Completed',
			  'mc_currency' => 'USD',
			  'mc_gross' =>$order->info['total'],
			  'mc_fee' => '',
			  'payment_date' => date('Y-m-d'),
			  'payer_id' => $approval_code,
			  'receiver_id' => '',
			  'txn_id' => $trasnaction_id,
			  'first_name' => $order->delivery['name'],
			  'address_street' => $order->delivery['street_address'],
			  'address_city' => $order->delivery['city'],
			  'address_state' => $order->delivery['state'],
			  'address_zip' => $order->delivery['postcode'],
			  'address_country' => $order->delivery['country'],
			  'date_added' => 'now()');
			tep_db_perform('paypal', $sql_data);
			$payment_id = tep_db_insert_id();
		             
		             
		   $orders_status = ($returndata['status'] == 'COMPLETED')? MODULE_PAYMENT_PAYPAL_SMC_ORDER_STATUS_ID:'1';  
		   if(MODULE_PAYMENT_PAYPAL_SMC_CCMODE == 'Authorize'){
		    tep_db_query("UPDATE " . TABLE_ORDERS . " SET payment_id='".$payment_id."', transaction_id='".$trasnaction_id."',approval_code='".$approval_code."', is_capture = 0, orders_status = '".$orders_status."' where orders_id = '" . (int)$insert_id . "'"); //Update the transaction ID to the order
		    }else{
		      tep_db_query("UPDATE " . TABLE_ORDERS . " SET payment_id='".$payment_id."',transaction_id='".$trasnaction_id."', approval_code='".$approval_code."', is_capture = 1, orders_status = '".$orders_status."' where orders_id = '" . (int)$insert_id . "'"); //Update the transaction ID to the order
		    }
		    if($returndata['status'] != 'COMPLETED'){
		         $sql_data_array = array('orders_id' => $insert_id,
					'orders_status_id' => $orders_status,
					'date_added' => 'now()',
					'customer_notified' => 1,
					'comments' => 'Paypal PENDING_REVIEW');
		        tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
		    }
		    unset($_SESSION['token_id']);
		}else{
		    $errormsg = $returndata['message'];
		    tep_db_query('delete from ' . TABLE_ORDERS . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_TOTAL . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_STATUS_HISTORY . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_PRODUCTS . ' where orders_id = "' . (int)$insert_id . '"');
		    $messageStack->add_session('checkout',$errormsg, 'error');
		    tep_redirect(tep_href_link(FILENAME_CHECKOUT, '', 'SSL', true, false));
		}
	   }else{
		    $errormsg = 'Payment unsuccessfull.';
		    tep_db_query('delete from ' . TABLE_ORDERS . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_TOTAL . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_STATUS_HISTORY . ' where orders_id = "' . (int)$insert_id . '"');
		    tep_db_query('delete from ' . TABLE_ORDERS_PRODUCTS . ' where orders_id = "' . (int)$insert_id . '"');
		    $messageStack->add_session('checkout',$errormsg, 'error');
		    tep_redirect(tep_href_link(FILENAME_CHECKOUT, '', 'SSL', true, false));
	   
	   }
    }
    function after_process() {
      return false;
    }
   function header_js() {
	$jstags = '<script defer="defer" src="https://www.paypal.com/sdk/js?client-id='.MODULE_PAYMENT_PAYPAL_SMC_CLIENT_ID.'&intent=authorize"></script>';
	return $jstags;
   }    
	function footer_js() {
		$jscode = '';
		if($this->enabled == true && (defined('MODULE_PAYMENT_PAYPAL_SMC_CLIENT_ID') && trim(MODULE_PAYMENT_PAYPAL_SMC_CLIENT_ID) != '')) {
		$jscode = '
			if(sel_method == \'paypal_smc\') {

			}

			';
		}
		return $jscode;
    } 
    //This function called when user select the radio button
    function setPageCode() {
		global $obj_catalog;
		$str_js = 'if(value == \'paypal_smc\'){
				  var smsbtn_chk = $(\'#smsbtn_chk\').val();
				  if(parseInt(smsbtn_chk) == 0){
					$(\'#process_payment\').css(\'display\', \'none\');
					$(\'#dynamic_process_btn\').css(\'display\', \'inline-block\');
					$(\'#dynamic_process_btn\').html(\'<div id="paypal-buttons"></div>\');
					$(\'#smsbtn_chk\').val(1);
					showSMCButton();
				  }else{
					$(\'#process_payment\').css(\'display\', \'none\');
					$(\'#dynamic_process_btn\').css(\'display\', \'inline-block\');

				  }
				}';
	if(is_object($obj_catalog))
		$obj_catalog->set_hooks_js($str_js, 'onselectAction');
    
	$str_js_functions = '
	function showSMCButton(){
		//=== Render paypal Buttons
		paypal.Buttons({
		//style:{ layout: "horizontal" },
		//=== Call your server to create an order
		createOrder: function(data, actions) {
		
			$(\'#loader-cart\').css(\'display\', \'block\');
			return fetch("ajax_handler.php?action=paypal_smc/create_pp_order", {
			  mode: "no-cors",
			  method: "POST",
			  headers: { "content-type": "application/json" },
			  body: JSON.stringify({ action: "create-order", })
			}).then(function(res) {
			  return res.json();
			}).then(function(data) {
			  if( !data.success && data.message ){
				console.error(data.message);
				$(\'#loader-cart\').css(\'display\', \'none\');
			  }
			  return data.id;
			});
		},
		 //=== Call your server to save the transaction
		onApprove: function(data, actions) {
		// Authorize the transaction
		  actions.order.authorize().then(function(authorization) {
		  var authorizationID = authorization.purchase_units[0].payments.authorizations[0].id;
			 if(authorizationID != \'\') {
			  $(\'#authorizationid\').val(authorizationID);
			  $(\'#smc_transaction_id\').val(data.orderID);
			  $(\'#smc_payerid\').val(data.payerID);
			  $("#checkout_payment" ).submit();
			 }else{
			   $(\'#loader-cart\').css(\'display\', \'none\');
			 }
		  });
		 },
		 onCancel: function(e) {
		 $(\'#loader-cart\').css(\'display\', \'none\');
		 
		 }
		}).render("#paypal-buttons");
	}';

	if(is_object($obj_catalog))
		$obj_catalog->set_hooks_js($str_js_functions, 'checkoutFunctions');

    }
    
    function get_error() {
      $error = array('title' => MODULE_PAYMENT_PAYPAL_SMC_TEXT_ERROR,
                     'error' => stripslashes(urldecode($_GET['error'])));
      return $error;
    }
    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_PAYPAL_SMC_STATUS'");
        $this->_check = tep_db_num_rows($check_query);
      }
      return $this->_check;
    }

    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Paypal Smart checkout Module', 'MODULE_PAYMENT_PAYPAL_SMC_STATUS', 'True', 'Do you want to accept payments through Paypal Smart checkout?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Api Client ID', 'MODULE_PAYMENT_PAYPAL_SMC_CLIENT_ID', 'Clint ID', 'Api Credentials client id for the Paypal Smart checkout service', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Api Secret Key', 'MODULE_PAYMENT_PAYPAL_SMC_SECRET_ID', 'Secret Key', 'Api Credentials secret key used for the Paypal Smart checkout service', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Mode', 'MODULE_PAYMENT_PAYPAL_SMC_TESTMODE', 'Test', 'Transaction mode used for processing orders', '6', '0', 'tep_cfg_select_option(array(\'Test\', \'Production\' ), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Processing Mode', 'MODULE_PAYMENT_PAYPAL_SMC_CCMODE', 'Authorize', 'Credit card processing mode', '6', '0', 'tep_cfg_select_option(array(\'Sale\', \'Authorize\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order Of Display', 'MODULE_PAYMENT_PAYPAL_SMC_SORT_ORDER', '200', 'The order in which this payment type is dislayed. Lowest is displayed first.', '6', '0' , now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PAYPAL_SMC_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
   }
    function remove() {
      $keys = '';
      $keys_array = $this->keys();
      for ($i=0; $i<sizeof($keys_array); $i++) {
        $keys .= "'" . $keys_array[$i] . "',";
      }
      $keys = substr($keys, 0, -1);
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in (" . $keys . ")");
    }

    function keys() {
      return array('MODULE_PAYMENT_PAYPAL_SMC_STATUS', 'MODULE_PAYMENT_PAYPAL_SMC_CLIENT_ID', 'MODULE_PAYMENT_PAYPAL_SMC_SECRET_ID', 'MODULE_PAYMENT_PAYPAL_SMC_TESTMODE', 'MODULE_PAYMENT_PAYPAL_SMC_CCMODE','MODULE_PAYMENT_PAYPAL_SMC_ORDER_STATUS_ID', 'MODULE_PAYMENT_PAYPAL_SMC_SORT_ORDER');
    }

    public static function rpc_create_pp_order() {
	    global $paypal_smc;
	  
		//=== Capture the input received from fetch() request
		$json_data = file_get_contents("php://input");
		$pp_post = json_decode($json_data, true);


	  //=== Check if request is to create an order
		if($pp_post['action'] == "create-order")
		{
			$_SESSION['payment'] = 'paypal_smc';
			if(isset($_SESSION['smc_transaction_id']) && $_SESSION['smc_transaction_id'] != ''){
			 unset($_SESSION['smc_transaction_id']);
			}
			$order = $paypal_smc->SMCcreateOrder();
			 print_r($order );
			//echo json_encode($order->result, JSON_PRETTY_PRINT);
		}

		//=== Check if request is to save an order
		elseif($pp_post['action'] == "save-order")
		{
			$_SESSION['smc_transaction_id'] = $pp_post['id'];
			$_SESSION['smc_payerid'] = $pp_post['payerid'];
			/*tep_redirect(tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'));
			exit;
			echo 'testere'.$post->id;
			echo 'ttttt'.$post->payerid;
			print_r($data);exit;
		   /*
			//=== Save order either by retrieving order from paypal OR the order we still have in session
			$order = paypalRequest::captureOrder($post->id);


		   // Prepare order query data & save order into database here

			//===  unset cart session
			unset($_SESSION["cart"]);*/

			echo json_encode(["success" => 1], JSON_PRETTY_PRINT);
		}
    }
    
	public static function SMCcreateOrder( $debug = false )
	{
	  global $response,$insert_id, $order, $messageStack, $paypal_smc;
	  
		lc_check_addon_class('order.php');
		$order = new order;

	  	$total =  number_format($order->info['total'], 2, '.', '');
		$arr_token =  $paypal_smc->getSMCTokenID();

		
		if(isset($arr_token['error'])) {
			 $json_string = json_encode(array('result' => $arr_token));
			 return json_decode($json_string);
		}
		$token_id = $arr_token['access_token'];
		$_SESSION['token_id'] = $token_id;
		//shipping methods form

		$currency_code = 'USD';
		$request_body["intent"] = "AUTHORIZE";
		$request_body["address"]['address_line_1'] = $order->delivery['street_address'];
		//$request_body["address"]['address_line_2'] =$order->delivery['street_address'];
		$request_body["address"]['admin_area_2'] = $order->delivery['city'];		
		$request_body["address"]['country_code'] = $order->delivery['country']['iso_code_2'];
		$request_body["address"]['postal_code'] = $order->delivery['postcode'];
		$request_body["address"]['admin_area_1'] = $order->delivery['state'];
		
		$pu_amount["currency_code"] = $currency_code;
		$pu_amount["value"] = $total;
		$purchase_units["amount"] = $pu_amount;
		$purchase_units["amount"] = $pu_amount;

		$purchase_units["shipping"]['address']['address_line_1'] = $order->delivery['street_address'];
		//$purchase_units["shipping"]['address']['address_line_1'] =$order->delivery['street_address'];
		$purchase_units["shipping"]['address']['admin_area_2'] = $order->delivery['city'];		
		$purchase_units["shipping"]['address']['country_code'] = $order->delivery['country']['iso_code_2'];
		$purchase_units["shipping"]['address']['postal_code'] = $order->delivery['postcode'];
		$purchase_units["shipping"]['address']['admin_area_1'] = $order->delivery['state'];
		//$purchase_units["shipping"]['address']['phone'] = "(123) 456-7890";
		
		$request_body["purchase_units"][] = $purchase_units;
		$json_setdata = json_encode($request_body);
		$returndata = $paypal_smc->SMCprocess($json_setdata,'v2/checkout/orders', $token_id);
		return $returndata;

	}
	function SMCprocess($jsondata='', $url_endpoint = '', $token='', $tp='POST')
	{
		$curl_url = $this->url.$url_endpoint;		
		$authorization = "Authorization: Bearer ".$token;
		$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $curl_url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $jsondata);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $tp);
			curl_setopt($ch, CURLOPT_SSLVERSION, 6);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			// proxy option for godaddy hosted customers (required)
			//curl_setopt($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");
			$response = curl_exec($ch);
			
			$err = curl_error($ch);
			$access_token="";
			if ($err) {
			  return "cURL Error #:" . $err;
			}

			//$res = json_decode($response,true);
			curl_close($ch);
			return  $response;
	}
	function getSMCTokenID() {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->url."v1/oauth2/token");
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERPWD, MODULE_PAYMENT_PAYPAL_SMC_CLIENT_ID.":".MODULE_PAYMENT_PAYPAL_SMC_SECRET_ID);
		curl_setopt($ch, CURLOPT_SSLVERSION, 6);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
		$result = curl_exec($ch);
		$err = curl_error($ch);
		$access_token="";
		if ($err) {
		  return array('error'=> "cURL Error #:" . $err);
		}
		else
		{
			$jsond = json_decode($result, true);
			if(isset($jsond['access_token'])) {
				return array('access_token' => $jsond['access_token'], 'retval'=>$jsond);
			} else {
			  return array('error'=> $jsond);
			}
		}
     }

  }

// Paypal Smart checkout Consolidated Credit Card Checkbox Implementation
?>