<?php

if ( ! defined( 'ABSPATH' ) ) {

    exit;

}



add_action( 'elementsell_daily_billing_check', 'elementsell_run_daily_payment_reminders', 20 );



/**

 * Kontrola upomínek běží často, protože první z nich odchází v řádu minut

 * po objednání. Denní běh by ji poslal až druhý den.

 */

add_filter( 'cron_schedules', 'elementsell_add_reminder_schedule' );

add_action( 'wp', 'elementsell_schedule_reminder_check' );

add_action( 'elementsell_reminder_check', 'elementsell_run_payment_reminders_check' );



if ( defined( 'PF_PLUGIN_FILE' ) ) {

    register_deactivation_hook( PF_PLUGIN_FILE, 'elementsell_unschedule_reminder_check' );

}



/**

 * @param array<string, array{interval: int, display: string}> $schedules

 * @return array<string, array{interval: int, display: string}>

 */

function elementsell_add_reminder_schedule( $schedules ) {

    if ( ! isset( $schedules['elementsell_15min'] ) ) {

        $schedules['elementsell_15min'] = [

            'interval' => 15 * MINUTE_IN_SECONDS,

            'display'  => __( 'Každých 15 minut (ElementSell)', 'platebni-formular' ),

        ];

    }



    return $schedules;

}



/**

 * @return void

 */

function elementsell_schedule_reminder_check() {

    if ( ! wp_next_scheduled( 'elementsell_reminder_check' ) ) {

        wp_schedule_event( time() + MINUTE_IN_SECONDS, 'elementsell_15min', 'elementsell_reminder_check' );

    }

}



/**

 * @return void

 */

function elementsell_unschedule_reminder_check() {

    wp_clear_scheduled_hook( 'elementsell_reminder_check' );

}



/**

 * Průběžná kontrola — pošle jen to, co je opravdu splatné.

 *

 * @return array{checked: int, sent: int, skipped: int, errors: string[], sent_ids: int[]}

 */

function elementsell_run_payment_reminders_check() {

    $result = elementsell_process_payment_reminders();



    if ( (int) $result['sent'] > 0 && class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {

        ElementSell_Cron_Log::add(

            sprintf( 'Upomínky (průběžně): %d odesláno', (int) $result['sent'] )

        );

    }



    return $result;

}



/**

 * @return array{checked: int, sent: int, skipped: int, errors: string[], sent_ids: int[]}

 */

function elementsell_run_daily_payment_reminders() {

    $result = elementsell_process_payment_reminders();



    if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {

        ElementSell_Cron_Log::add(

            sprintf(

                'Upomínky: %d odesláno, %d zkontrolováno',

                (int) $result['sent'],

                (int) $result['checked']

            )

        );



        if ( ! empty( $result['errors'] ) ) {

            ElementSell_Cron_Log::add( 'Upomínky: chyba při odesílání' );

        }

    }



    return $result;

}

