<?php
//-----------------------------------------
// Author: Qphoria@gmail.com
// Web: http://www.theQdomain.com/
//-----------------------------------------
class ControllerPaymentOfflineCC extends Controller {
	private $error = array();
	private $name = '';

	public function index() {

		$this->checkdb();

		/* START ERRORS */
		$errors = array(
			'warning',
			'types'
		);
		/* END ERRORS */



		/* START COMMON STUFF */
		$this->name = basename(__FILE__, '.php');

		if (!isset($this->session->data['token'])) { $this->session->data['token'] = 0; }
		$this->data['token'] = $this->session->data['token'];
		$this->data = array_merge($this->data, $this->load->language('payment/' . $this->name));

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/setting');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && ($this->validate($errors))) {
			foreach ($this->request->post as $key => $value) {
				if (is_array($value)) { $this->request->post[$key] = implode(',', $value); }
			}
			$this->load->model('setting/setting');

			$this->model_setting_setting->editSetting($this->name, $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$this->redirect((((HTTPS_SERVER) ? HTTPS_SERVER : HTTP_SERVER) . 'index.php?token=' . $this->session->data['token'] . '&route=extension/payment'));
		}

		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'href'      => (((HTTPS_SERVER) ? HTTPS_SERVER : HTTP_SERVER) . 'index.php?token=' . $this->session->data['token'] . '&route=common/home'),
       		'text'      => $this->language->get('text_home'),
      		'separator' => FALSE
   		);

   		$this->data['breadcrumbs'][] = array(
       		'href'      => (((HTTPS_SERVER) ? HTTPS_SERVER : HTTP_SERVER) . 'index.php?token=' . $this->session->data['token'] . '&route=extension/payment'),
       		'text'      => $this->language->get('text_payment'),
      		'separator' => ' :: '
   		);

   		$this->data['breadcrumbs'][] = array(
       		'href'      => (((HTTPS_SERVER) ? HTTPS_SERVER : HTTP_SERVER) . 'index.php?token=' . $this->session->data['token'] . '&route=payment/' . $this->name),
       		'text'      => $this->language->get('heading_title'),
      		'separator' => ' :: '
   		);

		$this->data['action'] = (((HTTPS_SERVER) ? HTTPS_SERVER : HTTP_SERVER) . 'index.php?token=' . $this->session->data['token'] . '&route=payment/' . $this->name);

		$this->data['cancel'] = (((HTTPS_SERVER) ? HTTPS_SERVER : HTTP_SERVER) . 'index.php?token=' . $this->session->data['token'] . '&route=extension/payment');

		$this->id       = 'content';
		$this->template = 'payment/' . $this->name . '.tpl';

		/* 14x backwards compatibility */
		if (method_exists($this->document, 'addBreadcrumb')) { //1.4.x
			$this->document->breadcrumbs = $this->data['breadcrumbs'];
			unset($this->data['breadcrumbs']);
		}//

		$this->children = array(
            'common/header',
            'common/footer'
        );

        foreach ($errors as $error) {
			if (isset($this->error[$error])) {
				$this->data['error_' . $error] = $this->error[$error];
			} else {
				$this->data['error_' . $error] = '';
			}
		}
		/* END COMMON STUFF */




		/* START FIELDS */
		$this->data['extension_class'] = 'payment';
		$this->data['tab_class'] = 'htabs';

		$geo_zones = array();

		$this->load->model('localisation/geo_zone');

		$geo_zones[0] = $this->language->get('text_all_zones');
		foreach ($this->model_localisation_geo_zone->getGeoZones() as $geozone) {
			$geo_zones[$geozone['geo_zone_id']] = $geozone['name'];
		}

		$order_statuses = array();

		$this->load->model('localisation/order_status');

		foreach ($this->model_localisation_order_status->getOrderStatuses() as $order_status) {
			$order_statuses[$order_status['order_status_id']] = $order_status['name'];
		}

		$customer_groups = array();

		$this->load->model('sale/customer_group');

		foreach ($this->model_sale_customer_group->getCustomerGroups() as $customer_group) {
			$customer_groups[$customer_group['customer_group_id']] = $customer_group['name'];
		}

		$this->data['tabs'] = array();

