<?php

// If user not in admin area, abort.
defined('DRAGONIZER_ADMIN_INIT') || die();

class Dragonizer_Dashboard extends Dragonizer_Core
{
	public function __construct()
	{
		parent::__construct();

		add_action('wp_ajax_dragonizer_refresh_assets_cache_files', [$this, 'ajax_refresh_assets_cache_files']);
		add_action('wp_ajax_dragonizer_preload_assets_cache_files', [$this, 'ajax_preload_assets_cache_files']);
		add_action('wp_ajax_dragonizer_purge_assets_cache_files', [$this, 'ajax_purge_assets_cache_files']);
		add_action('wp_ajax_dragonizer_assets_cache_file_log', [$this, 'ajax_assets_cache_file_log']);
		add_action('admin_post_deactivate_plugin', [$this, 'deactivate_plugin']);
		add_action('wp_ajax_dragonizer_submit_permissions_policy', [$this, 'dragonizer_submit_permissions_policy']);
		add_action('wp_ajax_dragonizer_clear_log_file', [$this, 'dragonizer_clear_log_file']);

		if (!wp_doing_ajax()) {

			$reset    = $_GET['dragonizer_reset'] ?? null;
			$export   = $_GET['dragonizer_export'] ?? null;
			$import   = $_FILES['imported_file'] ?? null;

			if (!$export && !$import && !$reset) return;

			if ($reset && check_admin_referer('dragonizer_reset', 'dragonizer_secret')) {
				$this->wp_config_clean(['force']);
				DRFS::is_htaccess() && $this->htaccess_clean();
				$this->delete_settings('everything');
				$this->purge_upload_dir();
				$this->purge_all_cache();
				$this->drop_preloading_list();

				$this->delete_all_dragonizer_crons();
				$this->clean_dragonizer_data_from_options(true);

				wp_cache_flush();

				// Clear OPcache
				if (function_exists('opcache_reset')) {
					opcache_reset();
				}

				update_option('delete_dragonizer_object_cache_file', true);

				wp_redirect(add_query_arg(
					['page' => 'dragonizer_main'], 
					admin_url('admin.php')
				));
				exit;
				
			} elseif ($export && check_admin_referer('dragonizer_export', 'dragonizer_secret')) {

				$filename = 'Dragonizer-' . date('Y-m-d');

				nocache_headers();
				@header("Content-type: application/vnd.ms-excel");
				@header("Content-Type: application/force-download");
				@header("Content-Type: application/download");
				@header("Content-disposition: " . $filename . ".json");
				@header("Content-disposition: filename=" . $filename . ".json");

				$settings = $this->settings;
				unset($settings['data']);
				unset($settings['colors']);
				// unset($settings['ssl_secure']);
				unset($settings['login_customizer']['logo']);
				unset($settings['login_customizer']['background']);
				unset($settings['login_customizer']['custom_login']);
				$generate_json = json_encode($settings);

				print $generate_json;
				exit;
			} elseif ($import) {
				if ($import && !empty($import['tmp_name'])) {

					$import_data     = DRFS::read($import['tmp_name']);

					$import_settings = json_decode($import_data, true);

					$allowed = ['modules_status', 'preloading', 'caching', 'object_cache', 'shamsi', 'lazy_load', 'wp_tweaks', 'translator', 'db_optimizer', 'wp_optimizer', 'woo_optimizer', 'copyright', 'maintenance', 'login_customizer', 'ssl_secure', 'minify',];

					$settings = is_array($import_settings) ? array_intersect_key($import_settings, array_flip($allowed)) : [];

					$op = 'toastr.options={progressBar:!0,positionClass:"toast-top-right",rtl:!1}';
					if (is_rtl()) {
						$op = 'toastr.options={progressBar:!0,positionClass:"toast-top-left",rtl:!0};';
					}

					if (count($settings) > 0) {

						if (!dr_is_ssl()) {
							unset($settings['ssl_secure']);
						}

						$this->save_settings($settings, true);
						add_action('admin_enqueue_scripts', function () use ($op) {
							wp_register_script('dragonizer-fadein-msg', '', [], '', true);
							wp_enqueue_script('dragonizer-fadein-msg');
							wp_add_inline_script('dragonizer-fadein-msg', $op . 'toastr["success"]("' . __('Settings imported successfully', 'dragonizer') . '","' . __('Success', 'dragonizer') . '");');
						}, 999999);
					} else {
						add_action('admin_enqueue_scripts', function () use ($op) {
							wp_register_script('dragonizer-fadein-msg', '', [], '', true);
							wp_enqueue_script('dragonizer-fadein-msg');
							wp_add_inline_script('dragonizer-fadein-msg', $op . 'toastr["error"]("' . __('Import settings failed', 'dragonizer') . '","' . __('Failed', 'dragonizer') . '");');
						}, 999999);
					}
				}
			}
		}
	}

	public function dragonizer_clear_log_file()
	{
		// Clear the log file
		DRFS::write(DRAGONIZER_UP_DIR . "/" . dr_get_log_filename(), '');

		wp_send_json_success('Log file cleared.');
	}

