<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'wp', 'elementsell_billing_schedule_daily_check' );
add_action( 'elementsell_daily_billing_check', 'elementsell_billing_run_daily_check' );
register_deactivation_hook( PF_PLUGIN_FILE, 'elementsell_billing_unschedule_daily_check' );

/**
 * @return int[]
 */
function elementsell_billing_get_daily_check_timestamps() {
    $hook       = 'elementsell_daily_billing_check';
    $timestamps = [];

    foreach ( _get_cron_array() ?: [] as $timestamp => $cronhooks ) {
        if ( isset( $cronhooks[ $hook ] ) ) {
            $timestamps[] = (int) $timestamp;
        }
    }

    sort( $timestamps );

    return $timestamps;
}

/**
 * Zajistí právě jeden naplánovaný běh denní kontroly (odstraní duplicity z cron option).
 *
 * @return void
 */
function elementsell_billing_schedule_daily_check() {
    $hook       = 'elementsell_daily_billing_check';
    $timestamps = elementsell_billing_get_daily_check_timestamps();

    if ( count( $timestamps ) > 1 ) {
        $keep = $timestamps[0];
        wp_clear_scheduled_hook( $hook );
        wp_schedule_event( $keep, 'daily', $hook );
        return;
    }

    if ( empty( $timestamps ) ) {
        wp_schedule_event( time(), 'daily', $hook );
    }
}

/**
 * @return void
 */
function elementsell_billing_unschedule_daily_check() {
    wp_clear_scheduled_hook( 'elementsell_daily_billing_check' );
}

/**
 * @return void
 */
function elementsell_billing_run_daily_check() {
    elementsell_billing_process_monthly_charge();
}

/**
 * @return void
 */
function elementsell_send_activation_request_to_remote_server() {
    if ( function_exists( 'elementsell_telemetry_send_activation' ) ) {
        elementsell_telemetry_send_activation();
    }

    if ( defined( 'PF_VERSION' ) ) {
        if ( function_exists( 'elementsell_telemetry_mark_sent_version' ) ) {
            elementsell_telemetry_mark_sent_version( PF_VERSION );
        } else {
            update_option( 'elementsell_plugin_version', PF_VERSION, false );
        }
    }
}

register_activation_hook( PF_PLUGIN_FILE, 'elementsell_send_activation_request_to_remote_server' );
