<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/*
Plugin Name: Invoct – PDF Invoices & Billing for WooCommerce
Description: Free and powerful invoicing plugin for WordPress and WooCommerce. Create and manage PDF invoices, set up periodic invoices, handle billing, and track warehouse inventory — all from a simple, unified dashboard. Includes multiple professional invoice templates.
Version: 2.0
Author: Kiril Kirkov
Author URI: https://github.com/kirilkirkov/
License: GPLv2 or later
Text Domain: kirilkirkov-pdf-invoice-manager
*/

if(!class_exists('\KirilKirkov\WpInvoices\Config')) {
	require 'Includes/Admin/Config/Config.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\Invoices')) {
	require 'Includes/Admin/Classes/Invoices/Invoices.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\InvoicesAData')) {
	require 'Includes/Admin/Classes/Invoices/InvoicesAData.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\InvoicesList')) {
	require 'Includes/Admin/Classes/Invoices/InvoicesList.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\CreateInvoice')) {
	require 'Includes/Admin/Classes/Invoices/CreateInvoice.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\PeriodicInvoices')) {
	require 'Includes/Admin/Classes/Invoices/PeriodicInvoices.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\Clients')) {
	require 'Includes/Admin/Classes/Clients/Clients.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\CreateClient')) {
	require 'Includes/Admin/Classes/Clients/CreateClient.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\CreateItem')) {
	require 'Includes/Admin/Classes/Items/CreateItem.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\Items')) {
	require 'Includes/Admin/Classes/Items/Items.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\SendInvoice')) {
	require 'Includes/Admin/Classes/Invoices/SendInvoice.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\Charts')) {
	require 'Includes/Admin/Classes/Invoices/Charts.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\Woo')) {
	require 'Includes/Admin/Classes/Woocommerce/Woo.php';
}

// Public classes
if(!class_exists('\KirilKirkov\WpInvoices\ShortCodes')) {
	require 'Includes/Public/Classes/ShortCodes.php';
}

if(!class_exists('\KirilKirkov\WpInvoices\WpInvoicesPdf')) {
	require 'Includes/Public/Classes/WpInvoicesPdf.php';
}
// End of Public classes

use KirilKirkov\WpInvoices\Config;
use KirilKirkov\WpInvoices\Invoices;
use KirilKirkov\WpInvoices\InvoicesAData;
use KirilKirkov\WpInvoices\CreateInvoice;
use KirilKirkov\WpInvoices\PeriodicInvoices;
use KirilKirkov\WpInvoices\Clients;
use KirilKirkov\WpInvoices\CreateClient;
use KirilKirkov\WpInvoices\CreateItem;
use KirilKirkov\WpInvoices\Items;
use KirilKirkov\WpInvoices\InvoicesList;
use KirilKirkov\WpInvoices\SendInvoice;
use KirilKirkov\WpInvoices\Charts;
use KirilKirkov\WpInvoices\Woo;
// Public classes
use KirilKirkov\WpInvoices\ShortCodes;
use KirilKirkov\WpInvoices\WpInvoicesPdf;

