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

/**
 * @param array $settings
 * @return string demo|production
 */
function elementsell_get_thepay_environment_from_settings( $settings ) {
    if ( ! is_array( $settings ) ) {
        return 'demo';
    }

    return ( isset( $settings['environment'] ) && $settings['environment'] === 'production' ) ? 'production' : 'demo';
}

/**
 * @param array  $settings
 * @param string $environment
 * @return array{environment: string, project_id: string, merchant_id: string, api_password: string}
 */
function elementsell_get_thepay_credentials_for_environment( $settings, $environment ) {
    if ( ! is_array( $settings ) ) {
        $settings = [];
    }

    $environment = $environment === 'production' ? 'production' : 'demo';
    $prefix        = $environment . '_';

    $project_id   = trim( (string) ( $settings[ $prefix . 'project_id' ] ?? '' ) );
    $merchant_id  = trim( (string) ( $settings[ $prefix . 'merchant_id' ] ?? '' ) );
    $api_password = trim( (string) ( $settings[ $prefix . 'api_password' ] ?? '' ) );

    if ( $merchant_id === '' && ! empty( $settings['merchant_id'] ) ) {
        $legacy_env = elementsell_get_thepay_environment_from_settings( $settings );

        if ( $legacy_env === $environment ) {
            $merchant_id  = trim( (string) $settings['merchant_id'] );
            $project_id   = trim( (string) ( $settings['project_id'] ?? '' ) );
            $api_password = trim( (string) ( $settings['api_password'] ?? '' ) );
        }
    }

    return [
        'environment'  => $environment,
        'project_id'   => $project_id,
        'merchant_id'  => $merchant_id,
        'api_password' => $api_password,
    ];
}

/**
 * @param array $settings
 * @return array{environment: string, project_id: string, merchant_id: string, api_password: string}
 */
function elementsell_resolve_thepay_widget_credentials( $settings ) {
    $environment = elementsell_get_thepay_environment_from_settings( $settings );

    return elementsell_get_thepay_credentials_for_environment( $settings, $environment );
}

/**
 * Uloží ThePay credentials z widgetu do per-environment WP options.
 * Aktivní režim (demo/ostrý) se NEukládá globálně — zůstává jen ve widgetu.
 *
 * @param array $settings
 * @return void
 */
function elementsell_sync_thepay_widget_credentials_to_options( $settings ) {
    if ( ! is_array( $settings ) ) {
        return;
    }

    foreach ( [ 'demo', 'production' ] as $env ) {
        $credentials = elementsell_get_thepay_credentials_for_environment( $settings, $env );
        $option_key  = 'elementsell_thepay_' . $env . '_';

        if ( $credentials['project_id'] !== '' ) {
            update_option( $option_key . 'project_id', $credentials['project_id'] );
        }

        if ( $credentials['merchant_id'] !== '' ) {
            update_option( $option_key . 'merchant_id', $credentials['merchant_id'] );
        }

        if ( $credentials['api_password'] !== '' ) {
            update_option( $option_key . 'api_password', $credentials['api_password'] );
        }
    }
}

/**
 * @param string $environment
 * @return array{environment: string, project_id: int, merchant_id: string, api_password: string}
 */
function elementsell_resolve_thepay_credentials_from_options( $environment = '' ) {
    // Bez explicitního prostředí neber site-wide „poslední aktivní režim“ —
    // ten dřív přepínal demo/ostrý napříč widgety.
    $environment = $environment === 'production' ? 'production' : 'demo';
    $option_key  = 'elementsell_thepay_' . $environment . '_';

    $project_id   = get_option( $option_key . 'project_id', false );
    $merchant_id  = get_option( $option_key . 'merchant_id', false );
    $api_password = get_option( $option_key . 'api_password', false );

    $has_per_env_store = (
        (string) get_option( 'elementsell_thepay_demo_merchant_id', '' ) !== ''
        || (string) get_option( 'elementsell_thepay_production_merchant_id', '' ) !== ''
    );

    // Legacy my_* jen když ještě neexistují per-environment options (starý web).
    // Jinak by demo platba mohla omylem sáhnout po ostrých my_* údajích.
    $use_legacy_fallback = ! $has_per_env_store;

    return [
        'environment'  => $environment,
        'project_id'   => (int) ( false !== $project_id ? $project_id : ( $use_legacy_fallback ? get_option( 'my_project_id', 0 ) : 0 ) ),
        'merchant_id'  => (string) ( false !== $merchant_id ? $merchant_id : ( $use_legacy_fallback ? get_option( 'my_merchant_id', '' ) : '' ) ),
        'api_password' => (string) ( false !== $api_password ? $api_password : ( $use_legacy_fallback ? get_option( 'my_api_password', '' ) : '' ) ),
    ];
}

