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

/********************************************************************
 * Copyright (C) 2025 Hassine RIANI (https://upvimeo.com)
 *
 * This file is part of Upvimeo
 *
 * Upvimeo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Upvimeo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Upvimeo. If not, see <https://www.gnu.org/licenses/>.
 **********************************************************************/

/**
 * Class UpVimeo_Cron
 *
 * Responsible for setting up the Cron events
 *
 * @license GPLv2
 * @copyright Hassine RIANI (https://upvimeo.com)
 * @since 1.9.0
 */
class UpVimeo_Cron
{

	/**
	 * Initialize the corn system
	 *
	 * @param  UpVimeo  $root
	 *
	 * @return void
	 */
	public function init($root)
	{
		$root->get_loader()->add_filter('cron_schedules', $this, 'custom_schedules', 9, 1);
		$root->get_loader()->add_action('init', $this, 'schedule_actions', 9);
	}

	/**
	 * Return possible list of cron tasks
	 * @return float[]|int[]
	 */
	private function get_actions()
	{
		return array(
			'cleanup_pull_files' => 'hourly',
			'metadata_sync' => 'UPVIMEO_fifteen_minutes',
			'status_sync' => 'UPVIMEO_twenty_minutes',
		);
	}

	/**
	 * Custom cron schedules
	 * @return void
	 */
	public function custom_schedules($schedules)
	{

		$schedules['UPVIMEO_fifteen_minutes'] = array(
			'interval' => 15 * MINUTE_IN_SECONDS,
			'display' => esc_html__('Every Fifteen Minutes', 'upvimeo-direct-uploads'),
		);

		$schedules['UPVIMEO_twenty_minutes'] = array(
			'interval' => 20 * MINUTE_IN_SECONDS,
			'display' => esc_html__('Every Twenty Minutes', 'upvimeo-direct-uploads'),
		);

		return $schedules;
	}

	/**
	 * Registers the cron events
	 */
	public function schedule_actions()
	{

		foreach ($this->get_actions() as $key => $recurrence) {
			$hook = sprintf('upvimeo_action_%s', $key);
			$timestamp = wp_next_scheduled($hook);
			if ($timestamp == false) {
				wp_schedule_event(time(), $recurrence, $hook);
			}
			if (method_exists($this, 'do_' . $key)) {
				add_action($hook, array($this, 'do_' . $key));
			}
		}
	}

	/**
	 * Clean up pull files
	 * @return void
	 */
	public function do_cleanup_pull_files()
	{

		$logtag = 'TMP FILE CLEAN UP';
		$logger = new UpVimeo_Logger();

		$logger->log('Starting the temporary files clean up process.', $logtag);

		/**
		 * How many minutes needs to pass in order the temporary uploads used for Vimeo Pull uploading method to be removed.
		 * Warning: please make sure you leave at least 30 minutes for Vimeo to process the file. Setting this value to low may cause missing uploads.
		 */
		$removal_delay_minutes = apply_filters('UPVIMEO_upload_pull_removal_delay', 180);
		if ($removal_delay_minutes < 20) { // Protection for just in case.
			$removal_delay_minutes = 100;
		}

		$time_now = time();
		$settings = new UpVimeo_Settings_Helper();
		$tmp_files = $settings->get_temporary_files();
		if (count($tmp_files) > 0) {
			foreach ($tmp_files as $path => $time_age) {
				$diff_minutes = round(abs($time_now - $time_age) / 60, 2);
				$file_exists = file_exists($path);
				if ($diff_minutes >= $removal_delay_minutes && $file_exists) {
					if (wp_delete_file($path)) {
						$settings->remove_from_temporary_files($path);
						$logger->log(sprintf('Deleted temporary video file %s after %s minutes', $path, $diff_minutes), $logtag);
					} else {
						$logger->log(sprintf('Unable to remove temporary video file %s.', $path), $logtag);
					}
				} elseif (!$file_exists) {
					$settings->remove_from_temporary_files($path);
					$logger->log(sprintf('Temporary video file %s not found in the file system', $path), $logtag);
				}
			}
		} else {
			$logger->log('No temporary files found for clean up.', $logtag);
		}
	}

	/**
	 * Sync all the videos in the library with Vimeo.com
	 * @return void
	 */
	public function do_metadata_sync()
	{
		$logtag = 'upvimeo-METADATA-SYNC';
		$logger = new UpVimeo_Logger();
		$logger->log('Starting metadata sync via cron.', $logtag);
		$sync = new UpVimeo_Sync();
		$sync->sync_metadata();
		$logger->log('Finished metadata sync via cron.', $logtag);
	}

	/**
	 * Sync all the videos in the library with Vimeo.com
	 * @return void
	 */
	public function do_status_sync()
	{
		$logtag = 'upvimeo-STATUS-SYNC';
		$logger = new UpVimeo_Logger();
		$logger->log('Starting status sync via cron.', $logtag);
		$sync = new UpVimeo_Sync();
		$sync->sync_status();
		$logger->log('Finished status sync via cron.', $logtag);
	}
}
