<?php

class easypay extends base {
  
  var $code;
  var $title;
  var $description;
  var $enabled;
  var $refcode;
  
  
  function easypay() {
    global $order, $messageStack;
    $this->code = 'easypay';
    if (IS_ADMIN_FLAG === true) {
		// Payment Module title in Admin
		$this->title = MODULE_PAYMENT_EASYPAY_TEXT_ADMIN_TITLE;
		if (IS_ADMIN_FLAG === true && defined('MODULE_PAYMENT_EASYPAY_IPN_DEBUG') && MODULE_PAYMENT_EASYPAY_IPN_DEBUG != 'Off') 
		{
			$this->title .= '<span class="alert"> (debug mode active)</span>';
		}
		if (IS_ADMIN_FLAG === true && MODULE_PAYMENT_EASYPAY_TESTING == 'Test')
		{
			$this->title .= '<span class="alert"> (dev/test mode active)</span>';
		}
    } else {
      $this->title = "Pay by Credit Card"; // Payment Module title in Catalog
    }
    $this->description = MODULE_PAYMENT_EASYPAY_TEXT_DESCRIPTION;
    $this->sort_order = MODULE_PAYMENT_EASYPAY_SORT_ORDER;
    $this->enabled = ((MODULE_PAYMENT_EASYPAY_STATUS == 'True') ? true : false);
	
    if ((int)MODULE_PAYMENT_EASYPAY_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_EASYPAY_ORDER_STATUS_ID;
    }
	
    if (is_object($order)) $this->update_status();

    $this->form_action_url = 'https://securepayments.telemoneyworld.com/easypay2/paymentpage.do';

    // verify table structure
    if (IS_ADMIN_FLAG === true) $this->tableCheckup();
  }



  function update_status() {
  	if ( is_object($$module) || ($_SESSION['shipping']['id'] == 'expresscod_expresscod') ) {

        $this->enabled = false;}			

    
  }

  function javascript_validation() {
    return false;
  }

  function selection() {
    return array('id' => $this->code,
                 'module' => $this->title,
                 'icon' => MODULE_PAYMENT_EASYPAY_TEXT_CATALOG_LOGO
                 );
  }

  function pre_confirmation_check() {
    return false;
  }

  function confirmation() {
    return false;
  }

  function process_button() {
	 global $db, $order, $currencies, $currency;
	 
	 $ref = "BLACK_TACTICAL_EP-".time();
	 $this->refcode = $ref;
	 
	 $submit_data = array(
		"mid" => "112201538284",
		"ref" => $ref,
		"amt" => number_format($order->info['total'], 2),
		//"amt" => 0.10,
		"cur" => "SGD",
		"returnurl" => zen_href_link(FILENAME_CHECKOUT_PROCESS, 'referer=easypay&oid='.base64_encode($ref), 'SSL'),
		"statusurl" => zen_href_link('easypay_main_handler.php', '', 'SSL',false,false,true),
	 );
	 foreach($submit_data as $key => $value) {
      	$process_button_string .= zen_draw_hidden_field($key, $value) . "\n";
     }
     
    $db->Execute("delete from " . TABLE_EASYPAY . " where session_id = '" . $ref . "'");

    $sql = "insert into " . TABLE_EASYPAY . " (session_id, status,amount,datadump) values (
            '" . $ref . "',
            'pending',
            ".number_format($order->info['total'], 2).",
            '".base64_encode(var_export($order, true))."'
            )";