		$this->data['tabs'][] = array(
			'id'		=> 'tab_general',
			'title'		=> $this->language->get('tab_general')
		);

		$this->data['fields'] = array();

		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_status'),
			'type'			=> 'select',
			'name' 			=> $this->name . '_status',
			'value' 		=> (isset($this->request->post[$this->name . '_status'])) ? $this->request->post[$this->name . '_status'] : $this->config->get($this->name . '_status'),
			'required' 		=> false,
			'help'			=> $this->language->get('help_reminder'),
			'options'		=> array(
				'0' => $this->language->get('text_disabled'),
				'1' => $this->language->get('text_enabled')
			)
		);

		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_encryption'),
			'type'			=> 'text',
			'size'			=> '60',
			'name' 			=> $this->name . '_encryption',
			'value' 		=> (isset($this->request->post[$this->name . '_encryption'])) ? $this->request->post[$this->name . '_encryption'] : $this->config->get($this->name . '_encryption'),
			'required' 		=> false,
			'error'			=> (isset($this->error['encryption'])) ? $this->error['encryption'] : ''
		);

		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_types'),
			'type'			=> 'select',
			'multiple'		=> true,
			'name' 			=> $this->name . '_types[]',
			'value' 		=> explode(',', (isset($this->request->post[$this->name . '_types'])) ? $this->request->post[$this->name . '_types'] : $this->config->get($this->name . '_types')),
			'required' 		=> false,
			'options'		=> array(
				'visa' 			=> 'Visa',
				'mastercard'	=> 'MasterCard',
				'amex'			=> 'American Express',
				'disc'			=> 'Discover',
				'diner'			=> 'Diners Club',
				'jcb'			=> 'JCB',
				'solo'			=> 'Solo',
				'maestro'		=> 'Maestro',
			),
			'required' 		=> true,
			'error'			=> (isset($this->error['types'])) ? $this->error['types'] : ''
		);

		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_mode'),
			'type'			=> 'select',
			'name' 			=> $this->name . '_mode',
			'value' 		=> (isset($this->request->post[$this->name . '_mode'])) ? $this->request->post[$this->name . '_mode'] : $this->config->get($this->name . '_mode'),
			'required' 		=> false,
			'options'		=> array(
				'0' => $this->language->get('text_non_compliant'),
				'1' => $this->language->get('text_non_compliant_email'),
				'2' => $this->language->get('text_compliant'),
			)
		);

