<?php

namespace Vendtics\App\Providers;

defined( "ABSPATH" ) || exit;

use Vendtics\App\Jobs\Campaign;
use Vendtics\WpMVC\Contracts\Provider;
use Vendtics\App\Repositories\CampaignRepository;
use Vendtics\App\Repositories\SettingsRepository;

class JobsServiceProvider implements Provider {
    public Campaign $campaign;

    public function boot() {
        $this->campaign = vendtics_singleton( Campaign::class );
        add_filter( 'cron_schedules', [ $this, 'filter_cron_schedules' ] );
        add_action( 'init', [$this, 'vendtics_schedule_every_hour_cron'] );
        add_action( 'vendtics_every_min_cron_job_event', [$this, 'custom_minute_cron_job_function'] );
    }

    public function filter_cron_schedules( array $schedules ) : array {
        $schedules['vendtics_every_minute'] = [
            'interval' => 60, // 60 seconds (1 minute)
            'display'  => __( 'Every Minute', 'vendtics' )
        ];

        return $schedules;
    }

    public function vendtics_schedule_every_hour_cron() {
        if ( ! wp_next_scheduled( 'vendtics_every_min_cron_job_event' ) ) {
            wp_schedule_event( time(), 'vendtics_every_minute', 'vendtics_every_min_cron_job_event' );
        }
    }

    function custom_minute_cron_job_function() {
        if ( $this->campaign->is_active() || $this->campaign->is_processing() || $this->campaign->is_queued() ) {
            return;
        }

        $repository = vendtics_singleton( CampaignRepository::class );
        $campaign   = $repository->scheduled_first();

        if ( ! $campaign ) {
            return;
        }

        $body = vendtics_email_add_utm_params( $campaign->body, $campaign->utm_parameters );
        $body = vendtics_email_add_pre_header( $body, $campaign->pre_header );

        $campaign->body = $body;

        unset( $campaign->utm_parameters, $campaign->pre_header );

        $repository       = vendtics_singleton( SettingsRepository::class );
        $general_settings = $repository->get_settings()['general'];

        $this->campaign->push_to_queue(
            [
                'campaign'                      => $campaign,
                'per_email_seconds'             => $this->per_email_seconds(),
                'last_email_sent_time'          => 0,
                'unsubscribe_confirmation_page' => get_permalink( intval( $general_settings['unsubscribe_confirm_page'] ) )
            ]
        )->save()->dispatch();
    }

    protected function per_email_seconds() {
        $repository     = vendtics_singleton( SettingsRepository::class );
        $email_settings = $repository->get_settings()['email'];

        $available_frequency = [
            ['value' => '1_min'],
            ['value' => '2_min'],
            ['value' => '5_min'],
            ['value' => '10_min'],
            ['value' => '15_min'],
            ['value' => '30_min'],
            ['value' => '60_min'],
        ];

        // Find the selected frequency in available_frequency
        $selected_frequency = null;

        foreach ( $available_frequency as $freq ) {
            if ( $freq['value'] === $email_settings['frequency'] ) {
                $selected_frequency = $freq['value'];
                break;
            }
        }

        if ( $selected_frequency ) {
            // Extract the numeric value and calculate seconds
            list( $freq_value, $freq_unit ) = explode( '_', $selected_frequency );
            $seconds_per_frequency          = (int) $freq_value * 60; // Convert minutes to seconds
    
            // Calculate seconds per email
            $seconds_per_email = $seconds_per_frequency / intval( $email_settings['limit'] );
    
            return $seconds_per_email;
        }

        return 12; // Default value
    }    
}