<?php

namespace HelpGent\App\Providers;

defined( 'ABSPATH' ) || exit;

use Exception;
use HelpGent\WpMVC\Contracts\Provider;
use HelpGent\App\BackgroundServices\ScheduledBackgroundService;

class BackgroundProcessorServiceProvider implements Provider {
    protected ?ScheduledBackgroundService $background_service = null;

    public function boot() {
        add_action( 'init', [ $this, 'action_init' ] );
    }

    /**
     * Fires after WordPress has finished loading but before any headers are sent.
     */
    public function action_init(): void {
        if ( ! wp_next_scheduled( 'helpgent_background_processor_schedule' ) ) {
            wp_schedule_event( time(), 'twicedaily', 'helpgent_background_processor_schedule' );
        }

        $this->background_service = helpgent_singleton( ScheduledBackgroundService::class );

        add_action( 'helpgent_background_processor_schedule', [ $this, 'schedule' ] );
    }

    public function schedule() {
        if ( ! $this->background_service ) {
            return;
        }

        $this->background_service->add_service_task(
            'remove_users',
            [ 'guest_user_remove' => intval( helpgent_get_setting( 'guest_user_auto_remove' ) ) ] 
        );

        $hours = intval( helpgent_get_setting( 'remove_unverified_response_after_hours', 48 ) );

        if ( 0 < $hours ) {
            $this->background_service->add_service_task(
                'remove_unverified_response',
                [ 'created_at' =>  helpgent_now()->setTimestamp( time() - ( HOUR_IN_SECONDS * $hours ) )->format( helpgent_date_time_format() ) ] 
            );
        }

        $attachment = helpgent_get_setting( 'attachment_auto_remove', '0' );

        if ( '1' === $attachment ) {
            $schedule_days = intval( helpgent_get_setting( 'attachment_remove_after_days', 30 ) );

            $this->background_service->add_service_task(
                'remove_unknown_attachment',
                [ 'created_at' => helpgent_now()->sub_days( 1 )->format( helpgent_date_time_format() ) ] 
            );

            $this->background_service->add_service_task(
                'remove_expired_attachment',
                [ 'expired_date' =>  helpgent_now()->sub_days( $schedule_days )->format( helpgent_date_time_format() ) ] 
            );
        }

        try {
            $this->background_service->run();

            /**
             * @var FontFamilyServiceProvider $font_family
             */
            $font_family = helpgent_singleton( FontFamilyServiceProvider::class );
            $font_family->init_background_service();
            $font_family->download( "Inter" );
        } catch ( Exception $e ) {
        }
    }
}