/**
 * Demo/ostrý credentials jen z per-environment options — bez legacy my_* fallbacku.
 *
 * @param string $environment
 * @return array{environment: string, project_id: int, merchant_id: string, api_password: string}
 */
function elementsell_resolve_thepay_credentials_from_options_strict( $environment ) {
    $environment = $environment === 'production' ? 'production' : 'demo';
    $option_key  = 'elementsell_thepay_' . $environment . '_';

    return [
        'environment'  => $environment,
        'project_id'   => (int) get_option( $option_key . 'project_id', 0 ),
        'merchant_id'  => trim( (string) get_option( $option_key . 'merchant_id', '' ) ),
        'api_password' => trim( (string) get_option( $option_key . 'api_password', '' ) ),
    ];
}

/**
 * Credentials pro landing demo — vždy demo prostředí, nikdy ostrý fallback.
 *
 * @param array|null $settings
 * @return array{environment: string, project_id: int, merchant_id: string, api_password: string}|null
 */
function elementsell_resolve_thepay_credentials_for_landing_demo( $settings = null ) {
    $credentials = elementsell_resolve_thepay_credentials_from_options_strict( 'demo' );

    if ( is_array( $settings ) ) {
        $from_settings = elementsell_get_thepay_credentials_for_environment( $settings, 'demo' );

        if ( $credentials['merchant_id'] === '' && $from_settings['merchant_id'] !== '' ) {
            $credentials['merchant_id'] = $from_settings['merchant_id'];
        }

        if ( $credentials['project_id'] <= 0 && (int) $from_settings['project_id'] > 0 ) {
            $credentials['project_id'] = (int) $from_settings['project_id'];
        }

        if ( $credentials['api_password'] === '' && $from_settings['api_password'] !== '' ) {
            $credentials['api_password'] = $from_settings['api_password'];
        }
    }

    $credentials['environment']  = 'demo';
    $credentials['project_id']   = (int) $credentials['project_id'];
    $credentials['merchant_id']  = trim( (string) $credentials['merchant_id'] );
    $credentials['api_password'] = trim( (string) $credentials['api_password'] );

    $credentials = apply_filters( 'elementsell_landing_demo_thepay_credentials', $credentials, $settings );

    if (
        $credentials['merchant_id'] === ''
        || $credentials['project_id'] <= 0
        || $credentials['api_password'] === ''
        || $credentials['environment'] !== 'demo'
    ) {
        return null;
    }

    return $credentials;
}

/**
 * @return string fio|thepay
 */
function elementsell_get_last_payment_method() {
    $method = (string) get_option( 'elementsell_last_payment_method', '' );

    if ( in_array( $method, [ 'fio', 'thepay' ], true ) ) {
        return $method;
    }

    return 'fio';
}

/**
 * Výchozí jméno odesílatele e-mailu z nastavení faktur (faktury_jmeno).
 *
 * @return string
 */
function elementsell_get_widget_email_from_name_default() {
    $invoice_name = trim( (string) get_option( 'faktury_jmeno', '' ) );

    if ( $invoice_name !== '' ) {
        return $invoice_name;
    }

    return trim( (string) get_bloginfo( 'name' ) );
}

/**
 * Staré nebo prázdné hodnoty jména odesílatele ve widgetu.
 *
 * @param string $name
 * @return bool
 */
function elementsell_is_legacy_widget_sender_name( $name ) {
    $name = trim( (string) $name );

    return $name === '' || $name === 'Ruda z Ostravy' || $name === 'Platební formulář';
}

/**
 * Globální výchozí hodnoty platebních polí widgetu z WP options.
 *
 * @return array<string, string>
 */
