<?php
/**
 * Cron Class File
 *
 * This class defines tasks that must be run when.
 */

namespace CarDealerPress\Includes\Cron;

use CarDealerPress\Includes\Database\Company_Handler;
use CarDealerPress\includes\functions\Logger;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Cron {
	use Logger;


	public function remove_cron_schedule() {
		$blog_id   = get_current_blog_id();
		$timestamp = wp_next_scheduled( 'cdp_cron_inventory_update' );
		wp_unschedule_event( $timestamp, 'cdp_cron_inventory_update' );
		$this->append_log( array( 'message' => 'CDP Message: WP Cron cdp_cron_inventory_update removed, on site:' . $blog_id ) );
	}

	public function init_refresh_log_file() {
		add_action( 'cdp_cron_log_file_refresh', array( $this, 'refresh_log_file' ) );
		$this->add_wp_cron_log_job();
	}

	function add_wp_cron_log_job() {
		if ( ! wp_next_scheduled( 'cdp_cron_log_file_refresh' ) ) {
			$this->append_log( array( 'message' => 'CDP Cron Job Created - Log file' ) );
			wp_schedule_event( time(), 'daily', 'cdp_cron_log_file_refresh' ); // or run twicedaily.
		}
	}
	public function refresh_log_file() {
		$log_file_creation = filectime( CDP_LOGS );
		$now               = time();
		// Start with keeping 24 hours of logs.
		$time_for_refresh = 60 * 60 * 24;
		#if ( $now - $log_file_creation >= $time_for_refresh ) {
			wp_delete_file( CDP_LOGS );
			global $wp_filesystem;
			include_once ABSPATH . 'wp-admin/includes/file.php';
			WP_Filesystem();
			$date      = wp_date( 'Y-m-d H:i:s' );
			$message   = "[$date]: Log file created<br>";
			$wp_filesystem->put_contents(CDP_LOGS, $message );
		#}
	}

	public function init_cron_company_handler() {
		add_action( 'cdp_cron_company_handler_refresh', array( $this, 'company_handler_refresh' ) );
		$this->add_wp_cron_company_handler();
	}

	function add_wp_cron_company_handler() {
		if ( ! wp_next_scheduled( 'cdp_cron_company_handler_refresh' ) ) {
			$this->append_log( array( 'message' => 'CDP Message: Cron Company Handler Created' ) );
			wp_schedule_event( time(), 'daily', 'cdp_cron_company_handler_refresh' );
		}
	}

	public function company_handler_refresh() {
		$this->append_log( array( 'message' => 'CDP Message: Cron Company Handler Refresh Check' ) );
		(new Company_Handler())->init_company_handler();
	}

	public function company_handler_backup_transient_refresh() {
		// As a backup, if cron is not working.
		$blog_id = get_current_blog_id();
		if ( ! get_transient( 'cdp_company_check_update_handler_processing_' . 	$blog_id ) ) {
			$this->append_log( array( 'message' => 'CDP Message: Checking for updates to Company' ) );
			set_transient( 'cdp_company_check_update_handler_processing_' . $blog_id, 'Running', ( 60 * 60 * 24 ) );
			(new Company_Handler())->init_company_handler();
		}
	}
}
