<?php

/**
 * BillDesk Payment Module
 *
 * @package paymentMethod
 * @copyright Copyright 2003-2018 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: Drbyte Sun Jan 7 21:30:21 2018 -0500 Modified in v1.5.6 $
 */

use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Message;
use io\billdesk\client\hmacsha256\BillDeskJWEHS256Client;
use io\billdesk\client\hmacsha256\JWESymmetricHelper;
use io\billdesk\client\hmacsha256\Config;
use io\billdesk\client\hmacsha256\JWEHS256Helper;
use Symfony\Polyfill\Intl\Idn\Info;

error_log("__DIR__" . __DIR__);
include_once(__DIR__ . '/billdesk/vendor/autoload.php');
include_once(__DIR__ . '/billdesk/logger.php');

if (!defined('TABLE_BILLDESK_PAYMENTS')) define('TABLE_BILLDESK_PAYMENTS', DB_PREFIX . 'billdesk');
class billdesk extends base
{
  var $code, $title, $description, $enabled;

  // class constructor
  function __construct()
  {
    global $order;

    $this->code = 'billdesk';
    $this->title = "BillDesk";
    $this->description = '<strong>BillDesk Payments Module </strong>';
    $this->sort_order = defined('MODULE_PAYMENT_BILLDESK_SORT_ORDER') ? MODULE_PAYMENT_BILLDESK_SORT_ORDER : null;
    $this->enabled = (defined('MODULE_PAYMENT_BILLDESK_STATUS') && MODULE_PAYMENT_BILLDESK_STATUS == 'True');

    if (defined('MODULE_PAYMENT_BILLDESK_ORDER_STATUS_ID') && (int)MODULE_PAYMENT_BILLDESK_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_BILLDESK_ORDER_STATUS_ID;
    }
    if (IS_ADMIN_FLAG === true) {
      $this->title = "BillDesk";
      $this->tableCheckup();
    }
    if (is_object($order)) $this->update_status();
  }

  // class methods
  function update_status()
  {
    global $order, $db;

    // other status checks?
    if ($this->enabled) {
      // other checks here
    }
  }

  function javascript_validation()
  {
    return true;
  }

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

  function pre_confirmation_check()
{
    return true;
}

function confirmation()
  {
   /**
    *global $_POST;
    *$confirmation = array('title' => $title);
    *return $confirmation; */
     $lang = $GLOBALS['define'] ?? [];
    $title = $lang['MODULE_PAYMENT_BILLDESK_TEXT_DESCRIPTION'] ?? 'BillDesk';

    $confirmation = array(
        'title' => $title
    );
    return $confirmation;

  }



  /**
   * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
   * This sends the data to the payment gateway for processing.
   * (These are hidden fields on the checkout confirmation page)
   *
   * @return string
   */
  function process_button()
  {
    return true;
  }


