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

/**
 * @param int    $post_id
 * @param string $widget_id
 * @return array|null
 */
function elementsell_find_elementor_widget_settings( $post_id, $widget_id ) {
    $post_id   = (int) $post_id;
    $widget_id = trim( (string) $widget_id );

    if ( $post_id <= 0 || $widget_id === '' ) {
        return null;
    }

    $raw = get_post_meta( $post_id, '_elementor_data', true );

    if ( ! is_string( $raw ) || $raw === '' ) {
        return null;
    }

    $elements = json_decode( $raw, true );

    if ( ! is_array( $elements ) ) {
        return null;
    }

    return elementsell_walk_elementor_for_widget( $elements, $widget_id );
}

/**
 * @param array  $elements
 * @param string $widget_id
 * @return array|null
 */
function elementsell_walk_elementor_for_widget( $elements, $widget_id ) {
    foreach ( $elements as $element ) {
        if (
            ! empty( $element['id'] )
            && $element['id'] === $widget_id
            && ! empty( $element['widgetType'] )
            && $element['widgetType'] === 'elementsell_payment_form'
        ) {
            return isset( $element['settings'] ) && is_array( $element['settings'] )
                ? $element['settings']
                : [];
        }

        if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
            $found = elementsell_walk_elementor_for_widget( $element['elements'], $widget_id );

            if ( $found !== null ) {
                return $found;
            }
        }
    }

    return null;
}

/**
 * Doplní výchozí hodnoty z Elementor controls (stejně jako get_settings_for_display).
 *
 * @param array|null $settings
 * @return array
 */
function elementsell_merge_payment_widget_defaults( $settings ) {
    if ( ! is_array( $settings ) ) {
        $settings = [];
    }

    if ( ! class_exists( '\Elementor\Plugin' ) ) {
        if ( ! isset( $settings['amount'] ) || $settings['amount'] === '' || floatval( $settings['amount'] ) <= 0 ) {
            $settings['amount'] = 100;
        }

        return $settings;
    }

    $widget = \Elementor\Plugin::$instance->widgets_manager->get_widget_types( 'elementsell_payment_form' );

    if ( ! $widget ) {
        return $settings;
    }

    foreach ( $widget->get_controls() as $control_name => $control ) {
        if ( ! array_key_exists( 'default', $control ) ) {
            continue;
        }

        if ( ! array_key_exists( $control_name, $settings ) || $settings[ $control_name ] === '' || $settings[ $control_name ] === null ) {
            $settings[ $control_name ] = $control['default'];
        }
    }

    if ( ! isset( $settings['amount'] ) || $settings['amount'] === '' || floatval( $settings['amount'] ) <= 0 ) {
        $amount_control = $widget->get_controls( 'amount' );
        $settings['amount'] = isset( $amount_control['default'] ) ? $amount_control['default'] : 100;
    }

    if ( function_exists( 'elementsell_merge_payment_widget_global_defaults' ) ) {
        $settings = elementsell_merge_payment_widget_global_defaults( $settings );
    }

    return $settings;
}

/**
 * @param string $message
 * @return void
 */
function elementsell_payment_fail( $message ) {
    $back_url = '';

    if ( ! empty( $_POST['source_page_url'] ) ) {
        $back_url = esc_url( wp_unslash( (string) $_POST['source_page_url'] ) );
    }

    if ( $back_url === '' ) {
        $back_url = wp_get_referer() ? esc_url( wp_get_referer() ) : home_url( '/' );
    }

    $widget_id = isset( $_POST['elementsell_widget_id'] )
        ? sanitize_text_field( wp_unslash( (string) $_POST['elementsell_widget_id'] ) )
        : '';
    $anchor    = $widget_id !== '' ? 'elementsell-payment-' . $widget_id : 'elementsell-form';

    if ( function_exists( 'elementsell_append_url_fragment' ) ) {
        $back_url = elementsell_append_url_fragment( $back_url, $anchor );
    }

    wp_die(
        '<div style="max-width:480px;margin:48px auto;padding:28px 24px;border:1px solid #e5e7eb;border-radius:12px;background:#fff;font-family:system-ui,-apple-system,BlinkMacSystemFont,\'Segoe UI\',sans-serif;text-align:center;">'
        . '<p style="margin:0 0 16px;font-size:17px;line-height:1.5;color:#111827;">' . esc_html( $message ) . '</p>'
        . '<p style="margin:0;"><a href="' . $back_url . '" style="display:inline-block;padding:12px 20px;border-radius:10px;background:#111827;color:#fff;text-decoration:none;font-size:15px;font-weight:600;">Zpět na formulář</a></p>'
        . '</div>',
        esc_html( $message ),
        [ 'response' => 400, 'back_link' => false ]
    );
}

/**
 * @param array  $settings
 * @param string $discount_code
 * @return float
 */
