<?php


class ControllerExtensionPaymentSkrill extends Controller {
	public function index() {

		//include 'pbb/security.php';

		//d_quickcheckout_fix
		require_once 'pbb/security.php';
		///

		$this->load->model('checkout/order');

		$this->load->language('extension/payment/skrill');

		$data['button_confirm'] = $this->language->get('button_confirm');

		//$data['action'] = 'https://testsecureacceptance.cybersource.com/pay';
		$data['action'] = 'https://secureacceptance.cybersource.com/pay';

		$data['pay_to_email'] = $this->config->get('payment_skrill_email');
		$data['platform'] = '31974336';

		$uniqid = uniqid();
		$signed_date_time = gmdate("Y-m-d\TH:i:s\Z");

		$data['transaction_uuid'] = $uniqid;
		$data['signed_date_time'] = $signed_date_time;
		$data['secret'] = $this->config->get('payment_skrill_secret');


		$data['description'] = $this->config->get('config_name');
		$data['transaction_id'] = $this->session->data['order_id'];
		$data['return_url'] = $this->url->link('checkout/success');
		$data['cancel_url'] = $this->url->link('checkout/checkout', '', true);
		$data['status_url'] = $this->url->link('extension/payment/skrill/callback');
		$data['language'] = $this->session->data['language'];
		$data['logo'] = $this->config->get('config_url') . 'image/' . $this->config->get('config_logo');

		$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);


		// override with default billing address for all payment details
		$this->load->model('checkout/order');
		$this->load->model('account/customer');
		$this->load->model('account/address');

		$orderDetails =  $this->model_checkout_order->getOrderCustomerID($this->session->data['order_id']);
		$order_customer_id = $orderDetails[0]['customer_id'];
		$customer_infos = $this->model_account_customer->getCustomer($order_customer_id);
		
		if(!empty($customer_infos)) {
			$default_addressid = $customer_infos['address_id'];
		} else {
			$default_addressid = 0;
		}

		$address_info_d = $this->model_account_address->getAddress($default_addressid);

		if(!empty($address_info_d)) {
			$order_info['payment_firstname'] 	= $address_info_d['firstname'];
			$order_info['payment_lastname'] 	= $address_info_d['lastname'];
			$order_info['payment_address_1'] 	= $address_info_d['address_1'];
			$order_info['payment_address_2']	= $address_info_d['address_2'];
			$order_info['payment_postcode'] 	= $address_info_d['postcode'];
			$order_info['payment_city'] 			= $address_info_d['city'];
			$order_info['payment_zone'] 			= $address_info_d['zone'];
			$order_info['payment_iso_code_2'] = $address_info_d['iso_code_2'];
			$order_info['payment_iso_code_3'] = $address_info_d['iso_code_3'];
		}


		$data['pay_from_email'] = $order_info['email'];
		$data['phone_number'] = $order_info['telephone'];

		$data['firstname'] = $order_info['payment_firstname'];
		$data['lastname'] = $order_info['payment_lastname'];
		$data['address'] = $order_info['payment_address_1'];
		$data['address2'] = $order_info['payment_address_2'];
		$data['postal_code'] = $order_info['payment_postcode'];
		$data['city'] = $order_info['payment_city'];
		$data['state'] = $order_info['payment_zone'];
		$data['country'] = $order_info['payment_iso_code_3'];

		$data['amount'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false);
		$data['currency'] = $order_info['currency_code'];

		$amount_value = number_format($order_info['total'], 2, '.', '');
		$data['amount_value'] = $amount_value;

//print_r($order_info);
		/** custom **/

		$payment_address_1 	= html_entity_decode(substr($order_info['payment_address_1'], 0, 58));
		$payment_address_2 	= html_entity_decode(substr($order_info['payment_address_2'], 0, 58));
		$payment_city 			= html_entity_decode($order_info['payment_city']);
		$payment_zone_code 	= html_entity_decode($order_info['payment_zone']);
		$payment_postcode 	= html_entity_decode($order_info['payment_postcode']);
		$payment_iso_code_2 = html_entity_decode($order_info['payment_iso_code_2']);
		$payment_firstname 	= html_entity_decode($order_info['payment_firstname']);
		$payment_lastname 	= html_entity_decode($order_info['payment_lastname']);

		$email 							= html_entity_decode($order_info['email']);
		$telephone 					= html_entity_decode($order_info['telephone']);

		$data['payment_address_1'] 	= $payment_address_1;
		$data['payment_address_2'] 	= $payment_address_2;
		$data['payment_city'] 			= $payment_city;
		$data['payment_zone_code'] 	= $payment_zone_code;
		$data['payment_postcode'] 	= $payment_postcode;
		$data['telephone'] 					= $telephone;
		$data['payment_iso_code_2'] = $payment_iso_code_2 ;
		$data['email'] 							= $email;
		$data['payment_firstname'] 	= $payment_firstname;
		$data['payment_lastname'] 	= $payment_lastname;