/*
		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_ajax'),
			'type'			=> 'select',
			'name' 			=> $this->name . '_ajax',
			'value' 		=> (isset($this->request->post[$this->name . '_ajax'])) ? $this->request->post[$this->name . '_ajax'] : $this->config->get($this->name . '_ajax'),
			'required' 		=> false,
			'options'		=> array(
				'0' => $this->language->get('text_disabled'),
				'1' => $this->language->get('text_enabled')
			)
		);
*/
/*
		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_customer_group'),
			'type'			=> 'select',
			'multiple'		=> true,
			'name' 			=> $this->name . '_customer_group[]',
			'value' 		=> (isset($this->request->post[$this->name . '_customer_group'])) ? $this->request->post[$this->name . '_customer_group'] : $this->config->get($this->name . '_customer_group'),
			'required' 		=> false,
			'options'		=> $customer_groups
		);
*/

		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_geo_zone'),
			'type'			=> 'select',
			'name' 			=> $this->name . '_geo_zone_id',
			'value' 		=> (isset($this->request->post[$this->name . '_geo_zone_id'])) ? $this->request->post[$this->name . '_geo_zone_id'] : $this->config->get($this->name . '_geo_zone_id'),
			'required' 		=> false,
			'options'		=> $geo_zones
		);

		$this->data['fields'][] = array(
			'entry' 		=> $this->language->get('entry_order_status'),
			'type'			=> 'select',
			'name' 			=> $this->name . '_order_status_id',
			'value' 		=> (isset($this->request->post[$this->name . '_order_status_id'])) ? $this->request->post[$this->name . '_order_status_id'] : $this->config->get($this->name . '_order_status_id'),
			'required' 		=> false,
			'options'		=> $order_statuses
		);

		$this->data['fields'][] = array(
			'entry'			=> $this->language->get('entry_sort_order'),
			'type'			=> 'text',
			'name'			=> $this->name . '_sort_order',
			'value'			=> (isset($this->request->post[$this->name . '_sort_order'])) ? $this->request->post[$this->name . '_sort_order'] : $this->config->get($this->name . '_sort_order'),
			'required'		=> false,
		);
		/* END FIELDS */

        $this->response->setOutput($this->render(TRUE));
	}

	private function validate($errors = array()) {
		if (!$this->user->hasPermission('modify', 'payment/' . $this->name)) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		foreach ($errors as $error) {
			if (isset($this->request->post[$this->name . '_' . $error]) && !$this->request->post[$this->name . '_' . $error]) {
				$this->error[$error] = $this->language->get('error_' . $error);
			}
			if ($error == 'types') {
				if (!isset($this->request->post[$this->name . '_types']) || !$this->request->post[$this->name . '_types']) {
					$this->error[$error] = $this->language->get('error_' . $error);
				}
			}
		}

		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	private function checkdb() {

		$sql = "
			CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "offline_cc_data` (
			`order_id` int(11) NOT NULL default '0',
			`cc_type` varchar(16) NOT NULL,
			`cc_name` varchar(64) NOT NULL,
			`cc_number` varchar(40) NOT NULL,
			`cc_exp` varchar(8) NOT NULL,
			`cc_cvv` int(6) NOT NULL default '0',
			`cc_startdate` varchar(20) NOT NULL,
			`cc_issuenum` varchar(20) NOT NULL,
			PRIMARY KEY  (`order_id`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8";
		$this->db->query($sql);

		// Copy old order table cc data to new offline cc data table if exists
		$tbl = '`' . DB_PREFIX . 'order`';
		$col = 'cc_number';
		$sql = "DESC $tbl $col";

		$query = $this->db->query($sql);

		if ($query->num_rows) {
			$data = $this->db->query("SELECT order_id, cc_type, cc_name, cc_number, cc_exp, cc_cvv, cc_startdate, cc_issuenum FROM `" . DB_PREFIX . "order`");
			if ($data->num_rows) {
				foreach($data->rows as $ccdata) {
					if ($ccdata['cc_number'] != "") {
						$this->db->query("INSERT INTO " . DB_PREFIX . "offline_cc_data SET order_id = '".$ccdata['order_id']."', cc_type = '".$ccdata['cc_type']."', cc_name = '".$ccdata['cc_name']."', cc_number = '".$ccdata['cc_number']."', cc_exp = '".$ccdata['cc_exp']."', cc_cvv = '".$ccdata['cc_cvv']."', cc_startdate = '".$ccdata['cc_startdate']."', cc_issuenum = '".$ccdata['cc_issuenum']."'");
					}
				}
			}

			//Delete old order columns to avoid repeat insertions
			$sql = array();
			$sql[] = "ALTER TABLE `" . DB_PREFIX . "order` DROP `cc_type`";
			$sql[] = "ALTER TABLE `" . DB_PREFIX . "order` DROP `cc_name`";
			$sql[] = "ALTER TABLE `" . DB_PREFIX . "order` DROP `cc_number`";
			$sql[] = "ALTER TABLE `" . DB_PREFIX . "order` DROP `cc_exp`";
			$sql[] = "ALTER TABLE `" . DB_PREFIX . "order` DROP `cc_cvv`";
			$sql[] = "ALTER TABLE `" . DB_PREFIX . "order` DROP `cc_startdate`";
			$sql[] = "ALTER TABLE `" . DB_PREFIX . "order` DROP `cc_issuenum`";
			foreach ($sql as $s) {
				$this->db->query($s);
			}


		}

	}

	public function deletecc() {
		$this->load->language('payment/offline_cc');

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

		$message = $this->language->get('text_deleted');

		$result = $this->db->query("UPDATE `" . DB_PREFIX . "offline_cc_data` SET cc_type = '" . $message . "', cc_name = '" . $message . "', cc_number = '" . $this->db->escape($message) . "', cc_exp = '00/00', cc_cvv = '' WHERE order_id = '" . $order_id . "'");

		$this->load->library('json');

		$this->response->setOutput(Json::encode($message));
	}
}
?>