function elementsell_get_payment_widget_global_defaults() {
    $defaults = [
        'payment_method'     => elementsell_get_last_payment_method(),
        'fio_account_number' => function_exists( 'elementsell_get_fio_account_number' )
            ? elementsell_get_fio_account_number()
            : '',
        'fio_api_token'      => trim( (string) get_option( 'fio_api_token', '' ) ),
    ];

    foreach ( [ 'demo', 'production' ] as $env ) {
        $credentials = elementsell_resolve_thepay_credentials_from_options( $env );

        $defaults[ $env . '_project_id' ]   = $credentials['project_id'] > 0 ? (string) $credentials['project_id'] : '';
        $defaults[ $env . '_merchant_id' ]  = $credentials['merchant_id'];
        $defaults[ $env . '_api_password' ] = $credentials['api_password'];
    }

    $meta_pixel_id = trim( (string) get_option( 'meta_pixel_id', '' ) );

    if ( $meta_pixel_id !== '' ) {
        $defaults['meta_pixel_id'] = $meta_pixel_id;
    }

    $meta_capi_token = trim( (string) get_option( 'meta_capi_token', '' ) );

    if ( $meta_capi_token !== '' ) {
        $defaults['meta_capi_token'] = $meta_capi_token;
    }

    $email_from_name = elementsell_get_widget_email_from_name_default();

    if ( $email_from_name !== '' ) {
        $defaults['email_from_name'] = $email_from_name;
    }

    return $defaults;
}

/**
 * Doplní prázdná platební pole widgetu z globálních WP options.
 *
 * @param array|null $settings
 * @return array
 */
function elementsell_merge_payment_widget_global_defaults( $settings ) {
    if ( ! is_array( $settings ) ) {
        $settings = [];
    }

    $global_defaults = elementsell_get_payment_widget_global_defaults();
    // environment (demo/ostrý) sem záměrně nepatří — je vždy per-widget, ne webový default.
    $credential_keys = [
        'payment_method',
        'fio_account_number',
        'fio_api_token',
        'demo_project_id',
        'demo_merchant_id',
        'demo_api_password',
        'production_project_id',
        'production_merchant_id',
        'production_api_password',
        'meta_pixel_id',
        'meta_capi_token',
        'email_from_name',
    ];

    if (
        isset( $settings['email_from_name'] )
        && elementsell_is_legacy_widget_sender_name( $settings['email_from_name'] )
    ) {
        $settings['email_from_name'] = '';
    }

    foreach ( $credential_keys as $key ) {
        if ( ! array_key_exists( $key, $global_defaults ) ) {
            continue;
        }

        $global_value = $global_defaults[ $key ];

        if ( $global_value === '' || $global_value === null ) {
            continue;
        }

        if ( ! array_key_exists( $key, $settings ) || $settings[ $key ] === '' || $settings[ $key ] === null ) {
            $settings[ $key ] = $global_value;
        }
    }

    return $settings;
}

/**
 * @param array $settings
 * @return void
 */
function elementsell_sync_fio_widget_credentials_to_options( $settings ) {
    if ( ! is_array( $settings ) || ! function_exists( 'elementsell_normalize_fio_account_number' ) ) {
        return;
    }

    $fio_account_number = isset( $settings['fio_account_number'] )
        ? elementsell_normalize_fio_account_number( sanitize_text_field( $settings['fio_account_number'] ) )
        : '';
    $fio_api_token      = isset( $settings['fio_api_token'] ) ? sanitize_text_field( $settings['fio_api_token'] ) : '';

    if ( $fio_account_number !== '' && elementsell_get_fio_account_number() !== $fio_account_number ) {
        update_option( 'fio_account_number', $fio_account_number );
    }

    if ( $fio_api_token !== '' && get_option( 'fio_api_token' ) !== $fio_api_token ) {
        update_option( 'fio_api_token', $fio_api_token );
    }
}

/**
 * Uloží platební credentials z widgetu do globálních WP options.
 *
 * @param array $settings
 * @return void
 */
/**
 * Vytáhne číslo pixelu z vloženého JS snippetu — fbq('init', '123...') i varianta
 * s dvojitými uvozovkami a noscript obrázek https://www.facebook.com/tr?id=123...
 *
 * @param string $code
 * @return string
 */
function elementsell_extract_pixel_id_from_code( $code ) {
    $patterns = [
        '/fbq\s*\(\s*[\'"]init[\'"]\s*,\s*[\'"](\d{6,20})[\'"]/i',
        '/facebook\.com\/tr\?id=(\d{6,20})/i',
    ];

    foreach ( $patterns as $pattern ) {
        if ( preg_match( $pattern, (string) $code, $matches ) ) {
            return $matches[1];
        }
    }

    return '';
}