    $db->Execute($sql);
     
     
	return $process_button_string;
  }

  function before_process() {
    global $db,$order_total_modules,$order;

    if (isset($_GET['referer']) && $_GET['referer'] == 'easypay' && isset($_GET['oid'])) {
    	
    	$ref = base64_decode($_GET['oid']);
    	$this->refcode = $ref;
    	

		$count = 0;
		while ($count < 5)
		{
			$trans = $db->Execute("select * from " . TABLE_EASYPAY . " where session_id='".$ref."'");
			if($trans->fields['status'] == "YES")
			{
				break;	
			}
			else if($trans->fields['status'] == "pending")
			{
				sleep(2);
			}else if($trans->fields['status'] != "YES" || $count == 4)
			{
				zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'));
				break;
			} 
			$count++;
		}
    	   
    }
  }

  function check_referrer($zf_domain) {
    return true;
  }

  function after_process() {
    global $insert_id, $db;
    
    $sql = "update " . TABLE_EASYPAY . " set 
					order_id=:order_id
					where session_id = :ref";
    $sql = $db->bindVars($sql, ':order_id', $insert_id, 'integer');
    $sql = $db->bindVars($sql, ':ref', $this->refcode, 'string');
    $db->Execute($sql);
    
    
    $sql2 = "insert into " . TABLE_ORDERS_STATUS_HISTORY . " (comments, orders_id, orders_status_id, customer_notified, date_added) values (:orderComments, :orderID, :orderStatus, -1, now() )";
    $sql2 = $db->bindVars($sql2, ':orderComments', 'Credit Card payment.  TransRef: ' . $this->refcode . '.', 'string');
    $sql2 = $db->bindVars($sql2, ':orderID', $insert_id, 'integer');
    $sql2 = $db->bindVars($sql2, ':orderStatus', 1, 'integer');
    $db->Execute($sql2);
    
    
  }
  
  function output_error() {
    return false;
  }

  function check() {
    global $db;
    if (!isset($this->_check)) {
      $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_EASYPAY_STATUS'");
      $this->_check = $check_query->RecordCount();
    }
    return $this->_check;
  }

  function install() {
    global $db, $messageStack;
    if (defined('MODULE_PAYMENT_EASYPAY_STATUS')) {
      $messageStack->add_session('EASYPAY2 Payments module already installed.', 'error');
      zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=EASYPAY', 'NONSSL'));
      return 'failed';
    }

    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable EASYPAY Module', 'MODULE_PAYMENT_EASYPAY_STATUS', 'True', 'Do you want to accept EASYPAY payments?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
    $db->Execute("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_EASYPAY_ORDER_STATUS_ID', '2', 'Set the status of orders made with this payment module to this value', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
    $db->Execute("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_EASYPAY_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
      
    $this->notify('NOTIFY_PAYMENT_EASYPAY_INSTALLED');
  }

  function remove() {
    global $db;
    $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key LIKE 'MODULE\_PAYMENT\_EASYPAY\_%'");
    $this->notify('NOTIFY_PAYMENT_EASYPAY_UNINSTALLED');
  }
  /**
   * Internal list of configuration keys used for configuration of the module
   *
   * @return array
    */
  function keys() {
    $keys_list = array(
                       'MODULE_PAYMENT_EASYPAY_STATUS',
                       'MODULE_PAYMENT_EASYPAY_BUSINESS_ID',
                       'MODULE_PAYMENT_EASYPAY_PDTTOKEN',
                       'MODULE_PAYMENT_EASYPAY_CURRENCY',
                       'MODULE_PAYMENT_EASYPAY_ZONE',
                       'MODULE_PAYMENT_EASYPAY_PROCESSING_STATUS_ID',
                       'MODULE_PAYMENT_EASYPAY_ORDER_STATUS_ID',
                       'MODULE_PAYMENT_EASYPAY_REFUND_ORDER_STATUS_ID',
                       'MODULE_PAYMENT_EASYPAY_SORT_ORDER',
                       'MODULE_PAYMENT_EASYPAY_DETAILED_CART',
                       'MODULE_PAYMENT_EASYPAY_ADDRESS_OVERRIDE' ,
                       'MODULE_PAYMENT_EASYPAY_ADDRESS_REQUIRED' ,
                       'MODULE_PAYMENT_EASYPAY_PAGE_STYLE' ,
                       'MODULE_PAYMENT_EASYPAY_HANDLER',
                       'MODULE_PAYMENT_EASYPAY_IPN_DEBUG',
                        );

    // EASYPAY testing/debug options go here:
    if (IS_ADMIN_FLAG === true) {
      if (isset($_GET['debug']) && $_GET['debug']=='on') {
        $keys_list[]='MODULE_PAYMENT_EASYPAY_DEBUG_EMAIL_ADDRESS';  /* this defaults to store-owner-email-address */
      }
    }
    return $keys_list;
  }

  function tableCheckup() {
    global $db, $sniffer;
    $fieldOkay1 = (method_exists($sniffer, 'field_type')) ? $sniffer->field_type(TABLE_EASYPAY, 'txn_id', 'varchar(20)', true) : -1;
    $fieldOkay2 = ($sniffer->field_exists(TABLE_EASYPAY, 'module_name')) ? true : -1;
    $fieldOkay3 = ($sniffer->field_exists(TABLE_EASYPAY, 'order_id')) ? true : -1;

    if ($fieldOkay1 == -1) {
      $sql = "show fields from " . TABLE_EASYPAY;
      $result = $db->Execute($sql);
      while (!$result->EOF) {
        if  ($result->fields['Field'] == 'txn_id') {
          if  ($result->fields['Type'] == 'varchar(20)') {
            $fieldOkay1 = true; // exists and matches required type, so skip to other checkup
          } else {
            $fieldOkay1 = $result->fields['Type']; // doesn't match, so return what it "is"
            break;
          }
        }
        $result->MoveNext();
      }
    }

  }

}