function elementsell_calculate_widget_amount( $settings, $discount_code = '' ) {
    if ( ! is_array( $settings ) ) {
        return 0.0;
    }

    $amount = isset( $settings['amount'] ) ? floatval( $settings['amount'] ) : 0.0;

    if ( $amount <= 0 ) {
        return 0.0;
    }

    $discount_code = trim( (string) $discount_code );

    if (
        $discount_code === ''
        || empty( $settings['discount_codes'] )
        || ! is_array( $settings['discount_codes'] )
    ) {
        return (float) round( $amount );
    }

    foreach ( $settings['discount_codes'] as $code ) {
        if ( ! is_array( $code ) || empty( $code['code'] ) ) {
            continue;
        }

        if ( strcasecmp( trim( (string) $code['code'] ), $discount_code ) !== 0 ) {
            continue;
        }

        $discount_percent = isset( $code['discount'] ) ? floatval( $code['discount'] ) / 100 : 0.0;

        return (float) round( $amount * ( 1 - $discount_percent ) );
    }

    return (float) round( $amount );
}

/**
 * @return array
 */
function elementsell_validate_payment_submission() {
    if (
        ! isset( $_POST['amount'] )
        || ! is_numeric( $_POST['amount'] )
        || floatval( $_POST['amount'] ) <= 0
    ) {
        elementsell_payment_fail( 'Neplatná částka.' );
    }

    $post_id = isset( $_POST['elementsell_post_id'] ) ? intval( $_POST['elementsell_post_id'] ) : 0;
    $widget_id = isset( $_POST['elementsell_widget_id'] )
        ? sanitize_text_field( wp_unslash( $_POST['elementsell_widget_id'] ) )
        : '';

    if ( $post_id <= 0 || $widget_id === '' ) {
        elementsell_payment_fail( 'Neplatný formulář.' );
    }

    $settings = elementsell_find_elementor_widget_settings( $post_id, $widget_id );

    if ( ! is_array( $settings ) ) {
        elementsell_payment_fail( 'Platební formulář nebyl nalezen.' );
    }

    $settings = elementsell_merge_payment_widget_defaults( $settings );

    $discount_code = isset( $_POST['discount_code'] )
        ? sanitize_text_field( wp_unslash( $_POST['discount_code'] ) )
        : '';
    $upsell_accepted = ! empty( $_POST['upsell_accepted'] ) && (string) $_POST['upsell_accepted'] === '1';
    $offer_token     = isset( $_POST['es_offer_token'] )
        ? sanitize_text_field( wp_unslash( (string) $_POST['es_offer_token'] ) )
        : '';
    $customer_email  = isset( $_POST['email'] )
        ? sanitize_email( wp_unslash( (string) $_POST['email'] ) )
        : '';

    if ( $upsell_accepted && ! elementsell_upsell_is_enabled( $settings ) ) {
        elementsell_payment_fail( 'Neplatná nabídka upsell.' );
    }

    if ( elementsell_upsell_is_enabled( $settings ) && empty( $_POST['upsell_decided'] ) ) {
        elementsell_payment_fail( 'Nejdřív potvrďte nebo odmítněte doplňkovou nabídku.' );
    }

    $offer_amount = null;
    $offer        = null;

    if ( $offer_token !== '' && function_exists( 'elementsell_automation_get_offer_by_token' ) ) {
        $offer = elementsell_automation_get_offer_by_token( $offer_token );

        if ( ! function_exists( 'elementsell_automation_validate_offer' ) || ! elementsell_automation_validate_offer( $offer, $customer_email ) ) {
            elementsell_payment_fail( 'Osobní nabídka není platná nebo patří jinému e-mailu.' );
        }

        $offer_amount = (float) $offer->price;
    }

    if ( $offer_amount !== null ) {
        $expected_amount = $offer_amount;

        if ( $upsell_accepted && elementsell_upsell_is_enabled( $settings ) ) {
            $expected_amount += elementsell_get_upsell_price( $settings );
        }
    } else {
        $expected_amount = elementsell_calculate_payment_amount( $settings, $discount_code, $upsell_accepted );
    }
    $posted_amount   = floatval( $_POST['amount'] );

    if ( $expected_amount <= 0 || abs( $posted_amount - $expected_amount ) > 0.01 ) {
        elementsell_payment_fail( 'Neplatná částka.' );
    }

    $_POST['amount'] = (string) $expected_amount;

    // Název produktu nikdy z klienta — jen z widgetu / osobní nabídky.
    $product_name = trim( (string) ( $settings['product_name'] ?? '' ) );

    if ( $offer_token !== '' && ! empty( $offer ) && is_object( $offer ) ) {
        $offer_product = trim( (string) ( $offer->product_name ?? '' ) );

        if ( $offer_product !== '' ) {
            $product_name = $offer_product;
        }
    }

    if ( $product_name === '' ) {
        elementsell_payment_fail( 'Chybí název produktu ve formuláři.' );
    }

    $_POST['product_name'] = sanitize_text_field( $product_name );

    // Sync trigger (no-op): 2026-07-22.

    if ( function_exists( 'elementsell_validate_payment_spam_submission' ) ) {
        elementsell_validate_payment_spam_submission();
    }

    return $settings;
}