function elementsell_sync_payment_widget_credentials_to_options( $settings ) {
    if ( ! is_array( $settings ) ) {
        return;
    }

    elementsell_sync_fio_widget_credentials_to_options( $settings );
    elementsell_sync_thepay_widget_credentials_to_options( $settings );

    if ( isset( $settings['payment_method'] ) && in_array( $settings['payment_method'], [ 'fio', 'thepay' ], true ) ) {
        update_option( 'elementsell_last_payment_method', $settings['payment_method'] );
    }

    $meta_pixel_id = isset( $settings['meta_pixel_id'] )
        ? preg_replace( '/[^0-9]/', '', (string) $settings['meta_pixel_id'] )
        : '';

    // Záchrana: pixel ID nevyplněné, ale je ve vloženém snippetu jako fbq('init', '...').
    if ( $meta_pixel_id === '' && ! empty( $settings['meta_pixel_code'] ) ) {
        $meta_pixel_id = elementsell_extract_pixel_id_from_code( (string) $settings['meta_pixel_code'] );
    }

    if ( $meta_pixel_id !== '' && get_option( 'meta_pixel_id' ) !== $meta_pixel_id ) {
        update_option( 'meta_pixel_id', $meta_pixel_id );
    }

    $meta_capi_token = isset( $settings['meta_capi_token'] ) ? sanitize_textarea_field( $settings['meta_capi_token'] ) : '';

    if ( $meta_capi_token !== '' && get_option( 'meta_capi_token' ) !== $meta_capi_token ) {
        update_option( 'meta_capi_token', $meta_capi_token );
    }
}

/**
 * Credentials pro vytvoření platby: widget z Elementoru má přednost před WP options.
 *
 * @param array|null $widget_settings
 * @return array{environment: string, project_id: int, merchant_id: string, api_password: string}
 */
function elementsell_resolve_thepay_credentials_for_payment( $widget_settings = null ) {
    if ( ! is_array( $widget_settings ) || empty( $widget_settings ) ) {
        return elementsell_resolve_thepay_credentials_from_options();
    }

    $from_widget = elementsell_resolve_thepay_widget_credentials( $widget_settings );
    $environment = $from_widget['environment'];
    $from_options = elementsell_resolve_thepay_credentials_from_options( $environment );

    return [
        'environment'  => $environment,
        'merchant_id'  => $from_widget['merchant_id'] !== '' ? $from_widget['merchant_id'] : $from_options['merchant_id'],
        'project_id'   => (int) ( $from_widget['project_id'] !== '' ? $from_widget['project_id'] : $from_options['project_id'] ),
        'api_password' => $from_widget['api_password'] !== '' ? $from_widget['api_password'] : $from_options['api_password'],
    ];
}

/**
 * Nahradí prázdné/legacy jméno odesílatele ve widgetu globálním defaultem (faktury_jmeno).
 *
 * @param array $settings
 * @return array
 */
function elementsell_apply_payment_widget_email_from_name_default( $settings ) {
    if ( ! is_array( $settings ) ) {
        return $settings;
    }

    if ( ! elementsell_is_legacy_widget_sender_name( $settings['email_from_name'] ?? '' ) ) {
        return $settings;
    }

    $default = elementsell_get_widget_email_from_name_default();

    if ( $default !== '' ) {
        $settings['email_from_name'] = $default;
    }

    return $settings;
}

/**
 * Projde strom Elementor elementů a doplní email_from_name u platebního widgetu.
 *
 * @param array $elements
 * @return bool True pokud došlo ke změně.
 */
function elementsell_walk_elements_apply_email_from_name_default( &$elements ) {
    if ( ! is_array( $elements ) ) {
        return false;
    }

    $changed = false;

    foreach ( $elements as &$element ) {
        if (
            ! empty( $element['widgetType'] )
            && $element['widgetType'] === 'elementsell_payment_form'
            && isset( $element['settings'] )
            && is_array( $element['settings'] )
        ) {
            $before = $element['settings']['email_from_name'] ?? null;
            $element['settings'] = elementsell_apply_payment_widget_email_from_name_default( $element['settings'] );
            $after  = $element['settings']['email_from_name'] ?? null;

            if ( $before !== $after ) {
                $changed = true;
            }
        }

        if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
            if ( elementsell_walk_elements_apply_email_from_name_default( $element['elements'] ) ) {
                $changed = true;
            }
        }
    }

    unset( $element );

    return $changed;
}