		$data['callbackurl'] = $this->url->link('payment/skrill/callback');
		/** end custom **/


		$products = '';

		foreach ($this->cart->getProducts() as $product) {
			$products .= $product['quantity'] . ' x ' . $product['name'] . ', ';
		}

		$data['detail1_text'] = $products;
		$data['order_id'] = $this->session->data['order_id'];

		$address_f = $order_info['payment_address_1'] . ', ' . $order_info['payment_address_2'];
		$full_address = substr($address_f, 0, 58);

		$sign_para = array (
	    'access_key' => $this->config->get('payment_skrill_email'),
	    'profile_id' => $this->config->get('payment_skrill_secret'),
	    'transaction_uuid' => $uniqid,
	    'signed_field_names' => 'access_key,profile_id,transaction_uuid,signed_field_names,unsigned_field_names,signed_date_time,locale,transaction_type,reference_number,amount,currency,bill_to_address_line1,bill_to_address_line2,bill_to_address_city,bill_to_address_postal_code,bill_to_phone,bill_to_address_country,bill_to_email,bill_to_forename,bill_to_surname',
	    'unsigned_field_names' => '',
	    'signed_date_time' => $signed_date_time,
	    'locale' => 'en',
	    'transaction_type' => 'sale',
	    'reference_number' => $this->session->data['order_id'],
	    'amount' => $amount_value,
			'currency' => $order_info['currency_code'],
	    'bill_to_address_line1' => $payment_address_1,
			'bill_to_address_line2' => $payment_address_2,
			'bill_to_address_city' => $payment_city,
			//'bill_to_address_state' => $order_info['payment_zone'],
			'bill_to_address_postal_code' => $payment_postcode,
			'bill_to_phone' => $telephone,
			'bill_to_address_country' => $payment_iso_code_2,
			'bill_to_email' => $email,
			'bill_to_forename' => $payment_firstname,
			'bill_to_surname' => $payment_lastname,
	    'submit' => 'Submit'
		);




		$data['signature'] = sign($sign_para);
		//echo $this->load->view('extension/payment/skrill', $data);
		return $this->load->view('extension/payment/skrill', $data);

	}

	public function callback() {


		/* test webhook */

		// $data = print_r($this->request->post,true);
		// $filename = date('YmdHis').".txt";
    // if (!file_exists($filename)) {
    //     $fh = fopen($filename, 'w') or die("Can't create file");
    // }
    // $ret = file_put_contents($filename, $data, FILE_APPEND | LOCK_EX);
    // if($ret === false) {
    //     die('There was an error writing this file');
    // }
    // else {
    //     //echo "$ret bytes written to file";
    // }
		/* test webhook */



		if (isset($this->request->post['req_reference_number'])) {
			$order_id = $this->request->post['req_reference_number'];
		} else {
			$order_id = 0;
		}

		$this->load->model('checkout/order');

		$order_info = $this->model_checkout_order->getOrder($order_id);

		if ($order_info) {
			//$this->model_checkout_order->addOrderHistory($order_id, $this->config->get('config_order_status_id'));

			$verified = false;

			if ( $this->request->post['decision'] && $this->request->post['decision'] == "ACCEPT" ) {

				if( $this->request->post['decision'] !="" ) {
					$verified = true;
				}

			}

			if ($verified) {

				$comment = 'Transaction Reference Number: ' . $this->request->post['auth_trans_ref_no'] . ' <br>Card Number: ' .$this->request->post['req_card_number'] . '<br>Message: ' . $this->request->post['message'];

				$this->model_checkout_order->addOrderHistory($order_id, $this->config->get('payment_skrill_order_status_id'), $comment, false);


				$this->load->model('account/customer');
				$customer_info = $this->model_account_customer->getCustomer($order_info['customer_id']);
				$customer_id = $customer_info['customer_id'];

				$this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE customer_id = '" . (int)$customer_id . "'");

				// if($this->cart->clear()) {
				// 	$hello = " / cleared";
				// } else {
				// 	$hello = " / none clear";
				// }

				// /* test webhook */
				//
				// $data = print_r($this->request->post,true);
				// $filename = date('YmdHis').".txt";
		    // if (!file_exists($filename)) {
		    //     $fh = fopen($filename, 'w') or die("Can't create file");
		    // }
		    // $ret = file_put_contents($filename, $data.$hello, FILE_APPEND | LOCK_EX);
		    // if($ret === false) {
		    //     die('There was an error writing this file');
		    // }
		    // else {
		    //     //echo "$ret bytes written to file";
		    // }
				/* test webhook */

			}
		}



		$this->response->addHeader('HTTP/1.1 200 OK');
		//$this->response->addHeader('Content-Type: application/json');


	}
}