  function before_process()
  {
    global $order, $messageStack, $db;
    $logger = BillDeskLogger::logger("Before_process");

    //$logger->info("Order id in before process: " . $order->info['order_id']);
    $logger->info("Order total in before process: " . $order->info['total']);
    $logger->info("Child window value from session: ", [isset($_SESSION['childWindow']) ? $_SESSION['childWindow'] : "notset"]);
    $logger->info("Incoming Request (POST):", [$_POST]);
    $logger->info("Incoming Request (GET):", [$_GET]);
    $logger->info("Incoming Request (REQUEST):", [$_REQUEST]);

    if (!isset($_REQUEST['transaction_response']) && isset($_SESSION['transaction_response'])) {
    $_REQUEST['transaction_response'] = $_SESSION['transaction_response'];
    unset($_SESSION['transaction_response']); // optional cleanup
    $logger->info("Used fallback transaction_response from session");
   }
    if (isset($_REQUEST['transaction_response'])) {

      $logger->info("before_process: transaction_response:", [$_REQUEST['transaction_response']]);
      if (MODULE_PAYMENT_BILLDESK_CHILD_WINDOW == 'True' && !isset($_SESSION['childWindow'])) {
        $_SESSION['childWindow'] = true;
        echo '<html> <head> <script> function closeWindow() { window.close(); } </script> </head> <body onload="closeWindow()"> </body> </html>';
        exit();
      } else {
        $transaction_response = $_REQUEST['transaction_response'];
        $logger->info("Response received from PG IN after process function: ", [$transaction_response]);
        if ($transaction_response != "" || $transaction_response != null) {
          $merchantid = MODULE_PAYMENT_BILLDESK_MERCHANT_ID;
          $clientid = MODULE_PAYMENT_BILLDESK_CLIENT_ID;
          $encryptionKey = MODULE_PAYMENT_BILLDESK_ENCRYPTION_KEY;
          $signingKey = MODULE_PAYMENT_BILLDESK_SIGNING_KEY;
          $encryptionKeyId = MODULE_PAYMENT_BILLDESK_KEY_ID;//"HMAC";
          $signingKeyId = "AES_DIR";

          // ✅ Safe logging of configuration (do NOT log keys in plain text)
          $logger->info("Config Values:");
          $logger->info("Merchant ID: $merchantid");
          $logger->info("Client ID: $clientid");
          $logger->info("Encryption Key: $encryptionKey");
          $logger->info("Signing Key: $signingKey");
          $logger->info("Encryption Key ID: $encryptionKeyId");
          $logger->info("Signing Key ID: $signingKeyId");


           $client = new JWESymmetricHelper(
                                 $encryptionKey,
                                 $clientid,
                                 $encryptionKeyId,
                                 $logger,
                                 $signingKey,
                                 $signingKeyId
                             );
          $logger->debug("Raw transaction_response: $transaction_response");

          $jws = $client->verifyAndDecrypt($transaction_response);
          $txn = json_decode($jws);
          $logger->debug("Encrypted_response :" . json_encode($txn));




          $success_url = zen_href_link(FILENAME_CHECKOUT_SUCCESS, '', 'SSL', true, false);
          if ($txn->amount == $order->info['total']) {
            $sql_data_array = array(
              'order_id' => $txn->additional_info->additional_info1,
              'billdesk_order_id' => $txn->orderid,
              'transaction_id' => $txn->orderid,
              'transaction_date' => $txn->transactionid,
              'currency' => $txn->transaction_date,
              'amount' => $txn->amount,
            );
            zen_db_perform(TABLE_BILLDESK_PAYMENTS, $sql_data_array);
            if ($txn->auth_status === '0300') {
              //$order->info['order_status'] = MODULE_PAYMENT_BILLDESK_PROCESSING_STATUS;

              // $sql_array = array(
              //   'orders_status' => MODULE_PAYMENT_BILLDESK_ORDER_STATUS_ID,
              //   'orders_date_finished' => 'now()'
              // );
              // $db->perform(TABLE_ORDERS, $sql_array, 'update', "orders_id = " . $txn->additional_info->additional_info1);

              // Update order history
              zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, array(
                'orders_id' => $txn->additional_info->additional_info1,
                'orders_status_id' => MODULE_PAYMENT_BILLDESK_ORDER_STATUS_ID,
                'date_added' => 'now()',
                'customer_notified' => 0,
                'comments' => 'Transaction Id -' . $txn->transactionid,
              ));


              zen_update_orders_history($txn->additional_info->additional_info1, null, null, 2, -1);
              $_SESSION['cart']->reset(true);
              zen_redirect($success_url);
              // return true;
            } else if ($txn->auth_status === '0002') {
              $logger->info('txn->auth_status === 0002');
              $messageStack->add_session('shopping_cart', 'Description: ' . $txn->transaction_error_desc, 'error');
              $messageStack->add_session('shopping_cart', 'Type: '  . $txn->transaction_error_type, 'error');
              $messageStack->add_session('shopping_cart', 'Code: '  . $txn->transaction_error_code, 'error');
              zen_redirect(zen_href_link(FILENAME_SHOPPING_CART, '', 'NONSSL'));
            } else if ($txn->auth_status === '0399') {
              $logger->info('txn->auth_status === 0399');
              $messageStack->add_session('shopping_cart', 'Error description: ' . $txn->transaction_error_desc, 'error');
              $messageStack->add_session('shopping_cart', 'Error type: '  . $txn->transaction_error_type, 'error');
              $messageStack->add_session('shopping_cart', 'Error code: '  . $txn->transaction_error_code, 'error');
              zen_redirect(zen_href_link(FILENAME_SHOPPING_CART, '', 'NONSSL'));
            }
          } else {
            exit();
          }
        }
        if (isset($_SESSION['childWindow'])) {
          unset($_SESSION['childWindow']);
        }
        exit();
      }
      // success
      // return true;
    } else {
      if (isset($_SESSION['childWindow'])) {
        unset($_SESSION['childWindow']);
      }
      $logger->info("before_process: transaction_response not set");
    }
    if (isset($_REQUEST['transaction_status'])) {
      $transaction_response = $_REQUEST['transaction_status'];
      $logger->info("Response received: " . $transaction_response);
      if ($transaction_response == 111) {
        zen_update_orders_history($order->info['order_id'], null, null, 1, -1);
        $messageStack->add_session('shopping_cart', 'Modal cosed by user.',  'error');
        zen_redirect(zen_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
      }
    }
    return false;
  }

