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

/**
 * @return void
 */
function elementsell_billing_process_monthly_charge() {
    $parent_payment_uid = elementsell_billing_get_parent_payment_uid();

    if ( $parent_payment_uid === '' ) {
        if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {
            ElementSell_Cron_Log::add( 'Poplatek přeskočen (není uložená karta)' );
        }
        return;
    }

    $previous_month = strtotime( 'first day of previous month' );
    $year           = (int) gmdate( 'Y', $previous_month );
    $month          = (int) gmdate( 'n', $previous_month );

    $fee_paid_key = elementsell_billing_get_fee_paid_option_key( $year, $month );

    if ( get_option( $fee_paid_key, 'ne' ) === 'ano' ) {
        if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {
            ElementSell_Cron_Log::add( 'Poplatek za měsíc už uhrazen' );
        }
        return;
    }

    $revenue = elementsell_get_production_revenue_for_month( $year, $month );
    $fee_czk = elementsell_calculate_billing_fee( $revenue );

    update_option( elementsell_billing_get_revenue_option_key( $year, $month ), $revenue );

    if ( $fee_czk <= 0 ) {
        update_option( $fee_paid_key, 'ano' );
        if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {
            ElementSell_Cron_Log::add( 'Poplatek 0 Kč (pod limitem tržeb)' );
        }
        return;
    }

    $client = elementsell_billing_get_thepay_client();

    if ( ! $client ) {
        if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {
            ElementSell_Cron_Log::add( 'Poplatek: nelze připojit platební bránu' );
        }
        return;
    }

    $amount_halere      = (int) round( $fee_czk * 100 );
    $child_payment_uid  = uniqid( 'es_fee_', true );
    $realize_params     = new \ThePay\ApiClient\Model\RealizePaymentBySavedAuthorizationParams(
        $child_payment_uid,
        $amount_halere,
        'CZK'
    );

    try {
        $response = $client->realizePaymentBySavedAuthorization( $parent_payment_uid, $realize_params );

        if ( ! $response->wasSuccessful() ) {
            update_option( 'payment_failed', 'ano' );
            if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {
                ElementSell_Cron_Log::add( 'Poplatek: stržení selhalo' );
            }
            elementsell_telemetry_report_fee_failed(
                [
                    'billing_year'  => $year,
                    'billing_month' => $month,
                    'revenue'       => $revenue,
                    'fee_amount'    => $fee_czk,
                    'payment_uid'   => $child_payment_uid,
                ]
            );
            return;
        }

        update_option( 'child_payment_uid', sanitize_text_field( $child_payment_uid ) );
        update_option( $fee_paid_key, 'ano' );
        delete_option( 'payment_failed' );

        elementsell_telemetry_report_fee_charge(
            [
                'billing_year'  => $year,
                'billing_month' => $month,
                'revenue'       => $revenue,
                'fee_amount'    => $fee_czk,
                'payment_uid'   => $child_payment_uid,
            ]
        );

        elementsell_billing_send_invoice_request(
            [
                'payment_uid'   => $child_payment_uid,
                'amount'        => $fee_czk,
                'currency'      => 'CZK',
                'billing_year'  => $year,
                'billing_month' => $month,
            ]
        );

        if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {
            ElementSell_Cron_Log::add( 'Poplatek stržen ' . (int) round( $fee_czk ) . ' Kč' );
        }
    } catch ( Exception $e ) {
        update_option( 'payment_failed', 'ano' );
        if ( class_exists( 'ElementSell_Cron_Log' ) && ElementSell_Cron_Log::is_active() ) {
            ElementSell_Cron_Log::add( 'Poplatek: stržení selhalo' );
        }
        elementsell_telemetry_report_fee_failed(
            [
                'billing_year'  => $year,
                'billing_month' => $month,
                'revenue'       => $revenue,
                'fee_amount'    => $fee_czk,
                'error'         => $e->getMessage(),
            ]
        );
        error_log( 'ElementSell billing charge failed: ' . $e->getMessage() );
    }
}
