<?php
function ewfk_api_login()
{
	$headers = array('Accept' => 'application/json');
	$body = array('email' => EWFK_API_EMAIL, 'password' => EWFK_API_PASS, 'returnSecureToken' => true);
	$args = array(
		'body' => $body,
		'timeout' => '5',
		'redirection' => '5',
		'httpversion' => '1.0',
		'blocking' => true,
		'headers' => $headers,
		'cookies' => array(),
	);

	$request = wp_remote_post(EWFK_API_URL . 'accounts:signInWithPassword?key=' . EWFK_API_KEY, $args);

	return $request['body'];
}

function ewfk_api_status($token)
{

	$headers = array('Accept' => 'application/json', 'PAC' => EWFK_API_PAC, "Authorization" => "Bearer " . $token);
	$body = array();
	$args = array(
		'body' => $body,
		'timeout' => '5',
		'redirection' => '5',
		'httpversion' => '1.0',
		'blocking' => true,
		'headers' => $headers,
		'cookies' => array(),
	);
	$request = wp_remote_get(EWFK_API_URL . 'taxcore:status?key=' . EWFK_API_KEY, $args);


	return $request['body'];
}
function ewfk_api_invoice($token, $data, $email)
{

	$headers = array('Accept' => 'application/json', 'PAC' => EWFK_API_PAC, "Authorization" => "Bearer " . $token);
	$body = $data;
	$args = array(
		'body' => $body,
		'timeout' => '5',
		'redirection' => '5',
		'httpversion' => '1.0',
		'blocking' => true,
		'headers' => $headers,
		'cookies' => array(),
	);

	$request = wp_remote_post(EWFK_API_URL . 'taxcore:invoices?key=' . EWFK_API_KEY, $args);


	$_SESSION['msg'] = json_decode($request['body'])->messages;
	$_SESSION['email'] = $email;
	$ewfk_upload_dir=wp_upload_dir();
	$dir = $ewfk_upload_dir['basedir'];


	if (json_decode($request['body'])->messages == "Success") {

		$dir = $ewfk_upload_dir['basedir'];


		$mpdf = new \Mpdf\Mpdf();

		$order = array("======== КРАЈ ФИСКАЛНОГ РАЧУНА =========");
		$replace = array("");


		$qr_code = json_decode($request['body'])->verificationQRCode;

		$data = base64_decode($qr_code);
		$dir_invoice = md5($qr_code . time());
		mkdir($dir . "/" . $dir_invoice, 0755);
		$dir_inv = $dir . "/" . $dir_invoice;
		file_put_contents($dir_inv . "/qr.jpg", $data);

		$qr = '<img style="margin-left:20px;margin-top:-20px" height="200px" width="200px" src="file:///' . $dir_inv . "/qr.jpg" . '"/>';

		$mpdf->allow_charset_conversion = true;
		$mpdf->charset_in = 'UTF-8';

		$mpdf->WriteHTML("<div style='font-size:10px;width:310px;'><pre>" . str_replace($order, $replace, json_decode($request['body'])->journal) . "</pre>" . $qr . "<br />======== КРАЈ ФИСКАЛНОГ РАЧУНА =========</div>");

		$mpdf->Output($dir_inv . "/racun.pdf", \Mpdf\Output\Destination::FILE);


		$attachments = array($dir_inv . "/racun.pdf");
		$headers = 'From: Fiskalni račun <no-reply@it-creator.rs>' . "\r\n";
		wp_mail($email, 'Fiskalni račun', 'Poštovani,

U prilogu šaljemo fiskalni račun.

Hvala što koristite naše usluge.', $headers, $attachments);

		ewfk_deleteDir($dir_inv);
	}

}

function ewfk_deleteDir(string $dirPath): void
{
	if (!is_dir($dirPath)) {
		throw new InvalidArgumentException("$dirPath must be a directory");
	}
	if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
		$dirPath .= '/';
	}
	$files = glob($dirPath . '*', GLOB_MARK);
	foreach ($files as $file) {
		if (is_dir($file)) {
			ewfk_deleteDir($file);
		} else {
			unlink($file);
		}
	}
	rmdir($dirPath);
}
function ewfk_db_myplugin()
{

	// WP Globals
	global $table_prefix, $wpdb;


	$esirTable = $table_prefix . 'esir_config';


	if (
		$wpdb->get_var(
			$wpdb->prepare(
				"show tables like %s",
				$esirTable
			)
		) != $esirTable
	) {


		// Query - Create Table
		$sql = "CREATE TABLE `$esirTable` (";
		$sql .= " `id` int(11) NOT NULL auto_increment, ";
		$sql .= " `email` varchar(500) NOT NULL, ";
		$sql .= " `api_url` varchar(500) NOT NULL, ";
		$sql .= " `api_key` varchar(500), ";
		$sql .= " `api_pass` varchar(500) NOT NULL, ";
		$sql .= " `api_pac` varchar(500), ";
		$sql .= " `json` varchar(500), ";
		$sql .= " PRIMARY KEY `customer_id` (`id`) ";
		$sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";

		// Include Upgrade Script
		require_once (ABSPATH . '/wp-admin/includes/upgrade.php');

		// Create Table
		dbDelta($sql);
	}

}

