<?php

namespace WPDesk\FakturyKSEF\Cron;

use WPDesk\FakturyKSEF\Repository\PluginSettings;
use WPDesk\FakturyKSEF\Services\ReconciliationCutOffDateService;
use WPDeskKSEFVendor\WPDesk\PluginBuilder\Plugin\Hookable;
use WP_Query;

class ReconciliationJob implements Hookable {

	private const CRON_HOOK = 'fiksef_reconciliation_cron_job';

	private PluginSettings $settings;

	private ReconciliationCutOffDateService $cut_off_date_service;

	public function __construct( PluginSettings $settings, ReconciliationCutOffDateService $cut_off_date_service ) {
		$this->cut_off_date_service = $cut_off_date_service;
		$this->settings             = $settings;
	}

	public function hooks() {
		add_filter( 'cron_schedules', [ $this, 'add_cron_schedule' ] );
		add_action( 'init', [ $this, 'schedule_cron_event' ] );
		add_action( self::CRON_HOOK, [ $this, 'handle_cron_event' ] );
	}

	public function add_cron_schedule( $schedules ) {
		if ( ! isset( $schedules['every_eight_hours'] ) ) {
			$schedules['every_eight_hours'] = [
				'interval' => 8 * HOUR_IN_SECONDS,
				'display'  => __( 'Every 8 Hours', 'ksef-for-flexible-invoices' ),
			];
		}
		return $schedules;
	}

	public function schedule_cron_event() {
		if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
			wp_schedule_event( time(), 'every_eight_hours', self::CRON_HOOK );
		}
	}

	public function handle_cron_event() {
		if ( ! $this->settings->is_auto_sending_enabled() ) {
			return;
		}

		$cutoff_date = $this->cut_off_date_service->get_cut_off_date();
		if ( ! $cutoff_date ) {
			return;
		}

		$args = [
			'post_type'      => 'inspire_invoice',
			'post_status'    => 'publish',
			'posts_per_page' => 99,
			'fields'         => 'ids',
			'date_query'     => [
				[
					'after'     => gmdate( 'Y-m-d H:i:s', (int) $cutoff_date ),
					'inclusive' => true,
				],
			],
			'meta_query'     => [ //phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
				'relation' => 'AND',
				[
					'key'     => '_ksef_status',
					'value'   => 'success',
					'compare' => '!=',
				],
				[
					'key'     => '_ksef_network_error',
					'value'   => 'yes',
				],
			],
		];

		$query = new WP_Query( $args );

		if ( ! empty( $query->posts ) ) {
			foreach ( $query->posts as $post_id ) {
				do_action( 'fiksef_retry_document_sending', null, null, $post_id );
			}
		}
	}
}
