<?php

if (!defined('ABSPATH'))
	exit;

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://sourcecode-agency.it/
 * @since      1.0.0
 *
 * @package    polylai
 * @subpackage polylai/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    polylai
 * @subpackage polylai/admin
 * @author     Diego Imbriani <diego@sourcecode.team>
 */
class polylai_Admin
{

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	private $cron;

	private $rating_postponed;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct($plugin_name, $version)
	{

		$this->plugin_name = $plugin_name;
		$this->version = rand(1, 10000); // $version;
		$this->cron = polylai_Cron::getInstance();
		$this->rating_postponed = false;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{
		wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/style.css', array(), $this->version, 'all');
		$user = wp_get_current_user();
		if (in_array('author', (array) $user->roles)) {
			wp_enqueue_style($this->plugin_name . "-author", plugin_dir_url(__FILE__) . 'css/polylai-translator-author.css', array(), $this->version, 'all');
		}
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts()
	{
		wp_enqueue_script("freemius-checkout", "https://checkout.freemius.com/js/v1/", [], $this->version, false);
		wp_enqueue_script("alpine", "https://cdn.jsdelivr.net/npm/alpinejs@3.14.8/dist/cdn.min.js", ['jquery'], $this->version, ['strategy' => 'defer']);

		wp_register_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/polylai-translator-admin.js', ['jquery', 'alpine'], $this->version);

		$vars = [
			'polylai_ws_url' => POLYLAI_WS_URL,
			'polylai_credits_license' => get_option('polylai_credits_license'),
			'polylai_credits_nonce' => wp_create_nonce('polylai_credits_license_nonce'),
			'polylai_settings_nonce' => wp_create_nonce('polylai_settings_nonce'),
		];
		wp_localize_script($this->plugin_name, 'polylaiVars', $vars);
		wp_enqueue_script($this->plugin_name);
	}

	public function row_actions($actions, $post)
	{
		$type = get_post_type($post->ID);
		$allowed = ["post", "page"];

		if (!in_array($type, $allowed) && !polylai_fs()->can_use_premium_code__premium_only()) {
			return $actions;
		}


		if (current_user_can('edit_post', $post->ID)) {
			$nonce = wp_create_nonce('polylai_nonce');
			$actions['polylaitr'] = sprintf(
				'<a data-id="%d" data-nonce="%s" class="polylaitr-link">Translate</a>',
				$post->ID,
				$nonce
			);
		}
		return $actions;
	}

	public function create_translation_post_type()
	{
		$labels = array(
			'name' => _x('Translations', 'post type general name', 'ai-translator-for-polylang'),
			'singular_name' => _x('Translation', 'post type singular name', 'ai-translator-for-polylang'),
		);

		$args = array(
			'labels' => $labels,
			'public' => false,
			'publicly_queryable' => false,
			'show_ui' => false,
			'show_in_menu' => false,
			'query_var' => true,
			'rewrite' => array('slug' => 'polylai-translation'),
			'capability_type' => 'post',
			'has_archive' => true,
			'hierarchical' => false,
		);

		register_post_type('polylai-translation', $args);
	}

	public function show_translation_modal()
	{
		if (
			wp_verify_nonce(
				sanitize_text_field(
					wp_unslash($_REQUEST['polylai_nonce'])
				),
				'polylai_nonce'
			)
		) {
			$is_premium = polylai_fs()->can_use_premium_code__premium_only();
			require_once plugin_dir_path(__FILE__) . 'partials/translations-modal.php';
			wp_die();
		} else {
			wp_nonce_ays('');
		}
	}

	public function show_pricing()
	{
		if (
			wp_verify_nonce(
				sanitize_text_field(
					wp_unslash($_REQUEST['nonce'])
				),
				'polylai_show_pricing'
			)
		) {
			$pricing = $this->get_pricing();
			require_once plugin_dir_path(__FILE__) . 'partials/pricing.php';
			wp_die();
		} else {
			wp_nonce_ays();
		}
	}

	public function admin_menu()
	{
		//
		add_menu_page(
			__('Settings', 'ai-translator-for-polylang'),
			__('PolylAI Translator', 'ai-translator-for-polylang'),
			'manage_options',
			'polylai',
			[$this, 'settings_page'],
			plugin_dir_url(__FILE__) . 'img/icon-circle.svg',
			5
		);
		add_submenu_page(
			'polylai',
			__('Translations', 'ai-translator-for-polylang'),
			__('Translations', 'ai-translator-for-polylang'),
			'manage_options',
			'polylai-queue',
			[$this, 'queue_page']
		);
		add_submenu_page(
			'polylai',
			__('Bulk translations', 'ai-translator-for-polylang'),
			__('Bulk translations', 'ai-translator-for-polylang'),
			'manage_options',
			'polylai-bulk',
			[$this, 'bulk_page']
		);
		add_submenu_page(
			'polylai',
			__('Tutorial', 'ai-translator-for-polylang'),
			__('Tutorial', 'ai-translator-for-polylang'),
			'manage_options',
			'polylai-tutorial',
			[$this, 'tutorial']
		);
	}

	public function bulk_page()
	{
		require_once plugin_dir_path(__FILE__) . 'partials/bulk.php';
	}

	public function tutorial()
	{
		require_once plugin_dir_path(__FILE__) . 'partials/tutorial.php';
	}

	private function get_pricing()
	{
		$response = wp_remote_post(POLYLAI_WS_URL . "/pricing", [
			'timeout' => 100000,
			'method' => 'GET',
			'blocking' => true
		]);
		return $response;
	}

	public function register_post_status()
	{
		register_post_status('translating', ['internal' => true]);
		register_post_status('pending', ['internal' => true]);
		register_post_status('complete', ['internal' => true]);
		register_post_status('error', ['internal' => true]);
	}

	public function settings_page()
	{
		$svc_comm = true;
		require_once plugin_dir_path(__FILE__) . 'partials/settings.php';
	}

	public function queue_page()
	{
		require_once plugin_dir_path(__FILE__) . 'partials/queue.php';
	}

	public function handle_rating()
	{
		if (isset($_POST['polylai_rating_action'])) {
			if (wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['polylai_rating_nonce'])), 'polylai_rating_asked')) {
				if ($_POST['polylai_rating_action'] == 'remind') {
					$cookie_name = 'polylai_suspend_notice';
					$cookie_value = '1';
					$cookie_expiry = time() + (2 * 24 * 60 * 60); // 2 days from now

					// Set the cookie
					setcookie($cookie_name, $cookie_value, $cookie_expiry, "/");
					$this->rating_postponed = true;
					return;
				}
				if ($_POST['polylai_rating_action'] == 'done') {
					update_option('polylai_rating_asked', true);
					return;
				}
			} else {
				wp_nonce_ays();
			}
		}
	}

	public function handle_restart()
	{
		global $wpdb;

		if (isset($_POST['polylai_restart'])) {
			if (wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['polylai_restart_nonce'])), 'polylai_restart_nonce')) {
				delete_transient(polylai_Cron::LOCK_TRANSIENT_KEY);
			} else {
				wp_nonce_ays();
			}
		}
		wp_die();
	}

	public function save_credits_license()
	{
		if (wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['polylai_credits_license_nonce'])), 'polylai_credits_license_nonce')) {
			$license_key = sanitize_text_field($_POST['polylai_credits_license']);
			update_option('polylai_credits_license', $license_key);
			header("Content-type: application/json");
			echo wp_json_encode(['success' => true, 'valid' => true]);

			wp_die();
		} else {
			wp_nonce_ays();
		}
	}

	public function check_commands()
	{
		if (isset($_POST['polylai_restart'])) {
			delete_transient(polylai_Cron::LOCK_TRANSIENT_KEY);
			delete_transient(polylai_Cron::ACTIVITY_TRANSIENT_KEY);
		}
	}

	public function register_api()
	{
		register_rest_route('polylai/v1', '/cron', array(
			'methods' => 'GET',
			'callback' => [$this->cron, 'execCron'],
			'permission_callback' => function () {
				return true;
				$user = wp_get_current_user();
				if (in_array('author', (array) $user->roles)) {
					return true;
				}
				if (in_array('editor', (array) $user->roles)) {
					return true;
				}
				if (in_array('administrator', (array) $user->roles)) {
					return true;
				}
				return false;
			}
		));
	}

	private function run_http_cron()
	{
		$cron_url = home_url('/index.php?action=polylai_run_cron');

		try {
			wp_remote_get($cron_url, [
				'timeout' => 1,
				'blocking' => false
			]);
		} catch (Exception $e) {
			polylai_Utils::db_log('error', 'run_http_cron', $e->getMessage());
		}
	}

	public function polylai_run_cron()
	{
		if (wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['nonce'])), 'polylai_run_cron')) {
			$this->run_http_cron();
		} else {
			wp_nonce_ays();
		}
	}
	

	public function action_links($links)
	{
		$links[] = '<a href="options-general.php?page=polylai-translator-options">Settings</a>';
		return $links;
	}

	public function get_logs()
	{
		if (!isset($_POST['polylai_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['polylai_nonce'])), 'polylai_nonce')) {
			wp_send_json_error(['message' => 'Invalid nonce']);
			wp_die();
		}

		global $wpdb;

		$logs = [];
		$table_name = $wpdb->prefix . 'polylai_log';
		$query = $wpdb->prepare("SELECT `time`, `type`, `operation`, `post_id`, `post_title`, `message` FROM %i ORDER BY id DESC LIMIT 100", $table_name);
		$results = $wpdb->get_results($query);
		foreach ($results as $key => $row) {
			$logs[] = $row;
		}
		header("Content-type: application/json");
		echo wp_json_encode($logs);
		wp_die();
	}

	public function download_logs()
	{
		global $wpdb;

		$logs = [];
		$limit = polylai_Utils::is_debug() ? 1000 : 100;
		$table_name = $wpdb->prefix . 'polylai_log';
		$query = $wpdb->prepare("SELECT * FROM %i ORDER BY id DESC LIMIT %d", $table_name, $limit);
		$results = $wpdb->get_results($query);
		foreach ($results as $key => $row) {
			$logs[] = $row;
		}
		echo wp_json_encode($logs);
		wp_die();
	}
}