	public function dragonizer_submit_permissions_policy()
	{
		if (!current_user_can('manage_options')) {
			wp_die(__('You do not have permission', 'dragonizer'));
		}

		$permissions_policy = $_POST['permissions_array'];

		if (empty($permissions_policy)) {
			wp_die('', 400);
		}

		$old_ssl['ssl_secure'] = $this->get('ssl_secure') ?: [];
		$old_ssl['ssl_secure']['http_headers']['permissions_policy']['values'] = $permissions_policy;

		$this->save_settings($old_ssl);

		wp_die();
	}

	public function deactivate_plugin()
	{
		if (!wp_verify_nonce($_GET['_wpnonce'], 'deactivate_plugin')) {
			wp_nonce_ays('');
		}

		if (!current_user_can('activate_plugins')) {
			$redirect_url = add_query_arg('pc_action', 'generic_permission_err', wp_get_referer());
			wp_safe_redirect(esc_url_raw($redirect_url));
			exit;
		}

		deactivate_plugins($_GET['plugin']);
		wp_safe_redirect(wp_get_referer());
		die();
	}

	public function ajax_purge_assets_cache_files()
	{
		$file_name = $_POST['file'];

		if (empty($file_name)) {
			$file_name = 'all-of-them';
		}

		if ($file_name === 'all-of-them') {
			$this->purge_assets_cache();
		} else {
			DRFS::delete(_dr(DRAGONIZER_ASSETS_CACHE_DIR, $file_name));
			$this->ajax_refresh_assets_cache_files();
		}

		wp_die();
	}

	public function ajax_assets_cache_file_log()
	{
		$file_name = $_POST['file'];

		if (empty($file_name)) {
			wp_die('', 400);
		}
?>
		<div class="drag-dr-modal-wrap dragonizer-tableview">
			<h3 style="margin-top:-30px"><?= $file_name ?></h3>
			<div class="drag-dr-modal-body dragonizer-tableview-holder">
				<table style="max-width:100%">
					<tbody>
						<?php
						$log_file    = DRFS::read(_dr(DRAGONIZER_CACHE_DIR, 'assets', $file_name) . '.log') ?? '';
						$access_file = DRFS::read(_dr(DRAGONIZER_CACHE_DIR, 'assets', $file_name) . '.accessed') ?? '';

						if ($log_file !== '') {
							preg_match_all('/(?:\h-\h.*?->\h)\K(.*\.\b(?:css|js)\b)(?=\h\(No need to minify\))?/', $log_file, $input_files);

							$saved_reque   = preg_match_all('/\((\d+) requests saved\)/m', $log_file, $reque) ? array_sum($reque[1]) : 0;
							$saved_space_k = preg_match_all('/\((\d+\.\d+)[K] saved\)|\((\d+)[K] saved\)/m', $log_file, $space_k) ? array_sum($space_k[1]) : 0;
							$saved_space_m = preg_match_all('/\((\d+\.\d+)[M] saved\)|\((\d+)[M] saved\)/m', $log_file, $space_m) ? array_sum($space_m[1]) * 1024 : 0;
							$saved_space   = $saved_space_k + $saved_space_m;

							foreach ($input_files[0] as $input_file) {
						?>
								<tr>
									<td><?= $input_file ?></td>
								</tr>
						<?php }
						} ?>
					</tbody>
				</table>
			</div>

			<div class="drag-dr-modal-footer">
				<?php
				if ($saved_reque > 0 && $saved_space > 0) { ?>

					<p><?= sprintf(__("Generating this file has optimized loading your site by reducing %1s requests and %2s KB.", 'dragonizer'), $saved_reque, $saved_space) ?></p>
				<?php } elseif ($saved_reque > 0 && $saved_space == 0) { ?>
					<p><?= sprintf(__("Generating this file has optimized loading your site by reducing %s KB.", 'dragonizer'), $saved_reque) ?></p>
				<?php } elseif ($saved_reque == 0 && $saved_space > 0) { ?>
					<p><?= sprintf(__("Generating this file has optimized loading your site by reducing %s requests.", 'dragonizer'), $saved_space) ?></p>
				<?php }

				if ($access_file !== '') {
					$date = dr_substr($access_file, '-', 1);
					$url = substr($access_file, strpos($access_file, "-") + 1);

					if ($date !== '' && $url !== '')
				?>
					<p><?= sprintf(__("This file was last used in <bdo style='direction:ltr'>%1s</bdo> at <a style='text-decoration:none' target='_blank' href='%2s'>this url</a>.", 'dragonizer'), dr_to_shamsi($date), $url) ?></p>
				<?php
				}
				?>
				<button type="button" class="drag-dr-cancel-modal drag-dr-button-secondary"><?php _e('Cancel', 'dragonizer'); ?></button>
			</div>
		</div>
	<?php

		wp_die();
	}