  function after_process()
  {
    global $insert_id, $order, $messageStack;
    $logger = BillDeskLogger::logger("After_process");
    $logger->info("Inside after_process() function: " . $order->info['order_id']);
    zen_update_orders_history($order->info['order_id'], null, null, 1, -1);
    $res = $this->createorder($order);
    if ($res['status'] == 'ACTIVE') {
      if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
        $protocol = 'https://';
      } else {
        $protocol = 'http://';
      }
?>
      <script src="<?php echo $protocol; ?>code.jquery.com/jquery-latest.min.js"></script>
      <script type="text/javascript">
        jQuery(document).ready(function() {
          var flowtype = "payments";
          const flowConfig = {
            merchantId: '<?php echo $res['mercid'] ?>',
            bdOrderId: '<?php echo $res['bdorderid'] ?>',
            authToken: '<?php echo $res['links'][1]['headers']['authorization'] ?>',
          }
          var childwindow = '<?php echo MODULE_PAYMENT_BILLDESK_CHILD_WINDOW ?>';
          var retrycount = '<?php echo MODULE_PAYMENT_BILLDESK_RETRY_COUNT ?>';
          if (childwindow == "True") {
            flowConfig.childWindow = true;
          } else {
            flowConfig.childWindow = false;
          }
          flowConfig.retryCount = Number(retrycount);

          console.log("Flowconfig: ", flowConfig);
          var onSdkModalClosed = function(response) {
            if (response.status === 111) {
              const form = document.createElement('form');
              form.method = 'POST';
              form.action = '<?php echo $this->before_process(); ?>';
              const hiddenField = document.createElement('input');
              hiddenField.type = 'hidden';
              hiddenField.name = 'transaction_status';
              hiddenField.value = response.status;
              form.appendChild(hiddenField);

              document.body.appendChild(form);
              form.submit();
            }
            if (response) {
              console.log("SDK Modal closed: ", response);
              const form = document.createElement('form');
              form.method = 'POST';
              form.action = '<?php echo $this->before_process(); ?>';
              const hiddenField = document.createElement('input');
              hiddenField.type = 'hidden';
              hiddenField.name = 'transaction_response';
              if (response.txnResponse.terminal_state == 'N') {
                hiddenField.value = response.txnResponse.terminal_state;
              } else {
                hiddenField.value = response.txnResponse.transaction_response;
              }
              form.appendChild(hiddenField);

              document.body.appendChild(form);
              form.submit();
            }
          }

          var sdkConfig = {
            responseHandler: onSdkModalClosed,
            merchantLogo: '<?php echo MODULE_PAYMENT_BILLDESK_MERCHANT_LOGO ?>',
            flowConfig: flowConfig,
            flowType: flowtype,
          }
          if ('<?php echo MODULE_PAYMENT_BILLDESK_ENVIRONMENT ?>' == 'UAT') {
            var script = document.createElement('script');
            script.type = "module";
            script.src = 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.esm.js';
            document.body.appendChild(script);

            var script1 = document.createElement('script');
            script1.nomodule = "";
            script1.src = 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.js';
            document.body.appendChild(script1);

            var head = document.getElementsByTagName('HEAD')[0];
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.type = 'text/css';
            link.href = 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.css';
            head.appendChild(link);
          } else {
            var script = document.createElement('script');
            script.type = "module";
            script.src = 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.esm.js';
            document.body.appendChild(script);

            var script1 = document.createElement('script');
            script1.nomodule = "";
            script1.src = 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.js';
            document.body.appendChild(script1);

            var head = document.getElementsByTagName('HEAD')[0];
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.type = 'text/css';
            link.href = 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.css';
            head.appendChild(link);
          }
          console.log("SDK config: ", sdkConfig);
          //loadBillDeskSdk(sdkConfig);
          function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
          }
          sleep(5000).then(() => {
            loadBillDeskSdk(sdkConfig);
          });
        })
      </script>

<?php
      die();
    } else {
      $messageStack->add_session('shopping_cart', 'Error message: ' . $res['message'], 'error');
      $messageStack->add_session('shopping_cart', 'Error code: '  . $res['error_code'], 'error');
      $messageStack->add_session('shopping_cart', 'Error type: '  . $res['error_type'],  'error');
      zen_redirect(zen_href_link(FILENAME_SHOPPING_CART, '', 'SSL'));
    }
    return false;
  }

  public function createOrder($order)
{
    $logger = BillDeskLogger::logger("Create Order");
    global $currencies;

    $logger->info('Creating BillDesk order...');

    $amount = number_format($order->info['total'], 2, '.', '');
    $currency_code = $order->info['currency'];
    $order_id = $order->info['order_id'];
    $customer_email = $order->customer['email_address'];
    $customer_phone = $order->customer['telephone'];

    $logger->info("Order ID: $order_id");
    $logger->info("Amount: $amount $currency_code");
    $logger->info("Customer Email: $customer_email");
    $logger->info("Customer Phone: $customer_phone");

    $logger->info("Inside Create Order");

    $currency_map = array(
        'INR' => '356', 'USD' => '840', 'EUR' => '978', 'JPY' => '392',
        'AUD' => '036', 'HKD' => '344', 'MYR' => '458', 'SGD' => '702',
        'NZD' => '554'
    );

    $currency = isset($currency_map[$currency_code]) ? $currency_map[$currency_code] : '356';
    $OrderTotal = $order->info['total'];
    //$returnUrl = zen_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL');
      $returnUrl = zen_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL', false);

    // Force SID from session manually if not already defined
    if (!defined('SID') || SID === '') {
        $sid = (defined('SESSION_NAME') && isset($_GET[SESSION_NAME])) ? SESSION_NAME . '=' . $_GET[SESSION_NAME] : session_name() . '=' . session_id();
    } else {
        $sid = SID;
    }

    if ($sid != '') {
        $returnUrl .= (strpos($returnUrl, '?') !== false ? '&' : '?') . $sid;
    }

    $logger->info("Return URL generated: " . $returnUrl);


    $ip = getenv('HTTP_CLIENT_IP') ?:
          getenv('HTTP_X_FORWARDED_FOR') ?:
          getenv('HTTP_X_FORWARDED') ?:
          getenv('HTTP_FORWARDED_FOR') ?:
          getenv('HTTP_FORWARDED') ?:
          getenv('REMOTE_ADDR');
    $ipaddress = strtok($ip, ",");
    $bd_version = "pluginv,1.0.7";
    $userAgent = $_SERVER['HTTP_USER_AGENT'];

    $merchantid = MODULE_PAYMENT_BILLDESK_MERCHANT_ID;
    $clientid = MODULE_PAYMENT_BILLDESK_CLIENT_ID;
    $encryptionKey = MODULE_PAYMENT_BILLDESK_ENCRYPTION_KEY;
    $signingKey = MODULE_PAYMENT_BILLDESK_SIGNING_KEY;
    $encryptionKeyId = MODULE_PAYMENT_BILLDESK_KEY_ID;
    $signingKeyId = "AES_DIR";

    // ✅ Safe logging of configuration (do NOT log keys in plain text)
    $logger->info("Config Values:");
    $logger->info("Merchant ID: $merchantid");
    $logger->info("Client ID: $clientid");
    $logger->info("Encryption Key: $encryptionKey");
    $logger->info("Signing Key: $signingKey");
    $logger->info("Encryption Key ID: $encryptionKeyId");
    $logger->info("Signing Key ID: $signingKeyId");

    $config = new Config();
    $config->setClientId($clientid);
    $config->setMerchantId($merchantid);
    $config->setEncryptionKeyBase64($encryptionKey);
    $config->setSigningKeyBase64($signingKey);
    $config->setEncryptionKeyId($encryptionKeyId);
    $config->setSigningKeyId($signingKeyId);

    $endpoint = (MODULE_PAYMENT_BILLDESK_ENVIRONMENT === 'UAT')
                ? 'https://uat1.billdesk.com/u2'
                : 'https://api.billdesk.com';

    $logger->info("Environment endpoint: $endpoint");

    try {
        $client = new BillDeskJWEHS256Client($config, $endpoint);
        $client->setLogger($logger);

        $request = array(
            'mercid' => $merchantid,
            'orderid' => $order_id,
            'amount' => $OrderTotal,
            'order_date' => date_format(new \DateTime(), DATE_W3C),
            'currency' => $currency,
            'ru' => $returnUrl,
            'itemcode' => MODULE_PAYMENT_BILLDESK_ITEM_CODE,
            'device' => array(
                'init_channel' => 'internet',
                'ip' => $ipaddress,
                'user_agent' => $userAgent
            ),
            'additional_info' => array(
                'additional_info1' => $order_id,
                'additional_info7' => 'platform,zencart_' . PROJECT_VERSION_MAJOR . '.' . PROJECT_VERSION_MINOR . "-" . $bd_version,
            ),
        );

        $logger->info("Create order request: " . json_encode($request));

        $response = $client->createOrder($request);
        $results = $response->getResponse();
        $logger->info("Create order response: " . json_encode($results));

        return json_decode(json_encode($results), true);

    } catch (RequestException $ex) {
        $logger->error("Exception on create order: " . $ex->getMessage());
        if ($ex->hasResponse()) {
            $logger->error("Server response: " . $ex->getResponse());
        }
    } catch (\Exception $ex) {
        $logger->error("Unexpected exception: " . $ex->getMessage());
    }

    return false;
}



  function get_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_BILLDESK_STATUS'");
      $this->_check = $check_query->RecordCount();
    }
    return $this->_check;
  }

  function install()
  {
    global $db, $messageStack;
    if (defined('MODULE_PAYMENT_BILLDESK_STATUS')) {
      $messageStack->add_session('BillDesk module already installed.', 'error');
      zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=billdesk', '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 BillDesk Module', 'MODULE_PAYMENT_BILLDESK_STATUS', 'True', 'Do you want to accept BillDesk 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_BILLDESK_ORDER_STATUS_ID', '2', 'Set the status of Paid 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 ('<hr>Sort order of display.', 'MODULE_PAYMENT_BILLDESK_SORT_ORDER', '0', 'Sort order of displaying payment options to the customer. Lowest is displayed first.', '6', '0', now())");
    //$db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_BILLDESK_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('Merchant Id' , 'MODULE_PAYMENT_BILLDESK_MERCHANT_ID', '' , 'Enter Merchant id' , '6' , '0' , now())");
   // $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, use_function) VALUES ('Merchant Key' , 'MODULE_PAYMENT_BILLDESK_MERCHANT_KEY', '' , 'Enter Merchant key' , '6' , '0' , now(),'zen_cfg_password_display')");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('Client Id' , 'MODULE_PAYMENT_BILLDESK_CLIENT_ID', '' , 'Enter Client id' , '6' , '0' , now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('Key Id' , 'MODULE_PAYMENT_BILLDESK_KEY_ID', '' , 'Enter Key id' , '6' , '0' , now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('Item Code' , 'MODULE_PAYMENT_BILLDESK_ITEM_CODE', '' , 'Enter Item code' , '6' , '0' , now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('Merchant Logo' , 'MODULE_PAYMENT_BILLDESK_MERCHANT_LOGO', '' , 'Enter Merchant logo' , '6' , '0' , now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('Payment Categories' , 'MODULE_PAYMENT_BILLDESK_PAYMENT_CATEGORIES', '' , 'Enter Payment categories' , '6' , '0' , now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Environmnet' , 'MODULE_PAYMENT_BILLDESK_ENVIRONMENT', '' , 'Enter Environment' , '6' , '0','zen_cfg_select_option(array(\'UAT\', \'PROD\'), ' , now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) VALUES ('Retry Count' , 'MODULE_PAYMENT_BILLDESK_RETRY_COUNT', '' , 'Enter retry count' , '6' , '0' , now())");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Child Window' , 'MODULE_PAYMENT_BILLDESK_CHILD_WINDOW', '' , 'Enter child window' , '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, date_added, use_function) VALUES ('Encryption Password' , 'MODULE_PAYMENT_BILLDESK_ENCRYPTION_KEY', '' , 'Enter the encryption key' , '6' , '0' , now(),'zen_cfg_password_display')");
    $db->Execute("INSERT INTO " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, use_function) VALUES ('Signing Password' , 'MODULE_PAYMENT_BILLDESK_SIGNING_KEY', '' , 'Enter the signing key' , '6' , '0' , now(),'zen_cfg_password_display')");


    $this->tableCheckup();
  }

  function remove()
  {
    global $db;
    $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
  }

  function keys()
{
  return array(
    'MODULE_PAYMENT_BILLDESK_STATUS',
    'MODULE_PAYMENT_BILLDESK_ORDER_STATUS_ID',
    'MODULE_PAYMENT_BILLDESK_SORT_ORDER',
    //'MODULE_PAYMENT_BILLDESK_ZONE',
    'MODULE_PAYMENT_BILLDESK_MERCHANT_ID',
    'MODULE_PAYMENT_BILLDESK_KEY_ID',
    'MODULE_PAYMENT_BILLDESK_MERCHANT_KEY',
    'MODULE_PAYMENT_BILLDESK_ENCRYPTION_KEY',      // <-- Add this
    'MODULE_PAYMENT_BILLDESK_SIGNING_KEY',
    'MODULE_PAYMENT_BILLDESK_CLIENT_ID',
    'MODULE_PAYMENT_BILLDESK_KEY_ID',
    'MODULE_PAYMENT_BILLDESK_ITEM_CODE',
    'MODULE_PAYMENT_BILLDESK_MERCHANT_LOGO',
    'MODULE_PAYMENT_BILLDESK_PAYMENT_CATEGORIES',
    'MODULE_PAYMENT_BILLDESK_ENVIRONMENT',
    'MODULE_PAYMENT_BILLDESK_RETRY_COUNT',
    'MODULE_PAYMENT_BILLDESK_CHILD_WINDOW',
          // <-- Add this
    //'MODULE_PAYMENT_BILLDESK_JOSE_ENCRYPTION_KEY_ID', // skipped as requested
    //'MODULE_PAYMENT_BILLDESK_JOSE_SIGNING_KEY_ID'
  );
}


  protected function tableCheckup()
  {
    global $db, $sniffer;
    if (!$sniffer->table_exists(TABLE_BILLDESK_PAYMENTS)) {
      $sql = "
            CREATE TABLE `" . TABLE_BILLDESK_PAYMENTS . "` (
              `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                `order_id` varchar(255) DEFAULT NULL,
                `billdesk_order_id` varchar(255) DEFAULT NULL,
                `transaction_id` varchar(255) DEFAULT NULL,
                `transaction_date` varchar(255) DEFAULT NULL,
                `currency` varchar(255) DEFAULT NULL,
                `amount` varchar(255) DEFAULT NULL,
                PRIMARY KEY (`id`)
            )";
      $db->Execute($sql);
    }
  }
}
