<?php
/*
  

	osConcert Seat Booking Software
	https://www.osconcert.com
	Copyright (c) 2024 osConcert

	Released under the GNU General Public License 
*/

// Check to ensure this file is included in osConcert!
defined('_FEXEC') or die();


  class bank_transfer {
    var $code, $title, $description, $enabled;

// class constructor
	function __construct() {
		global $order;
		
		$this->code = 'bank_transfer';
		$name = "Bank Transfer Payment";
		$image = "";
		$path = "";

		if(MODULE_PAYMENT_BANK_TRANSFER_DISPLAY_NAME != "MODULE_PAYMENT_BANK_TRANSFER_DISPLAY_NAME")
			$name = MODULE_PAYMENT_BANK_TRANSFER_DISPLAY_NAME;
		if(MODULE_PAYMENT_BANK_TRANSFER_IMAGE != "MODULE_PAYMENT_BANK_TRANSFER_IMAGE")
			$image = MODULE_PAYMENT_BANK_TRANSFER_IMAGE;
		if($image != "" && file_exists($path . DIR_WS_IMAGES . $image))
		{
			$image = '<img class="img-fluid img-mod" src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . '" height="33">';
		}else
		{
			$image_array = array('.png','.gif','.jpg','.jpeg');
			$image_check = true;
			for($i=0;$i<sizeof($image_array);$i++){
				if($image_check && $image != "" && file_exists($path . DIR_WS_IMAGES . $image . $image_array[$i])){
					$image = '<img class="img-fluid img-mod" src="' . HTTP_SERVER . DIR_WS_HTTP_CATALOG . DIR_WS_IMAGES . $image . $image_array[$i] . '"  height="33">';
					$image_check = false;
				}
			}
			if($image_check)$image = $path;
		}
		//define what's not in the db
		define('MODULE_PAYMENT_BANK_TRANSFER_TEXT_TITLE',  '<span class="modname">' . $name . '</span>&nbsp;&nbsp;' . $image);		
		define("MODULE_PAYMENT_BANK_TRANSFER_TEXT_TEXT_TITLE", $name);

		$this->title = MODULE_PAYMENT_BANK_TRANSFER_TEXT_TITLE;
		$this->text_title = MODULE_PAYMENT_BANK_TRANSFER_TEXT_TEXT_TITLE;
		$this->description = MODULE_PAYMENT_BANK_TRANSFER_TEXT_DESCRIPTION;
		$this->email_footer = MODULE_PAYMENT_BANK_TRANSFER_TEXT_EMAIL_FOOTER;
		$this->sort_order = MODULE_PAYMENT_BANK_TRANSFER_SORT_ORDER;
		$this->enabled = ((MODULE_PAYMENT_BANK_TRANSFER_STATUS == 'True') ? true : false);
		$this->barred=false;
		
		if ((int)MODULE_PAYMENT_BANK_TRANSFER_ORDER_STATUS_ID > 0) {
			$this->order_status = MODULE_PAYMENT_BANK_TRANSFER_ORDER_STATUS_ID;
		}
		
		if (is_object($order)) $this->update_status();
	}

// class methods
    function update_status() {
      global $order;
	  
	  tep_check_module_status($this,MODULE_PAYMENT_BANK_TRANSFER_ZONE,trim(MODULE_PAYMENT_BANK_TRANSFER_EXCEPT_ZONE),trim(MODULE_PAYMENT_BANK_TRANSFER_EXCEPT_COUNTRY));
	  $this->barred=tep_check_payment_barred(trim(MODULE_PAYMENT_BANK_TRANSFER_EXCEPT_COUNTRY));
    }

    function javascript_validation() {
      return false;
    }


	public function selection() {
	  global $FSESSION;

	  // How many days before event we block bank transfer (integer)
	  $cutoff_days = (int)MODULE_PAYMENT_BANK_TRANSFER_CUTOFF_DAYS;
	  if ($cutoff_days < 0) $cutoff_days = 0;

	  // Build order snapshot
	  require_once(DIR_WS_CLASSES . 'order.php');
	  $min_order = new order;

	  // Now (unix ts) — your helper already accounts for server/timezone
	  $now_ts = (int)getServerDate(false);

	  // If ANY product is inside cutoff, hide this method
	  for ($i = 0, $n = count($min_order->products); $i < $n; $i++) {
		$pid = (int)$min_order->products[$i]['id'];
		if (!$this->bt_allowed_for_product($pid, $cutoff_days, $now_ts)) {
		  return false; // hides Bank Transfer entirely
		}
	  }

	  // Build your selection UI (unchanged from your original)
	  $order_query  = tep_db_query("SELECT MAX(orders_id) AS orders_id FROM " . TABLE_ORDERS);
	  $order_result = tep_db_fetch_array($order_query);
	  $orders_id    = (int)$order_result['orders_id'] + 1;

	  $selection_text = '<div style="padding:5px;border:2px dotted red;"><strong>'
					  . HEADING_REFERENCE
					  . '</strong></div>';

	  $selection = array(
		'id'     => $this->code,
		'module' => $this->title,
		'barred' => $this->barred,
		'fields' => array(
		  array('title' => '', 'field' => $selection_text)
		),
	  );

	  return $selection;
	}

	/* ===========================
	   Private helpers (class methods)
	   =========================== */

	private function bt_allowed_for_product($product_id, $cutoff_days, $now_ts) {
	  $cid = $this->bt_get_products_category_id($product_id);
	  if (!$cid) return true; // no category info => don't block

	  $event_ts = $this->bt_get_event_ts_for_category($cid);
	  if (!$event_ts) return true; // no event date => don't block

	  $cutoff_ts = $event_ts - ((int)$cutoff_days) * 86400;

	  // Disallow if we're already within N days: now > cutoff
	  // Use >= if you want to also block on the boundary day itself
	  return ($now_ts <= $cutoff_ts);
	}

	private function bt_get_products_category_id($products_id) {
	  $q = tep_db_query("
		SELECT categories_id
		  FROM " . TABLE_PRODUCTS_TO_CATEGORIES . "
		 WHERE products_id = '" . (int)$products_id . "'
		 LIMIT 1
	  ");
	  if ($row = tep_db_fetch_array($q)) {
		return (int)$row['categories_id'];
	  }
	  return 0;
	}

	private function bt_get_event_ts_for_category($category_id) {
	  // 1) canonical: unix ts from categories
	  $q = tep_db_query("
		SELECT concert_date_unix, date_id
		  FROM " . TABLE_CATEGORIES . "
		 WHERE categories_id = '" . (int)$category_id . "'
		 LIMIT 1
	  ");
	  $row = tep_db_fetch_array($q);

	  if ($row) {
		$unix = isset($row['concert_date_unix']) ? (int)$row['concert_date_unix'] : 0;
		if ($unix > 0) {
		  return $unix;
		}

		// 2) fallback: date_id like '23-10-2025 1400' (format d-m-Y Hi)
		if (!empty($row['date_id'])) {
		  $tz = $this->bt_get_store_tz();
		  $dt = DateTime::createFromFormat('d-m-Y Hi', $row['date_id'], $tz);
		  $errs = DateTime::getLastErrors();
		  if ($dt && empty($errs['warning_count']) && empty($errs['error_count'])) {
			return $dt->getTimestamp();
		  }
		}
	  }

	  // 3) last resort: categories_description.concert_date '23-10-2025' (no time component)
	  global $FSESSION;
	  $dq = tep_db_query("
		SELECT concert_date
		  FROM " . TABLE_CATEGORIES_DESCRIPTION . "
		 WHERE categories_id = '" . (int)$category_id . "'
		   AND language_id    = '" . (int)$FSESSION->languages_id . "'
		 LIMIT 1
	  ");
	  if ($drow = tep_db_fetch_array($dq)) {
		if (!empty($drow['concert_date'])) {
		  $tz = $this->bt_get_store_tz();

		  // Choose start-of-day or end-of-day policy for date-only values:
		  // For leniency, use 23:59:59; for strictness, use 00:00:00.
		  $dt = DateTime::createFromFormat('d-m-Y H:i:s', $drow['concert_date'].' 00:00:00', $tz);
		  if (!$dt) {
			$dt = DateTime::createFromFormat('d-m-Y', $drow['concert_date'], $tz);
		  }
		  if ($dt) {
			return $dt->getTimestamp();
		  }
		}
	  }

	  return 0;
	}

	private function bt_get_store_tz() {
	  if (defined('STORE_TIMEZONE') && STORE_TIMEZONE) {
		try {
		  return new DateTimeZone(STORE_TIMEZONE);
		} catch (Exception $e) {
		  // fall through
		}
	  }
	  // fallback to PHP default or UTC
	  $name = @date_default_timezone_get();
	  if (!$name) $name = 'UTC';
	  return new DateTimeZone($name);
	}

		
	

    function pre_confirmation_check() {
      return false;
    }

    function confirmation() {
      return array('title' => MODULE_PAYMENT_BANK_TRANSFER_TEXT );
    }

    function process_button() {
      return false;
    }

    function before_process() {
      return false;
    }

    function after_process() {
      return false;
    }

    function get_error() {
      return false;
    }

    function check() {
      if (!isset($this->_check)) {
        $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_BANK_TRANSFER_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 Bank Deposit Module', 'MODULE_PAYMENT_BANK_TRANSFER_STATUS', 'True', 'Do you want to accept Bank Deposit payments?', '6', '1', '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, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_BANK_TRANSFER_ZONE', '1,2,3', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'tep_get_zone_class_title', 'tep_cfg_pull_down_zone_classes(', 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 ('Exclude these Countries', 'MODULE_PAYMENT_BANK_TRANSFER_EXCEPT_COUNTRY', '', 'If countries are selected, disable this payment method for that countries.', '6', '3', 'tep_cfg_pull_down_zone_except_countries(MODULE_PAYMENT_BANK_TRANSFER_ZONE,', 'tep_get_zone_except_country', 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 ('Exclude these Zones', 'MODULE_PAYMENT_BANK_TRANSFER_EXCEPT_ZONE', '', 'If a zone is selected, disable this payment method for that zone.', '6', '4', 'tep_cfg_pull_down_zone_classes(','tep_get_zone_class_title', 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_BANK_TRANSFER_SORT_ORDER', '1', 'Sort order of display. Lowest is displayed first.', '6', '5', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('BIC Number', 'MODULE_PAYMENT_BANK_TRANSFER_BIC', 'ABCDEFGH', 'BIC Number', '6', '6', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Bank Account No.', 'MODULE_PAYMENT_BANK_TRANSFER_ACCNUM', '12345678', 'Bank Account No.', '6', '7', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('IBAN Code.', 'MODULE_PAYMENT_BANK_TRANSFER_IBAN', '1234 5678 1234 5678', 'IBAN Code.', '6', '8', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Bank Account Holder', 'MODULE_PAYMENT_BANK_TRANSFER_ACCNAM', 'Joe Bloggs', 'Bank account name', '6', '9', now());");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Bank Name', 'MODULE_PAYMENT_BANK_TRANSFER_BANKNAM', 'The Bank', 'Bank Name', '6', '10', 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_BANK_TRANSFER_ORDER_STATUS_ID', '1', 'Set the status of orders made with this payment module to this value', '6', '11', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Display Name', 'MODULE_PAYMENT_BANK_TRANSFER_DISPLAY_NAME', 'Bank Transfer Payment', 'Set the Display name to payment module', '6', '12', 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 ('Image', 'MODULE_PAYMENT_BANK_TRANSFER_IMAGE', 'bank_transfer.png', 'Set the Image of payment module', '6', '13', 'tep_cfg_file_field(', now())");
	  tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cut off day', 'MODULE_PAYMENT_BANK_TRANSFER_CUTOFF_DAYS', '0', 'Amount of cut off days before day of concert', '6', '16', now());");
   }


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

    function keys() {
      return array('MODULE_PAYMENT_BANK_TRANSFER_STATUS', 'MODULE_PAYMENT_BANK_TRANSFER_ZONE', 'MODULE_PAYMENT_BANK_TRANSFER_EXCEPT_ZONE', 'MODULE_PAYMENT_BANK_TRANSFER_EXCEPT_COUNTRY', 'MODULE_PAYMENT_BANK_TRANSFER_SORT_ORDER', 'MODULE_PAYMENT_BANK_TRANSFER_BIC', 'MODULE_PAYMENT_BANK_TRANSFER_ACCNUM', 'MODULE_PAYMENT_BANK_TRANSFER_ACCNAM', 'MODULE_PAYMENT_BANK_TRANSFER_IBAN', 'MODULE_PAYMENT_BANK_TRANSFER_BANKNAM', 'MODULE_PAYMENT_BANK_TRANSFER_ORDER_STATUS_ID','MODULE_PAYMENT_BANK_TRANSFER_DISPLAY_NAME','MODULE_PAYMENT_BANK_TRANSFER_IMAGE','MODULE_PAYMENT_BANK_TRANSFER_CUTOFF_DAYS');

    }
	
	function get_comments() {
		global $FSESSION;
		  $comments.= MODULE_BANK_TRANSFER_INFO . TEXT_REFERENCEID . ' : ' . $FSESSION->referenceID ;
		  if($comments!="")
		  	return $comments;
		  else
		  	return;	
	}
  }
?>