	public function ajax_preload_assets_cache_files()
	{
		$this->make_request(esc_url(add_query_arg(array('dragonizer-create-order-list' => 'true'), site_url())));

		$this->ajax_refresh_assets_cache_files();

		wp_die();
	}

	public function ajax_refresh_assets_cache_files()
	{
		$cached_asset_files = glob(DRAGONIZER_ASSETS_CACHE_DIR . '/*.{js,css}', GLOB_BRACE); ?>
		<div class="dragonizer-tableview-holder">
			<table>
				<thead>
					<tr align="center" valign="middle">
						<td style="width:10%" caption="<?= __('Type', 'dragonizer') ?>"></td>
						<td style="width:40%" caption="<?= __('File Name', 'dragonizer') ?>"></td>
						<td style="width:20%" class="hidden-on-mobile" caption="<?= __('Creation Time', 'dragonizer') ?>"></td>
						<td style="width:20%" class="hidden-on-mobile" caption="<?= __('Last Used Time', 'dragonizer') ?>"></td>
						<td style="width:10%" caption="<?= __('Purge/Log', 'dragonizer') ?>"></td>
					</tr>
				</thead>
				<tbody>
					<?php
					if (count($cached_asset_files) > 0) {

						foreach ($cached_asset_files as $value) {
							$file_name = basename($value);
							if ($file_name === 'global-styles.css') continue;
							$cached_asset_file_log = DRFS::read($value . '.log') ?? '';

							if (!$cached_asset_file_log) continue;

							if (preg_match('/\d{4}\/\d{1,2}\/\d{1,2}\h\d{1,2}\:\d{1,2}:\d{1,2}/', $cached_asset_file_log, $output_array) === false) continue;

							$create_time = $output_array[count($output_array) - 1];

							$accessed_time = __('Unknown', 'dragonizer');
							if (file_exists($value . '.accessed')) {
								$accessed_time = DRFS::read($value . '.accessed');
								$accessed_time = dr_substr($accessed_time, '-', 1);
								if (strtotime('today') <= $accessed_time) {
									$accessed_time = __('Today', 'dragonizer');
								} elseif (strtotime('yesterday') <= $accessed_time) {
									$accessed_time = __('Yesterday', 'dragonizer');
								} elseif (strtotime('this week') <= $accessed_time) {
									$accessed_time = __('This Week', 'dragonizer');
								} elseif (strtotime('this month') <= $accessed_time) {
									$accessed_time = __('This Month', 'dragonizer');
								} else {
									$accessed_time = dr_to_shamsi($accessed_time);
									$accessed_time = "<bdo style=\"direction:ltr\"><?= $accessed_time ?></bdo>";
								}
							}

					?>
							<tr align="center" valign="middle">
								<td>
									<div>
										<?php
										if (dr_ends_with($value, '.js')) { ?>
											<img src="<?= _dr(DRAGONIZER_URL, '/assets/images/other/listview-js.png') ?>" />
										<?php
										} else { ?>
											<img src="<?= _dr(DRAGONIZER_URL, '/assets/images/other/listview-css.png') ?>" />
										<?php
										}
										?>
									</div>
								</td>
								<td>
									<a target="_blank" href="<?= DRFS::local_to_url($value) ?>"><?= $file_name ?></a>
								</td>
								<td class="hidden-on-mobile"><bdo style="direction:ltr"><?= $create_time ?></bdo></td>
								<td class="hidden-on-mobile"><?= $accessed_time ?></td>
								<td>
									<div>
										<img data-file="<?= $file_name ?>" title="<?= __('Purge', 'dragonizer') ?>" class="linked purge-single" src="<?= _dr(DRAGONIZER_URL, '/assets/images/other/listview-purge.png') ?>" />
										<img data-file="<?= $file_name ?>" title="<?= __('Log', 'dragonizer') ?>" class="linked log-single" src="<?= _dr(DRAGONIZER_URL, '/assets/images/other/listview-log.png') ?>" />
									</div>
								</td>
							</tr>
						<?php
						}
					} else {
						?>
						<tr>
							<td colspan="5"><?= __('No files have been cached yet', 'dragonizer') ?></td>
						</tr>
					<?php
					}
					?>

				</tbody>

				<tfoot>
					<tr>
						<td colspan="4">
							<div class="fixed">
								<?php if (count($cached_asset_files) > 0) { ?>
									<img id="purge-all" title="<?= __('Purge all', 'dragonizer') ?>" class="linked" style="width:40px;height:40px" src="<?= _dr(DRAGONIZER_URL, '/assets/images/other/listview-purg-all.png') ?>" />
								<?php
								}
								?>
								<img id="refresh-all" title="<?= __('Refresh', 'dragonizer') ?>" class="linked" style="width:40px;height:40px" src="<?= _dr(DRAGONIZER_URL, '/assets/images/other/listview-refresh.png') ?>" />
								<!-- preload img -->
							</div>
						</td>
					</tr>
				</tfoot>

			</table>
		</div>
<?php

		wp_die();
	}
}

new Dragonizer_Dashboard();