/**
 * Má se při načtení _elementor_data nahradit legacy email_from_name (editor / preview)?
 *
 * @return bool
 */
function elementsell_should_filter_elementor_email_from_name_context() {
    if ( ! function_exists( 'elementsell_is_elementor_context' ) || ! elementsell_is_elementor_context() ) {
        return false;
    }

    if ( function_exists( 'is_admin' ) && is_admin() ) {
        return true;
    }

    if ( isset( $_GET['elementor-preview'] ) || isset( $_POST['elementor-preview'] ) ) {
        return true;
    }

    return false;
}

/**
 * Při načtení _elementor_data v editoru nahradí legacy email_from_name faktury_jmeno.
 *
 * @param mixed  $value
 * @param int    $object_id
 * @param string $meta_key
 * @param bool   $single
 * @return mixed
 */
function elementsell_filter_elementor_data_email_from_name( $value, $object_id, $meta_key, $single ) {
    if ( $meta_key !== '_elementor_data' || ! elementsell_should_filter_elementor_email_from_name_context() ) {
        return $value;
    }

    static $processing = [];

    $cache_key = (int) $object_id . ':' . ( $single ? '1' : '0' );

    if ( isset( $processing[ $cache_key ] ) ) {
        return $value;
    }

    $processing[ $cache_key ] = true;

    remove_filter( 'get_post_metadata', 'elementsell_filter_elementor_data_email_from_name', 10 );

    $raw = get_post_meta( (int) $object_id, '_elementor_data', $single );

    add_filter( 'get_post_metadata', 'elementsell_filter_elementor_data_email_from_name', 10, 4 );

    unset( $processing[ $cache_key ] );

    if ( ! is_string( $raw ) || $raw === '' || strpos( $raw, 'elementsell_payment_form' ) === false ) {
        return $value;
    }

    $elements = json_decode( $raw, true );

    if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $elements ) ) {
        return $value;
    }

    if ( ! elementsell_walk_elements_apply_email_from_name_default( $elements ) ) {
        return $value;
    }

    $modified = wp_json_encode( $elements );

    return $single ? $modified : [ $modified ];
}

/**
 * Před uložením dokumentu v Elementoru normalizuje legacy email_from_name.
 *
 * @param array                         $data
 * @param \Elementor\Core\Base\Document $document
 * @return array
 */
function elementsell_filter_elementor_document_save_email_from_name( $data, $document ) {
    unset( $document );

    if ( ! empty( $data['elements'] ) && is_array( $data['elements'] ) ) {
        elementsell_walk_elements_apply_email_from_name_default( $data['elements'] );
    }

    return $data;
}

/**
 * Preview iframe v builderu — stejná normalizace jako v panelu editoru.
 *
 * @param array $elements
 * @param int   $post_id
 * @return array
 */
function elementsell_filter_elementor_builder_content_email_from_name( $elements, $post_id ) {
    unset( $post_id );

    if ( is_array( $elements ) ) {
        elementsell_walk_elements_apply_email_from_name_default( $elements );
    }

    return $elements;
}

/**
 * Default jméno odesílatele pro JS zálohu v panelu editoru.
 *
 * @param array $config
 * @param int   $post_id
 * @return array
 */
function elementsell_localize_editor_email_from_name_default( $config, $post_id = 0 ) {
    unset( $post_id );

    if ( ! is_array( $config ) ) {
        $config = [];
    }

    $config['elementsellEmailFromName'] = [
        'default' => elementsell_get_widget_email_from_name_default(),
        'legacy'  => [ '', 'Platební formulář', 'Ruda z Ostravy' ],
    ];

    return $config;
}

/**
 * @return void
 */
function elementsell_register_elementor_email_from_name_editor_hooks() {
    static $registered = false;

    if ( $registered ) {
        return;
    }

    $registered = true;

    add_filter( 'get_post_metadata', 'elementsell_filter_elementor_data_email_from_name', 10, 4 );
    add_filter( 'elementor/document/save/data', 'elementsell_filter_elementor_document_save_email_from_name', 10, 2 );
    add_filter( 'elementor/frontend/builder_content_data', 'elementsell_filter_elementor_builder_content_email_from_name', 10, 2 );
    add_filter( 'elementor/document/config', 'elementsell_localize_editor_email_from_name_default', 10, 2 );
    add_filter( 'elementor/editor/localize_settings', 'elementsell_localize_editor_email_from_name_default', 10, 2 );
}
