<?php

namespace IGD_PRO;

use IGD\App;

class Hooks {

	protected static $instance = null;

	public function __construct() {
		//handle pro redirection
		add_action( 'admin_init', [ $this, 'handle_pro_activation_redirect' ] );

		// localize pro data
		add_filter( 'igd_localize_data', [ $this, 'add_pro_localize_data' ], 10, 2 );

		// Add new cron schedules
		add_filter( 'cron_schedules', [ $this, 'cron_schedules' ] );
		add_action( 'init', [ $this, 'init_cron_job' ] );

		// Sync cloud files
		add_action( 'igd_sync_interval', 'igd_delete_cache' );

		// Restore sharing permissions
		add_action( 'igd_restore_sharing_interval', [ $this, 'restore_sharing_interval' ] );

		// Insert statistics
		add_action( 'igd_import_data', [ $this, 'import_statistics' ], 10, 2 );

	}

	public function import_statistics( $key, $data ) {

		if ( 'events' == $key ) {

			if ( ! class_exists( 'IGD\Statistics' ) ) {
				require_once IGD_PRO_INCLUDES . '/Statistics.php';
			}

			$statistics = Statistics::instance();

			foreach ( $data as $event ) {
				$statistics->insert_log( $event );
			}

		}
	}


	public function restore_sharing_interval() {
		global $wpdb;

		// Get interval setting, fallback to 1 hour if not set
		$interval = igd_get_settings( 'restoreManageSharingInterval', 1 );

		if ( 'custom' === $interval ) {
			$interval = intval( igd_get_settings( 'customRestoreManageSharingInterval', 1 ) );
		}

		$table = $wpdb->prefix . 'integrate_google_drive_logs';

		// Retrieve files shared within the interval
		$results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT file_id, account_id FROM {$table} WHERE type = 'shared' AND created_at BETWEEN DATE_SUB(NOW(), INTERVAL %d HOUR) AND NOW()",
				$interval
			),
			ARRAY_A
		);

		if ( empty( $results ) ) {
			return; // No recent shared files found
		}

		// Group files by account ID
		$accounts_files = [];

		foreach ( $results as $record ) {
			$accounts_files[ $record['account_id'] ][] = $record['file_id'];
		}

		// Sort accounts by account ID for predictable processing order
		ksort( $accounts_files );

		// Process each account's files
		$this->process_shared_files_restoration( $accounts_files );
	}

	/**
	 * Process shared files restoration for multiple accounts.
	 *
	 * @param array $accounts_files Array of files grouped by account ID.
	 */
	private function process_shared_files_restoration( $accounts_files ) {
		$api_params = [
			'supportsAllDrives' => true,
		];

		foreach ( $accounts_files as $account_id => $files ) {
			$this->restore_account_permissions( $account_id, $files, $api_params );
		}
	}

	/**
	 * Restore permissions for files in a specific account.
	 *
	 * @param string $account_id The account ID.
	 * @param array $files Array of file IDs.
	 * @param array $api_params API parameters.
	 */
	private function restore_account_permissions( $account_id, $files, $api_params ) {
		try {
			$app_instance = App::instance( $account_id );
			$client       = $app_instance->client;
			$drive        = $app_instance->getService();

			$client->setUseBatch( true );
			$batch = new \IGDGoogle_Http_Batch( $client );

			// Queue permission removal for each file
			foreach ( $files as $file_id ) {
				$batch->add( $drive->permissions->delete( $file_id, 'anyoneWithLink', $api_params ), $file_id );
			}

			$batch->execute();
			$client->setUseBatch( false );

		} catch ( \Exception $ex ) {
			error_log(
				sprintf(
					'IGD Error: Failed to restore sharing permissions for account %s: %s',
					esc_attr( $account_id ),
					esc_attr( $ex->getMessage() )
				)
			);
		}
	}

	public function cron_schedules( $schedules ) {
		// Add synchronization schedule
		$schedules = $this->add_sync_schedule( $schedules );

		// Add restore sharing schedule
		$schedules = $this->add_restore_sharing_schedule( $schedules );

		return $schedules;
	}

	private function add_sync_schedule( $schedules ) {
		$auto_sync = igd_get_settings( 'autoSync' );

		if ( ! $auto_sync ) {
			return $schedules;
		}

		$interval = igd_get_settings( 'syncInterval', '3600' );

		if ( 'custom' === $interval ) {
			$custom_interval = igd_get_settings( 'customSyncInterval', 3600 );
			$interval        = intval( $custom_interval );

			// Skip if interval is less than 60 seconds
			if ( $interval < 60 ) {
				return $schedules;
			}
		}

		$schedules['igd_sync_interval'] = [
			'interval' => $interval,
			'display'  => __( 'Integrate Google Drive Synchronize Interval', 'integrate-google-drive-premium' ),
		];

		return $schedules;
	}

	private function add_restore_sharing_schedule( $schedules ) {
		$restore_permissions = igd_get_settings( 'restoreManageSharing' );

		if ( ! $restore_permissions ) {
			return $schedules;
		}

		$interval = igd_get_settings( 'restoreManageSharingInterval', 1 );

		if ( 'custom' === $interval ) {
			$custom_interval = igd_get_settings( 'customRestoreManageSharingInterval', 1 );
			$interval        = intval( $custom_interval );
		}

		// Convert hours to seconds
		$interval = $interval * HOUR_IN_SECONDS;

		$schedules['igd_restore_sharing_interval'] = [
			'interval' => $interval,
			'display'  => __( 'Integrate Google Drive Restore Sharing Permissions Interval', 'integrate-google-drive-premium' ),
		];

		return $schedules;
	}

	public function init_cron_job() {
		// Initialize synchronization hook
		$this->setup_sync_cron();

		// Initialize restore sharing hook
		$this->setup_restore_sharing_cron();
	}

	/**
	 * Set up the synchronization cron job.
	 */
	private function setup_sync_cron() {
		$auto_sync = igd_get_settings( 'autoSync' );
		$sync_hook = 'igd_sync_interval';

		if ( ! $auto_sync ) {
			wp_clear_scheduled_hook( $sync_hook );

			return;
		}

		$interval = igd_get_settings( 'syncInterval', '3600' );

		if ( 'custom' === $interval ) {
			$interval = intval( igd_get_settings( 'customSyncInterval', 3600 ) );
		}

		// Validate interval is at least 60 seconds
		if ( $interval < 60 ) {
			wp_clear_scheduled_hook( $sync_hook );

			return;
		}

		$scheduled_interval = igd_pro_get_scheduled_interval( $sync_hook );

		// If settings changed, clear previous hook
		if ( $scheduled_interval !== $interval ) {
			wp_clear_scheduled_hook( $sync_hook );
		}

		// Schedule if not already scheduled
		if ( ! wp_next_scheduled( $sync_hook ) ) {
			wp_schedule_event( time(), 'igd_sync_interval', $sync_hook );
		}
	}

	/**
	 * Set up the restore sharing permissions cron job.
	 */
	private function setup_restore_sharing_cron() {
		$restore_permissions = igd_get_settings( 'restoreManageSharing' );
		$restore_hook        = 'igd_restore_sharing_interval';

		if ( ! $restore_permissions ) {
			wp_clear_scheduled_hook( $restore_hook );

			return;
		}

		$interval = igd_get_settings( 'restoreManageSharingInterval', 1 );

		if ( 'custom' === $interval ) {
			$interval = intval( igd_get_settings( 'customRestoreManageSharingInterval', 1 ) );
		}

		// Convert hours to seconds
		$interval = $interval * HOUR_IN_SECONDS;

		$scheduled_interval = igd_pro_get_scheduled_interval( $restore_hook );

		// If settings changed, clear previous hook
		if ( $scheduled_interval !== $interval ) {
			wp_clear_scheduled_hook( $restore_hook );
		}

		// Schedule if not already scheduled
		if ( ! wp_next_scheduled( $restore_hook ) ) {
			wp_schedule_event( time(), 'igd_restore_sharing_interval', $restore_hook );
		}


	}

	public function handle_pro_activation_redirect() {
		if ( get_option( 'igd_pro_do_activation_redirect', false ) ) {
			delete_option( 'igd_pro_do_activation_redirect' );
			wp_safe_redirect( admin_url( 'admin.php?page=integrate-google-drive' ) );
			exit;
		}
	}

	public function add_pro_localize_data( $data, $hook ) {
		$data['isPro']        = true;
		$data['proPluginUrl'] = IGD_PRO_URL;

		return $data;
	}

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self;
		}

		return self::$instance;
	}

}

Hooks::instance();