<?php
/********************************************************************
 * Copyright (C) 2024 Darko Gjorgjijoski (https://darkog.com/)
 * Copyright (C) 2024 IDEOLOGIX MEDIA Dooel (https://ideologix.com/)
 *
 * This file is property of IDEOLOGIX MEDIA Dooel (https://ideologix.com)
 * This file is part of Vimeify Plugin - https://wordpress.org/plugins/vimeify/
 *
 * Vimeify - Formerly "WP Vimeo Videos" 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.
 *
 * Vimeify - Formerly "WP Vimeo Videos" 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 this plugin. If not, see <https://www.gnu.org/licenses/>.
 *
 * Code developed by Darko Gjorgjijoski <dg@darkog.com>.
 **********************************************************************/

namespace Vimeify\Core\Backend\Tools;

use Vimeify\Core\Abstracts\BaseTool;
use Vimeify\Core\Abstracts\Interfaces\SystemInterface;
use Vimeify\Core\Utilities\FileSystem;

class ThumbnailReset extends BaseTool {

	const BATCH_SIZE = 100;

	/**
	 * Constructor
	 *
	 * @param string $id
	 * @param SystemInterface $system
	 */
	public function __construct( $id, $system ) {
		parent::__construct( $id, $system );

		$this->slug        = 'thumbnail_reset';
		$this->description = __( 'Clears all cached thumbnails so they are re-fetched from Vimeo on next access.', 'vimeify' );
		$this->is_one_time = false;
	}

	/**
	 * Returns the view
	 * @return string
	 */
	public function get_view() {
		return $this->system->views()->get_view( 'admin/partials/tools/thumbnail-reset', [
			'tool' => $this,
		] );
	}

	/**
	 * Returns the tool steps
	 * @return array
	 */
	public function get_steps() {
		$total_videos = $this->get_temporary_data( 'total_videos', 0 );
		$total_pages  = max( 1, (int) ceil( $total_videos / self::BATCH_SIZE ) );

		return [
			1 => [ 'name' => __( 'Clear cached files', 'vimeify' ), 'pages' => 1 ],
			2 => [ 'name' => __( 'Clear cached data', 'vimeify' ), 'pages' => $total_pages ],
		];
	}

	/**
	 * Initializes the process
	 * @return bool
	 */
	public function init_process() {
		$total_videos = (int) wp_count_posts( 'vimeify-video' )->publish;
		$this->set_temporary_data( 'total_videos', $total_videos );

		return true;
	}

	/**
	 * Executes a specific step
	 *
	 * @param int $step
	 * @param int $page
	 *
	 * @return bool
	 */
	public function do_step( $step, $page ) {
		if ( $step === 1 ) {
			return $this->clear_cached_files();
		}

		if ( $step === 2 ) {
			return $this->clear_cached_data( $page );
		}

		return true;
	}

	/**
	 * Step 1: Delete the filesystem thumbnail cache directory
	 * @return bool
	 */
	private function clear_cached_files() {
		$tmp_dir     = $this->system->tmp_dir();
		$thumbs_path = trailingslashit( $tmp_dir->path ) . 'thumbs';

		if ( is_dir( $thumbs_path ) ) {
			$files = glob( $thumbs_path . DIRECTORY_SEPARATOR . '*' );
			if ( is_array( $files ) ) {
				foreach ( $files as $file ) {
					if ( is_file( $file ) ) {
						@unlink( $file );
					}
				}
			}
			@rmdir( $thumbs_path );
		}

		return true;
	}

	/**
	 * Step 2: Delete post meta and transients for a batch of videos
	 *
	 * @param int $page
	 *
	 * @return bool
	 */
	private function clear_cached_data( $page ) {
		$offset = ( $page - 1 ) * self::BATCH_SIZE;

		$videos = get_posts( [
			'post_type'      => 'vimeify-video',
			'posts_per_page' => self::BATCH_SIZE,
			'offset'         => $offset,
			'post_status'    => 'any',
			'fields'         => 'ids',
		] );

		foreach ( $videos as $post_id ) {
			$vimeo_id = get_post_meta( $post_id, 'vimeify_response', true );

			// Delete cached picture data
			delete_post_meta( $post_id, 'vimeify_pictures' );

			// Delete thumbnail transient
			if ( ! empty( $vimeo_id ) ) {
				delete_transient( 'vimeify_' . $vimeo_id . '_thumb' );
			}
		}

		return true;
	}
}