function ewfk_my_admin_menu()
{
	add_menu_page('Esir admin', 'ESIR - WIN Fiskal (fiskalna kasa)', 'manage_options', 'esir/esir-admin-page.php', 'ewfk_admin_page', 'dashicons-money-alt', 58);
}

function ewfk_admin_page()
{
	$disabled = "";
	$message_woo = "";
	if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
		$disabled = "disabled";
		$message_woo = "To start using plugin, please activate and set woocommerce first!";
	}

	echo "<h1>ESIR - WIN Fiskal (fiskalna kasa)</h1>";
	echo "<hr/>";
	echo "<h2>Settings</h2>";

	$admin_url = get_admin_url();

	echo '<div class="wrap" style="width:550px;float:left;">';
	echo '<form action="' . esc_url($admin_url . 'admin-post.php') . '" method="post">';
	echo '<table class="form-table">';
	echo '<tr><th><label for="second_field_id">API Key:</label></th>';
	echo '<td><input type="text" class="regular-text" id="api_key_id" name="api_key_name" value="' . esc_attr(EWFK_API_KEY) . '" required></td></tr>';
	echo '<tr><th><label for="email">Email:</label></th>';
	echo '<td><input type="email" class="regular-text" id="email_id" name="email_name" value="' . esc_attr(EWFK_API_EMAIL) . '" required></td></tr>';
	echo '<tr><th><label for="third_field_id">Password:</label></th>';
	echo '<td><input type="password" class="regular-text" id="password_id" name="password_name" value="" required></td></tr>';
	echo '<tr><th><label for="second_field_id">PAC:</label></th>';
	echo '<td><input type="text" class="regular-text" id="pac_id" name="pac_name" value="" required></td></tr>';
	echo '<tr><th><label for="second_field_id">Cashier:</label></th>';
	echo '<td><input type="text" class="regular-text" id="cashier_id" name="cashier_name" value="' . esc_attr(EWFK_CASHIER) . '" required></td></tr>';
	echo '<tr><th><label for="second_field_id">Page after failed invoice:</label></th>';
	echo '<td><input type="text" class="regular-text" id="page_id" name="page_name" value="' . esc_attr(EWFK_PAGE_FAILED) . '" required></td></tr>';
	echo '<tr><th><label for="second_field_id">Notification email (after failed invoice):</label></th>';
	echo '<td><input type="email" class="regular-text" id="notif_email_id" name="notif_email_name" value="' . esc_attr(EWFK_NOTIF_EMAIL) . '" required></td></tr>';
	echo '<tr><th></th>';
	echo '<td><input type="hidden" name="action" value="submit-settings" />';
	echo wp_nonce_field('submit-settings', '_wpnonce', true, false);  // Proper nonce field
	echo '<input type="submit" class="regular-text" id="submit_id" name="submit_name" value="Save" ' . esc_attr($disabled) . '>';
	echo '</td></tr>';
	echo '</table>';
	echo '</form>';
	
	echo '<form action="' . esc_url($admin_url . 'admin-post.php') . '" method="post">';
	echo '<table class="form-table">';
	echo '<tr><th></th>';
	echo '<td><input type="hidden" name="action" value="test-api" />';
	echo '<input type="button" class="regular-text" id="test_api_id" name="test_api_name" value="Test API connection">';
	echo '</td></tr>';
	echo '</table>';
	echo '</form>';
	
	echo '</div><div style="width:400px;float:left">';
	echo '<div id="woo_chck" style="width:400px;margin-top:100px;padding-left:80px;font-size:20px;">' . esc_html($message_woo) . '</div>';
	echo '<div id="error_messsages" style="width:400px;margin-top:210px;padding-left:80px;font-size:20px;"></div>';
	echo '</div>';
}

