<?php

namespace JetBackup\Wordpress;

use JetBackup\BackupJob\BackupJob;
use JetBackup\CLI\CLI;
use JetBackup\Cron\Cron;
use JetBackup\Destination\Destination;
use JetBackup\Download\Download;
use JetBackup\Downloader\Downloader;
use JetBackup\Entities\Util;
use JetBackup\Exception\DBException;
use JetBackup\Exception\DestinationException;
use JetBackup\Exception\IOException;
use JetBackup\Exception\JBException;
use JetBackup\Exception\QueueException;
use JetBackup\Factory;
use JetBackup\JetBackup;
use JetBackup\Queue\QueueItem;
use JetBackup\Schedule\Schedule;
use JetBackup\Settings\Updates;
use JetBackup\SGB\Migration;
use JetBackup\UserInput\UserInput;
use SleekDB\Exceptions\InvalidArgumentException;

if (!defined( '__JETBACKUP__')) die('Direct access is not allowed');

class Init {

	private function __construct() { } // only static method

	/**
	 * @throws InvalidArgumentException
	 * @throws \SleekDB\Exceptions\IOException|DestinationException
	 * @throws DBException
	 * @throws IOException
	 * @throws QueueException
	 * @throws JBException
	 */
	public static function actionInit() {
		if (!function_exists('current_user_can') || !current_user_can('manage_options')) return;

		if(Helper::isMultisite()) {

			if(!Helper::isMainSite() || !Helper::isNetworkAdminUser()) return;
			if(Helper::isNetworkAdminInterface()) {
				// This will add menu item also in the network admin page
				add_action('network_admin_menu',                    ['\JetBackup\Wordpress\UI', 'main']);
			}

		}

		add_action('admin_menu',                    ['\JetBackup\Wordpress\UI', 'main']);
		add_action('wp_ajax_jetbackup_api',         ['\JetBackup\Ajax\Ajax',    'main']);

		if (Factory::getSettingsAutomation()->isHeartbeatEnabled()) {
			add_action('admin_footer',                  ['\JetBackup\Wordpress\UI', 'heartbeat']);
			add_action('wp_ajax_jetbackup_heartbeat', ['\JetBackup\Ajax\Ajax', 'heartbeat' ]);
		}


		self::_createWorkingSpace();

		// Migration has to run after workspace created
		(new Migration())->migrate();
		Destination::createDefaultDestination();
		Schedule::createDefaultSchedule();
		
		// Will create the job if not exists
		BackupJob::getDefaultJob();
		BackupJob::getDefaultConfigJob(); // Also create default config export schedule (hidden)
		
		self::_download();
	}

	private static function _download():void {
		try {
			$userInput = new UserInput();
			$userInput->setData($_REQUEST);

			if($download_id = $userInput->getValidated('download_id', 0, UserInput::UINT)) {
				$download = new Download($download_id);
				if(!$download->getId()) throw new JBException('The provided download id not found');
				$download->download();
			}

			if($queue_item_id = $userInput->getValidated('queue_item_id', 0, UserInput::UINT)) {
				$queue_item = new QueueItem($queue_item_id);
				if(!$queue_item->getId()) throw new JBException('The provided queue item id not found');
				$downloader = new Downloader($queue_item->getLogFile());
				$downloader->download();
			}
		} catch(JBException $e) {
			die('Error:' . $e->getMessage());
		}
	}
	
	private static function _createWorkingSpace() {

		$folders = [
			Factory::getLocations()->getDataDir(),
			Factory::getLocations()->getTempDir(),
			Factory::getLocations()->getDatabaseDir(),
			Factory::getLocations()->getDownloadsDir(),
			Factory::getLocations()->getBackupsDir(),
			Factory::getLocations()->getLogsDir(),
		];

		foreach ($folders as $folder) Util::secureFolder($folder);

	}

	public static function filterAdminBodyClass($classes) {
		$screen = Helper::getCurrentScreen();
		if ($screen && strpos($screen, 'jetbackup') !== false) $classes .= ' jetbackup';
		return $classes;
	}

	public static function actionCLI() {
		if (defined('WP_CLI') && WP_CLI) CLI::init();
	}

	public static function actionRegisterWebhookEndpoint() {
		register_rest_route('jetbackup/api', '/scheduler', array(
			'methods' => 'POST',
			'callback' => [Cron::class, 'restAPI'],
			'permission_callback' => '__return_true',
		));
	}

	public static function actionAPIEnqueueScripts() {
		// Enqueue jQuery if it's not already done by your theme or another plugin
		wp_enqueue_script('jquery');

		// Inline JavaScript code
		wp_add_inline_script('jquery', <<<EOD
jQuery(document).ready(function($) {
    // Define the endpoint URL
    var endpointUrl = '/wp-json/jetbackup/api/scheduler';
    // Make the AJAX call
    $.ajax({
        url: endpointUrl,
        type: 'POST',
        data: {},
        async: true,
    });
});
EOD);

	}


}
