<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * debuging function
 */
if (!function_exists('__debug')) {
	function __debug()
	{
		echo '<pre>';
		print_r(func_get_args());
		echo '</pre>';
	}
}

if (!function_exists('get_system_auth')) {
	function get_system_auth()
	{
		if (license_read()) {

			check_license();

			$data = license_read();

			if (base_url() != $data['string']) {
				$ci = &get_instance();
				$ci->session->set_flashdata('failed', '<div class="alert alert-danger" role="alert">Code lisensi Anda tidak valid</div>');

				redirect(base_url() . 'license');
			}

			if (strtotime('now') > $data['active_end']) {
				$ci = &get_instance();
				$ci->session->set_flashdata('failed', '<div class="alert alert-danger" role="alert">Code lisensi Anda telah kadaluarsa</div>');

				redirect(base_url() . 'license');
			}

			$one_month_before_expired = strtotime('-1 month', $data['active_end']);

			if (strtotime('now') > $one_month_before_expired) {
				$ci = &get_instance();
				$ci->session->set_flashdata('license_expired', '<div class="alert alert-danger" role="alert">Lisensi Anda akan kadaluarsa pada tanggal ' . date('Y-m-d H:i', $data['active_end']) . '</div>');
			}
		} else {
			// redirect(base_url() . 'license'); #bypass license or deactivated license by maswomdho
		}
	}
}

if (!function_exists('is_curl_enabled')) {
	function is_curl_enabled()
	{
		if (!function_exists("curl_init")) return false;

		return true;
	}
}

if (!function_exists('license_read')) {
	function license_read()
	{
		if (!file_exists(BASEPATH . 'results.txt')) return false;

		$default = [
			'license' => '',
			'string' => '',
			'date_check' => 0,
			'active_end' => 0
		];

		$encoded_string = file_get_contents(BASEPATH . 'results.txt');

		$CI = &get_instance();
		$secret_key = $CI->config->item('enc_key');
		$secret_iv = $CI->config->item('enc_iv');

		$encrypt_method = "AES-256-CBC";
		$key = hash('sha256', $secret_key);
		$iv = substr(hash('sha256', $secret_iv), 0, 16);

		$string = openssl_decrypt(base64_decode($encoded_string), $encrypt_method, $key, 0, $iv);

		$data = json_decode($string, true);

		return array_merge($default, $data);
	}
}

if (!function_exists('licnse_write')) {
	function license_write($data)
	{
		$data = json_encode($data, JSON_PRETTY_PRINT);

		$CI = &get_instance();
		$secret_key = $CI->config->item('enc_key');
		$secret_iv = $CI->config->item('enc_iv');

		$encrypt_method = "AES-256-CBC";
		$key = hash('sha256', $secret_key);
		$iv = substr(hash('sha256', $secret_iv), 0, 16);

		$data = base64_encode(openssl_encrypt($data, $encrypt_method, $key, 0, $iv));

		$fp = fopen(BASEPATH . 'results.txt', 'w');
		fwrite($fp, $data);
		fclose($fp);
	}
}

if (!function_exists('license_delete')) {
	function license_delete()
	{
		unlink(BASEPATH . 'results.txt');
	}
}

if (!function_exists('register_license')) {
	function register_license($email, $password, $license)
	{
		$url = 'https://app.tokoorder.com/sejoli-license/';

		$data = array(
			'user_email' => $email,
			'user_pass'  => $password,
			'license'    => $license,
			'string'     => base_url()
		);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_HEADER, true);
		$body = curl_exec($ch);
		$header = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$error = curl_error($ch);
		curl_close($ch);

		if (200 != (int) $header) {
			if (404 == (int) $header) {
				$error = 'Page not found';
			}
			throw new Exception('' . $header . ', ' . $error);
		} else {
			$json = json_decode($body, true);

			if ($json['valid']) {
				unset($data['user_email']);
				unset($data['user_pass']);
				$data['date_check'] = 0;
				$data['active_end'] = 0;
				license_write($data);

				return $json;
			} else {
				return $json;
			}
		}
	}
}

if (!function_exists('delete_license')) {
	function delete_license($email, $password, $license)
	{
		$CI = &get_instance();
		$url = 'https://app.tokoorder.com/sejoli-delete-license/';

		$data = array(
			'user_email' => $email,
			'user_pass'  => $password,
			'license'    => $license,
			'string'     => base_url()
		);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_HEADER, true);
		$body = curl_exec($ch);
		$header = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$error = curl_error($ch);
		curl_close($ch);

		if (200 != (int) $header) {
			if (404 == (int) $header) {
				$error = 'Page not found';
			}
			throw new Exception('' . $header . ', ' . $error);
		} else {
			$json = json_decode($body, true);

			if ($json['valid']) {
				license_delete();

				session_unset();
				session_destroy();
				delete_cookie('djehbicd');

				$file = APPPATH . 'config/config.php';

				$c = file_get_contents($file);
				$new = str_replace(rtrim(base_url(), '/'), '%BASE_URL%', $c);
				$new = str_replace($CI->config->item('enc_key'), '%ENC_KEY%', $new);
				$new = str_replace($CI->config->item('enc_iv'), '%ENC_IV%', $new);

				$handle = fopen($file, 'w+');
				@chmod($file, 0777);

				if (is_writable(dirname($file))) {
					fwrite($handle, $new);
				}

				$CI->load->dbforge();
				$CI->dbforge->drop_database($CI->db->database);

				reset_database();
				return $json;
			} else {
				return $json;
			}
		}
	}
}

if (!function_exists('reset_database')) {
	function reset_database()
	{
		$CI = &get_instance();
		$file = APPPATH . 'config/database.php';

		$c = file_get_contents($file);
		$new = str_replace($CI->db->hostname, 'localhost', $c);
		$new = str_replace($CI->db->database, '#', $new);
		$new = str_replace($CI->db->username, '#', $new);
		$new = str_replace($CI->db->password, '#', $new);

		$handle = fopen($file, 'w+');
		@chmod($file, 0777);

		if (is_writable(dirname($file))) {
			fwrite($handle, $new);
		}
	}
}

if (!function_exists('check_license')) {
	function check_license()
	{
		$data = license_read();

		if ($data['date_check'] > strtotime('now')) return;

		$url = 'https://app.tokoorder.com/sejoli-validate-license/';

		$q = array(
			'license'    => $data['license'],
			'string'     => base_url()
		);

		$request_url   = $url . '?' . http_build_query($q);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $request_url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_HEADER, true);
		$body = curl_exec($ch);
		$header = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$error = curl_error($ch);
		curl_close($ch);

		if (200 != (int) $header) {
			$data['date_check'] = strtotime('+1 days');
			license_write($data);
		} else {
			$json = json_decode($body, true);

			echo strtotime($json['end-date']);

			if ($json['valid']) {
				$data['date_check'] = strtotime('+30 days');
				$data['active_end'] = $json['detail']['end-date'] ? strtotime($json['detail']['end-date']) : strtotime('+50 years');
				license_write($data);
			} else {
				license_delete();
			}
		}
	}
}