function ewfk_settings_form_action()
{
	$admin_url = site_url() . '/wp-admin/admin.php?page=esir%2Fesir-admin-page.php';
	$email = sanitize_email($_POST['email_name']);
	$api_key_name = sanitize_text_field($_POST['api_key_name']);
	$password_name = sanitize_text_field($_POST['password_name']);
	$pac_name = sanitize_text_field($_POST['pac_name']);
	$cashier_name = sanitize_text_field($_POST['cashier_name']);
	$page_name = sanitize_url($_POST['page_name']);
	$notif_email_name = sanitize_email($_POST['notif_email_name']);
	if (!check_admin_referer('submit-settings')) {
		wp_die("error. " . "<a href='" . $admin_url . "'>Go back</a>");
	}
	if (!wp_http_validate_url($page_name)) {
		wp_die("Wrong url. " . "<a href='" . $admin_url . "'>Go back</a>");
	}

	if (!is_email($email)) {
		wp_die("Wrong email. " . "<a href='" . $admin_url . "'>Go back</a>");
	}

	if (!is_email($notif_email_name)) {
		wp_die("Wrong email. " . "<a href='" . $admin_url . "'>Go back</a>");
	}

	if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
		wp_die("Please activate and set woocommerce plugin first. " . "<a href='" . $admin_url . "'>Go back</a>");
	}


	$uuid_validation_regex = "/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/";
	$api_key_bool = preg_match($uuid_validation_regex, $api_key_name); // returns 1

	if (!$api_key_bool) {
		wp_die("Wrong api key.  " . "<a href='" . $admin_url . "'>Go back</a>");
	}

	$json_store = ewfk_create_json_store();
	$ciphering = "AES-128-CTR";
	$options = 0;

	$pac = openssl_encrypt(
		$pac_name,
		$ciphering,
		$json_store->ii,
		$options,
		$json_store->i
	);

	$cashier = trim($cashier_name);

	$notif_email = trim($notif_email_name);


	$page_failed = "";
	if (isset($_POST['page_name'])) {
		$page_failed = trim($page_name);
	}

	$json_array = json_encode(["cashier" => $cashier, "page_failed" => $page_failed, "notif_email" => $notif_email]);

	$password = openssl_encrypt(
		trim($password_name),
		$ciphering,
		$json_store->ii,
		$options,
		$json_store->i
	);


	if ($api_key_bool) {
		$api_key = openssl_encrypt(
			$api_key_name,
			$ciphering,
			$json_store->ii,
			$options,
			$json_store->i
		);
	}

	if (isset($_POST['submit_name'])) {

		global $wpdb;
		$tablename = $wpdb->prefix . 'esir_config';

		$sql = "DELETE from $tablename";
		$wpdb->query($sql);

		$wpdb->insert(
			$tablename,
			array(
				'email' => trim($email),
				'api_url' => EWFK_API_URL,
				'api_key' => trim($api_key),
				'api_pass' => $password,
				'api_pac' => trim($pac),
				'json' => $json_array
			),
			array('%s', '%s', '%s', '%s', '%s', '%s')
		);
	}

	header("Location: " . site_url("/wp-admin/admin.php?page=esir%2Fesir-admin-page.php"));

}
function ewfk_test_api_form_action()
{
	$admin_url = site_url() . '/wp-admin/admin.php?page=esir%2Fesir-admin-page.php';
	if (!check_ajax_referer('test_api')) {
		wp_die("error. " . "<a href='" . $admin_url . "'>Go back</a>");
	}

	$result_login = json_decode(ewfk_api_login());
	@$result = json_decode(ewfk_api_status($result_login->idToken));

	if (isset($result->sdcDateTime)) {
		echo "<span style='color:green'>API connection successful!</span>";
		wp_die();
	} else {
		echo "<span style='color:red'>API connection error. Check your API credentials!</span>";
		wp_die();
	}
}
function ewfk_generateRandomString($length = 10, $only_numbs = false)
{

	if ($only_numbs) {
		$characters = '0123456789';
	} else {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	}

	$charactersLength = strlen($characters);
	$randomString = '';
	for ($i = 0; $i < $length; $i++) {
		$randomString .= $characters[random_int(0, $charactersLength - 1)];
	}
	return $randomString;
}

function ewfk_create_json_store()
{
	$ciphering = "AES-128-CTR";

	$iv_length = openssl_cipher_iv_length($ciphering);
	// Non-NULL Initialization Vector for encryption
	$encryption_iv = (int) ewfk_generateRandomString($iv_length, true);
	$myJson = new stdClass();
	$myJson->i = $encryption_iv;
	$myJson->ii = ewfk_generateRandomString(20, false);

	$ewfk_upload_dir=wp_upload_dir();
	$dir = $ewfk_upload_dir['basedir'];
	mkdir($dir . "/ewfk_settings", 0755, true);
	file_put_contents($dir . "/ewfk_settings/store.json", json_encode($myJson));

	return $myJson;
}

function ewfk_get_settings_esir()
{
	global $table_prefix, $wpdb;


	$esirTable = $table_prefix . 'esir_config';

	$settings = $wpdb->get_row($wpdb->prepare(
		"SELECT * from %i order by id DESC LIMIT 1",
		$esirTable
	)
	);

	$ewfk_upload_dir=wp_upload_dir();

	$dir = $ewfk_upload_dir['basedir'];

	if (file_exists($dir . "/ewfk_settings/store.json")) {
		$keys = file_get_contents($dir . "/ewfk_settings/store.json");
		$settings_object = new stdClass();
		$ciphering = "AES-128-CTR";
		@$settings_object->email = $settings->email;
		@$settings_object->api_url = $settings->api_url;
		@$settings_object->api_key = openssl_decrypt(
			$settings->api_key,
			$ciphering,
			json_decode($keys)->ii,
			0,
			json_decode($keys)->i
		);
		@$settings_object->api_pass = openssl_decrypt(
			$settings->api_pass,
			$ciphering,
			json_decode($keys)->ii,
			0,
			json_decode($keys)->i
		);
		@$settings_object->api_pac = openssl_decrypt(
			$settings->api_pac,
			$ciphering,
			json_decode($keys)->ii,
			0,
			json_decode($keys)->i
		);
		@$settings_object->json = json_decode($settings->json);

		return $settings_object;
	}
}