if(!class_exists('KirilKirkovWpInvoices')) {

	class KirilKirkovWpInvoices
	{
		private static $instance;

		private function __construct()
		{
			$this->init(); // Sets up all the actions and filters
		}

		public static function getInstance()
		{
			if ( !self::$instance ) {
				self::$instance = new KirilKirkovWpInvoices();
			}

			return self::$instance;
		}

		private function init()
		{
			// Handle main init funcs
			add_action( 'init', array( $this, 'main_init' ) );

			// Register the options with the settings API
			add_action( 'admin_init', array( $this, 'admin_init' ) );

			// Add the menu and setting page
			add_action( 'admin_menu', array( $this, 'setup_admin' ) );

			// woocommerce
			$Woo = new Woo();
			add_action( 'woocommerce_loaded', function() use ($Woo) {
				// add metabox and columns only if woocommerce is active;
				if($Woo->hasActiveWoocommerce()) {
					add_action( 'add_meta_boxes', array($Woo, 'add_invoice_box'), 10, 2 );
					
					// HPOS-based
					if(!$Woo->is_cpt_orders_page()) {
						add_filter( 'manage_woocommerce_page_wc-orders_columns', array($Woo, 'add_invoice_column'), 20);
						add_action( 'manage_woocommerce_page_wc-orders_custom_column', array($Woo, 'add_invoice_column_value_hpos'), 20, 2);
					} else {
						// CPT-based
						add_filter( 'manage_edit-shop_order_columns', array($Woo, 'add_invoice_column'), 20 );
						add_action( 'manage_shop_order_posts_custom_column', array($Woo, 'add_invoice_column_value_cpt'), 20, 2);	
					}
				}
			} );

			// Set Screen Options Saving Filters
			function kirilkirkovwipdf_invoices_list_page_set_screen_option($status, $option, $value) {
				if ('kirilkirkovwipdf_invoices_list_per_page' === $option || 
				'kirilkirkovwipdf_clients_list_per_page' === $option || 
				'kirilkirkovwipdf_items_list_per_page' === $option) {
					return $value;
				}
			}
			add_filter('set-screen-option', 'kirilkirkovwipdf_invoices_list_page_set_screen_option', 10, 3);

			// admin scripts
			add_action('admin_enqueue_scripts', array($this, 'load_admin_assets'));

			// xhr
			add_action('wp_ajax_kirilkirkov_wp_inv_select_clients', array($this, 'kirilkirkov_wp_inv_select_clients') );
			add_action('wp_ajax_kirilkirkov_wp_inv_select_client_by_id', array($this, 'kirilkirkov_wp_inv_select_client_by_id') );
			add_action('wp_ajax_kirilkirkov_wp_inv_select_items', array($this, 'kirilkirkov_wp_inv_select_items') );
			add_action('wp_ajax_kirilkirkov_wp_inv_select_customers', array($this, 'kirilkirkov_wp_inv_select_customers') );
			add_action('wp_ajax_kirilkirkov_wp_inv_change_inv_paid_status', array($this, 'kirilkirkov_wp_inv_change_inv_paid_status') );

			// activation
			register_activation_hook( __FILE__, array($this, 'plugin_activation') );
			register_deactivation_hook( __FILE__, array( $this, 'plugin_deactivation' ) );

			// shortcodes
			$shortCodes = new ShortCodes();
			$shortCodes->init();

			PeriodicInvoices::addCronjob();
		}

		/**
		 * Main init function.
		 * Can handle another plugins hooks, etc.
		 */
		public function main_init()
		{
			// WooCommerce hooks
			$Woo = new Woo;
			if($Woo->hasActiveWoocommerce() && $Woo->hasEnabledAutoCreateInvoices()) {
				add_action( 'woocommerce_before_thankyou', array($Woo, 'new_order_created'), 10, 1 );
				add_action( 'woocommerce_new_order', array($Woo, 'new_order_created'), 10, 1 );
				add_action( 'woocommerce_checkout_order_processed', array($Woo, 'new_order_created'), 10, 1 );
				add_action( 'woocommerce_order_status_changed', array($Woo, 'order_status_changed'), 10, 3 );	
			}
		}

		/**
		 * Hook on activate plugin
		 * create table if not exists
		 * create default options
		 */
		public function plugin_activation()
		{
			Clients::create_tables();
			Invoices::create_tables();
			InvoicesAData::create_tables();
			Items::create_tables();
			PeriodicInvoices::create_tables();

			Invoices::add_default_options();
		}

		public function plugin_deactivation()
		{
			$shortCodes = new ShortCodes();
			$shortCodes->remove_cron();

			PeriodicInvoices::removeCronjob();
		}

		public function admin_init()
		{
			if (!is_admin()) {
				wp_die( esc_html__( 'This code is for admin area only', 'kirilkirkov-pdf-invoice-manager' ) );
			}
			
			foreach(Config::get_groups_input_fieds() as $group => $inputs) {
				foreach($inputs as $input) {
					if (strpos($input, 'file') !== false) {
						register_setting($group, Config::INPUTS_PREFIX.$input, array(
							'sanitize_callback' => array($this, "handle_{$input}")
						));
						continue;
					}
					register_setting($group, Config::INPUTS_PREFIX.$input, array(
						'sanitize_callback' => array($this, 'sanitize_setting')
					));
				}
			}

			Invoices::handle_download_inv();
			Charts::handle_export_csv();
		}

		/**
		 * Sanitize settings input
		 */
		public function sanitize_setting($input)
		{
			if (is_array($input)) {
				return array_map('sanitize_text_field', $input);
			}
			
			return sanitize_text_field($input);
		}

		/**
		 * Handle upload invoices company logo
		 */
		public function handle_logo_file($option)
		{
			if(!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])), Config::COMPANY_INPUT_GROUP . '-options')) {
				wp_die(esc_html__('Invalid nonce', 'kirilkirkov-pdf-invoice-manager'));
			}
			
			if(!empty($_FILES[Config::INPUTS_PREFIX."logo_file"]["tmp_name"])) {
				$urls = wp_handle_upload($_FILES[Config::INPUTS_PREFIX."logo_file"], array('test_form' => FALSE));
				if(!isset($urls['error']) && isset($urls['url'])) {
					return json_encode($urls);
				}
			}
			
			return get_option( Config::INPUTS_PREFIX.'logo_file' );
		}

		public function setup_admin()
		{
			// add settings page
			add_options_page( esc_html__( 'WP Invoices Settings', 'kirilkirkov-pdf-invoice-manager' ), esc_html__( 'WP Invoices', 'kirilkirkov-pdf-invoice-manager' ), 'administrator', Config::SETTINGS_GET_PARAM, array( $this, 'admin_settings_page' ) );

			// invoices
			global $kirilkirkovwipdf_invoices_list_per_page;
			$kirilkirkovwipdf_invoices_list_per_page = add_menu_page(esc_html__('WP Invoices', 'kirilkirkov-pdf-invoice-manager') , esc_html__('WP Invoices', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::TOP_LEVEL_INVOICES_PAGE_SLUG, array(new InvoicesList, 'list_invoices_page'), 'dashicons-media-document');
			add_action( "load-{$kirilkirkovwipdf_invoices_list_per_page}", [ new InvoicesList, 'screen_option_invoices' ] );

			add_submenu_page(Config::TOP_LEVEL_INVOICES_PAGE_SLUG, esc_html__('WP Invoices - Create Invoice', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Create Invoice', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_CREATE_INVOICE_PAGE_SLUG, array(new CreateInvoice, 'create'), 1);
			
			// periodic invoices
			add_submenu_page(Config::TOP_LEVEL_INVOICES_PAGE_SLUG, esc_html__('WP Invoices - Periodic Invoices', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Periodic Invoices', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_PERIODIC_INVOICES_PAGE_SLUG, array(new PeriodicInvoices, 'list_page'), 2);
			add_submenu_page('kkwp-inv-page-no-parent', esc_html__('Edit Periodic Invoice Options', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Edit Periodic Invoice Options', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_PERIODIC_INVOICES_EDIT_PAGE_SLUG, array(new PeriodicInvoices, 'edit_page'), 4);

			// preview inv
			add_submenu_page('kkwp-inv-page-no-parent', esc_html__('Preview Invoice', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Preview Invoice', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_PREVIEW_INVOICE_PAGE_SLUG, array(new Invoices, 'preview_inv_page'), 3);
			// send inv
			add_submenu_page('kkwp-inv-page-no-parent', esc_html__('Send Invoice', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Send Invoice', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_SEND_INVOICE_PAGE_SLUG, array(new Invoices, 'send_inv_page'), 4);
			// charts invoices
			add_submenu_page(Config::TOP_LEVEL_INVOICES_PAGE_SLUG, esc_html__('Charts Invoices', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Charts Invoices', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_CHARTS_INVOICE_PAGE_SLUG, array(new Charts, 'charts_inv_page'), 5);

			// clients
			global $kirilkirkovwipdf_clients_list_per_page;
			$kirilkirkovwipdf_clients_list_per_page = add_submenu_page(Config::TOP_LEVEL_INVOICES_PAGE_SLUG, esc_html__('WP Invoices - Clients', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Clients', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_CLIENTS_PAGE_SLUG, array(new Clients, 'clients_page'), 6);
			add_action( "load-{$kirilkirkovwipdf_clients_list_per_page}", [ new Clients, 'screen_option_clients' ] );
			add_submenu_page(Config::TOP_LEVEL_INVOICES_PAGE_SLUG, esc_html__('WP Invoices - Create Client', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Create Client', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_CREATE_CLIENT_PAGE_SLUG, array(new CreateClient, 'create_client_page'), 7);

			// items
			global $kirilkirkovwipdf_items_list_per_page;
			$kirilkirkovwipdf_items_list_per_page = add_submenu_page(Config::TOP_LEVEL_INVOICES_PAGE_SLUG, esc_html__('WP Invoices - Items', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Items', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_ITEMS_PAGE_SLUG, array(new Items, 'items_page'), 8);
			add_action( "load-{$kirilkirkovwipdf_items_list_per_page}", [ new Items, 'screen_option_items' ] );
			add_submenu_page(Config::TOP_LEVEL_INVOICES_PAGE_SLUG, esc_html__('WP Invoices - Create Item', 'kirilkirkov-pdf-invoice-manager'), esc_html__('Create Item', 'kirilkirkov-pdf-invoice-manager'), 'manage_options', Config::SUB_MENU_CREATE_ITEM_PAGE_SLUG, array(new CreateItem, 'create_item_page'), 9);
		}

		/**
		 * Admin settings page
		 */
		public function admin_settings_page() 
		{	 
			add_settings_section( 'invoices', esc_html__( 'Invoices', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_invoices'), 'invoices' );
			add_settings_section( 'clients_page', esc_html__( 'Clients Page', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_clients_page'), 'clients_page' );
			add_settings_section( 'company', esc_html__( 'Company', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_company'), 'company' );
			add_settings_section( 'templates', esc_html__( 'Templates', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_templates'), 'templates' );
			add_settings_section( 'woocommerce', esc_html__( 'WooCommerce', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_woocommerce'), 'woocommerce' );
			add_settings_section( 'payments', esc_html__( 'Payments', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_payments'), 'payments' );
			add_settings_section( 'currency_exhange', esc_html__( 'Currency Exhange', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_currency_exhange'), 'currency_exhange' );
			add_settings_section( 'api-integration', esc_html__( 'Api Integration', 'kirilkirkov-pdf-invoice-manager' ), array($this, 'section_settings_api_integration'), 'api-integration' );

			$Config = Config::class;

			require 'Includes/Admin/SettingsForm.php';
		}

		/**
		 * Section Settings->Invoices
		 */
		public function section_settings_invoices()
		{
			$Config = Config::class;

			require 'Includes/Admin/Views/SettingsForm/Invoices.php';
		}

		/**
		 * Section Settings->Clients Page
		 */
		public function section_settings_clients_page()
		{
			$Config = Config::class;
			$ShortCodes = ShortCodes::class;

			require 'Includes/Admin/Views/SettingsForm/ClientsPage.php';
		}

		/**
		 * Section Settings->Company
		 */
		public function section_settings_company()
		{
			$Config = Config::class;

			require 'Includes/Admin/Views/SettingsForm/Company.php';
		}

		/**
		 * Section Settings->Templates
		 */
		public function section_settings_templates()
		{
			$Config = Config::class;

			require 'Includes/Admin/Views/SettingsForm/Templates.php';
		}

		/**
		 * Section Settings->WooCommerce
		 */
		public function section_settings_woocommerce()
		{
			$Config = Config::class;
			$Woo = new Woo;

			require 'Includes/Admin/Views/SettingsForm/Woocommerce.php';
		}

		/**
		 * Section Settings->WooCommerce
		 */
		public function section_settings_payments()
		{
			$Config = Config::class;
			$Woo = new Woo;

			require 'Includes/Admin/Views/SettingsForm/Payments.php';
		}

		/**
		 * Section Settings->Api Integration
		 */
		public function section_settings_api_integration()
		{
			$Config = Config::class;
			$Woo = new Woo;

			require 'Includes/Admin/Views/SettingsForm/Api_Integration.php';
		}

		/**
		 * Section Settings->Currency Exchange
		 */
		public function section_settings_currency_exhange()
		{
			$Config = Config::class;

			require 'Includes/Admin/Views/SettingsForm/CurrencyExchange.php';
		}

		/**
		 * Load css/js libs and styles for plugin pages
		 */
		public function load_admin_assets($hook)
		{
			// is open our plugin
			$current_screen = get_current_screen();
			if(Config::is_current_screen_in_pages($current_screen->base)) {

				// core lib scripts
				wp_enqueue_script( 'jquery-ui-core' );
				wp_enqueue_script( 'jquery-ui-datepicker' );
				wp_enqueue_script( 'jquery-ui-sortable' );
				wp_enqueue_style( 'jquery-ui-css', esc_url(plugins_url('Includes/Admin/Assets/Css/jquery-ui/themes/smoothness/jquery-ui.min.css', __FILE__ )), array(), '1.0.0', 'all' );

				// main core css
				wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-core-css', esc_url(plugins_url('Includes/Admin/Assets/Css/core.css', __FILE__ )), array(), '1.0.0', 'all' );

				// admin js/css
				wp_enqueue_script(Config::SCRIPTS_PREFIX.'boot-admin-js', esc_url(plugins_url('Includes/Admin/Assets/Js/admin.js', __FILE__ )), array(), '1.0.0', true);
				wp_localize_script(Config::SCRIPTS_PREFIX.'boot-admin-js', 'kkpdfim_datepicker_data', array (
					'datepicker_format' => Config::get_dates_format_type(true)
				));

				wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-admin-css', esc_url(plugins_url('Includes/Admin/Assets/Css/admin.css', __FILE__ )), array(), '1.0.0', 'all' );
				wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-api-doc-css', esc_url(plugins_url('Includes/Admin/Assets/Css/api-documentation.css', __FILE__ )), array(), '1.0.0', 'all' );

				// only create invoice page
				if(strpos($current_screen->base, Config::SUB_MENU_CREATE_INVOICE_PAGE_SLUG) !== false) {
					wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-create-invoice-css', esc_url(plugins_url('Includes/Admin/Assets/Css/create-invoice.css', __FILE__ )), array(), '1.0.0', 'all' );
				}

				// only preview invoice page
				if(strpos($current_screen->base, Config::SUB_MENU_PREVIEW_INVOICE_PAGE_SLUG) !== false) {
					wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-preview-invoice-css', esc_url(plugins_url('Includes/Admin/Assets/Css/preview-invoice.css', __FILE__ )), array(), '1.0.0', 'all' );
					wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-preview-stabilization-invoice-css', esc_url(plugins_url('Includes/Admin/Assets/Css/preview-invoice-stabilization.css', __FILE__ )), array(), '1.0.0', 'all' );
					$custom_css = "
						@font-face {
							font-family: 'DejaVu Sans';
							font-style: normal; 
							src: url('" . esc_url(plugins_url('Includes/Fonts/DejaVuSans.ttf', __FILE__)) . "') format('truetype');
						}
					";
					wp_add_inline_style( Config::SCRIPTS_PREFIX.'boot-preview-invoice-css', $custom_css );
				}

				// only create clients page js
				if(strpos($current_screen->base, Config::SUB_MENU_CREATE_CLIENT_PAGE_SLUG) !== false) {
					wp_enqueue_script(Config::SCRIPTS_PREFIX.'boot-create-clients-js', esc_url(plugins_url('Includes/Admin/Assets/Js/create-clients.js', __FILE__ )), array(), '1.0.0', true);
				}

				// only invoices list page js
				if(strpos($current_screen->base, Config::TOP_LEVEL_INVOICES_PAGE_SLUG) !== false) {
					// Source code: https://github.com/select2/select2
					wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-inv-list-select2-css', esc_url(plugins_url('Includes/Admin/Assets/Css/select2.min.css', __FILE__ )), array(), '1.0.0', 'all');
					wp_enqueue_script('select2-js', esc_url(plugins_url('Includes/Admin/Assets/Js/select2.min.js', __FILE__ )), array(), '1.0.0', false);

					wp_enqueue_style(Config::SCRIPTS_PREFIX.'boot-inv-list-css', esc_url(plugins_url('Includes/Admin/Assets/Css/invoices-list.css', __FILE__ )), array(), '1.0.0', 'all' );
					wp_enqueue_script(Config::SCRIPTS_PREFIX.'boot-inv-list-js', esc_url(plugins_url('Includes/Admin/Assets/Js/invoices-list.js', __FILE__ )), array(), '1.0.0', true);
					// add custom data to boot-inv-list.js
					$date_format = Config::get_dates_format_type(true);
					wp_localize_script(Config::SCRIPTS_PREFIX.'boot-inv-list-js', 'kkpdfim_inv_data', array (
						'select_item' => array(
							'ajax_url' => admin_url( 'admin-ajax.php' ),
							'action_change_stat' => 'kirilkirkov_wp_inv_change_inv_paid_status',
							'nonce' => wp_create_nonce( 'change_inv_paid_status' ),
						),
						'date_format' => $date_format,
					));
				}

				// only create invoice page js
				if(strpos($current_screen->base, Config::SUB_MENU_CREATE_INVOICE_PAGE_SLUG) !== false) {
					// Source code: https://github.com/josdejong/mathjs
					wp_enqueue_script('math-js', esc_url(plugins_url('Includes/Admin/Assets/Js/math.min.js', __FILE__ )), array(), '1.0.0', true);
					wp_enqueue_script(Config::SCRIPTS_PREFIX.'boot-create-invoice-js', esc_url(plugins_url('Includes/Admin/Assets/Js/create-invoice.js', __FILE__ )), array(), '1.0.0', true);
					// add custom data to create-invoice.js
					wp_localize_script(Config::SCRIPTS_PREFIX.'boot-create-invoice-js', 'kkpdfim_inv_data', array (
						'invoice_type' => array(
							'invoice' => esc_html__('Invoice', 'kirilkirkov-pdf-invoice-manager'),
							'pro_forma' => esc_html__('Pro-forma', 'kirilkirkov-pdf-invoice-manager'),
							'debit_note' => esc_html__('Debit note', 'kirilkirkov-pdf-invoice-manager'),
							'credit_note' => esc_html__('Credit note', 'kirilkirkov-pdf-invoice-manager'),
						),
						'create_document' => array( 
							'round_to' => (int)get_option( Config::INPUTS_PREFIX.'count_decimal_digits' ),
							'enabled_calculator' => !(bool)get_option(Config::INPUTS_PREFIX.'disabled_js_calc'),
							'border_color_fields' => '#ced4da',
							'border_color_wrong' => 'red',
							'selected_currency' => Config::get_selected_currency(),
							'is_edit_mode' => filter_input( INPUT_GET, 'edit' ) !== null,
						),
						'select_client' => array(
							'ajax_url' => admin_url( 'admin-ajax.php' ),
							'action_select_client' => 'kirilkirkov_wp_inv_select_clients',
							'client_icon' => '<span class="dashicons dashicons-businessperson mr-2"></span>',
							'undefined_error' => esc_html__('Update error. Undefined reason.', 'kirilkirkov-pdf-invoice-manager'),
						),
						'select_client_by_query_param' => array(
							'ajax_url' => admin_url( 'admin-ajax.php' ),
							'action_select_client' => 'kirilkirkov_wp_inv_select_client_by_id',
							'client_icon' => '<span class="dashicons dashicons-businessperson mr-2"></span>',
							'undefined_error' => esc_html__('Update error. Undefined reason.', 'kirilkirkov-pdf-invoice-manager'),
						),
						'select_item' => array(
							'ajax_url' => admin_url( 'admin-ajax.php' ),
							'action_select_item' => 'kirilkirkov_wp_inv_select_items',
							'item_icon' => '<span class="dashicons dashicons-products mr-2"></span>',
							'undefined_error' => esc_html__('Update error. Undefined reason.', 'kirilkirkov-pdf-invoice-manager'),
							'low_quantity_warning' => esc_html__('Keep in mind that quantity for this item is lower than chosen.', 'kirilkirkov-pdf-invoice-manager'),
						),
						'select_customer' => array(
							'ajax_url' => admin_url( 'admin-ajax.php' ),
							'action_select_customer' => 'kirilkirkov_wp_inv_select_customers',
							'customer_icon' => '<span class="dashicons dashicons-businessperson mr-2"></span>',
							'undefined_error' => esc_html__('Update error. Undefined reason.', 'kirilkirkov-pdf-invoice-manager'),
						)
					));
				}

				// only invoices charts page js
				if(strpos($current_screen->base, Config::SUB_MENU_CHARTS_INVOICE_PAGE_SLUG) !== false) {
					// Source code: https://github.com/chartjs/Chart.js
					wp_enqueue_script('chart-js', esc_url(plugins_url('Includes/Admin/Assets/Js/chart.js', __FILE__ )), array(), '1.0.0', false);
					wp_enqueue_script(Config::SCRIPTS_PREFIX.'boot-inv-charts-js', esc_url(plugins_url('Includes/Admin/Assets/Js/invoices-charts.js', __FILE__ )), array(), '1.0.0', true);
					$dates = Charts::get_dates();

					// add custom data to invoices-charts.js
					wp_localize_script(Config::SCRIPTS_PREFIX.'boot-inv-charts-js', 'kkpdfim_inv_charts_data', array (
						'charts' => array(
							'by_type' => array(
								'title' => esc_html__('Count of issued invoices', 'kirilkirkov-pdf-invoice-manager'),
								'series_name' => esc_html__('Issued', 'kirilkirkov-pdf-invoice-manager'),
								'period_values' => Charts::get_issued_by_period(),
							),
							'num_by_month' => array(
								'title' => esc_html__('Count of issued invoices by month', 'kirilkirkov-pdf-invoice-manager'),
								'categories' => Charts::get_issued_count_by_month_categories(),
								'series' => Charts::get_count_by_month(),
							),
							'amount_by_month' => array(
								'title' => esc_html__('Amount of issued invoices by month', 'kirilkirkov-pdf-invoice-manager'),
								'categories' => Charts::get_issued_count_by_month_categories(),
								'series' => Charts::get_count_by_month(true),
							),
						)
					));
				}
			}
		}

		/**
		 * Xhr request
		 * Select list of clients
		 */
		public function kirilkirkov_wp_inv_select_clients()
		{
			if (!is_admin() || !current_user_can('manage_options')) {
				wp_die( esc_html__( 'This code is for admin area only', 'kirilkirkov-pdf-invoice-manager' ) );
			}

			$search = trim( sanitize_text_field( wp_unslash( filter_input( INPUT_GET, 'search' ) ?? '' ) ) );

			wp_send_json([
				'status' => 'success',
				'data' => Clients::get_clients($search),
			], 200);

			wp_die();
		}

		/**
		 * Xhr request
		 * Select client by ID when click "Create Invoice" from clients list page.
		 */
		public function kirilkirkov_wp_inv_select_client_by_id()
		{
			if (!is_admin() || !current_user_can('manage_options')) {
				wp_die( esc_html__( 'This code is for admin area only', 'kirilkirkov-pdf-invoice-manager' ) );
			}

			$client_id = trim( sanitize_text_field( wp_unslash( filter_input( INPUT_GET, 'client_id' ) ?? '' ) ) );

			wp_send_json([
				'status' => 'success',
				'data' => Clients::get_client($client_id),
			], 200);

			wp_die();
		}

		/**
		 * Xhr request
		 * Select list of items
		 */
		public function kirilkirkov_wp_inv_select_items()
		{
			if (!is_admin() || !current_user_can('manage_options')) {
				wp_die( esc_html__( 'This code is for admin area only', 'kirilkirkov-pdf-invoice-manager' ) );
			}

			$search = trim( sanitize_text_field( wp_unslash( filter_input( INPUT_GET, 'search' ) ?? '' ) ) );
			
			wp_send_json([
				'status' => 'success',
				'data' => Items::get_items($search),
			], 200);

			wp_die();
		}


		/**
		 * Xhr request
		 * Select list of items
		 */
		public function kirilkirkov_wp_inv_select_customers()
		{
			if (!is_admin() || !current_user_can('manage_options')) {
				wp_die( esc_html__( 'This code is for admin area only', 'kirilkirkov-pdf-invoice-manager' ) );
			}

			$search = trim( sanitize_text_field( wp_unslash( filter_input( INPUT_GET, 'search' ) ?? '' ) ) );
			
			$wp_user_query = new \WP_User_Query(
				array(
				  'search' => "*{$search}*",
				  'search_columns' => array(
				  'user_login',
				  'user_nicename',
				  'user_email',
				),
			  
			));
			$users = $wp_user_query->get_results();

			if(count($users) < 1) {
				wp_send_json([
					'status' => 'success',
					'data' => [],
				], 200);
				wp_die();
			}
			
			$result = [];
			foreach($users as $k => $user) {
				unset($users[$k]);
				$result[] = [
					'id' => $user->data->ID,
					'user_login' => $user->data->user_login,
					'user_email' => $user->data->user_email
				];
			}

			wp_send_json([
				'status' => 'success',
				'data' => $result,
			], 200);

			wp_die();
		}

		/**
		 * Xhr request
		 * Change invoice payment status from list invoices
		 */
		public function kirilkirkov_wp_inv_change_inv_paid_status()
		{
			if(!isset($_POST['nonce']) || !wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['nonce'])), 'change_inv_paid_status' )) {
				wp_send_json([
					'status' => 'error',
					'message' => esc_html__('Security check failed!', 'kirilkirkov-pdf-invoice-manager'),
				], 403);
	
				wp_die();
			}

			if (!is_admin()) {
				wp_die( esc_html__( 'This code is for admin area only', 'kirilkirkov-pdf-invoice-manager' ) );
			}

			if(!isset($_POST['status']) || !in_array((int)$_POST['status'], array(0, 1, 2)) 
			|| !isset($_POST['inv_id']) || (int)$_POST['inv_id'] < 1) {
				return;
			}

			Invoices::change_inv_paid_status((int)$_POST['inv_id'], (int)$_POST['status']);
			
			wp_send_json([
				'status' => 'success',
			], 200);

			wp_die();
		}
	}

	$kirilkirkovwipdf_WpInvoicesInstance = KirilKirkovWpInvoices::getInstance();
}
