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

/**
 * @param array $settings
 * @return bool
 */
function elementsell_are_custom_fields_visible( $settings ) {
    if ( ! is_array( $settings ) ) {
        return false;
    }

    if ( ! array_key_exists( 'show_custom_fields', $settings ) ) {
        return true;
    }

    return $settings['show_custom_fields'] === 'yes';
}

/**
 * @param array $settings
 * @return array<int, array{label: string, type: string}>
 */
function elementsell_get_custom_fields_from_widget_settings( $settings ) {
    if ( ! is_array( $settings ) ) {
        return [];
    }

    if ( ! elementsell_are_custom_fields_visible( $settings ) ) {
        return [];
    }

    if ( ! empty( $settings['custom_fields'] ) && is_array( $settings['custom_fields'] ) ) {
        $fields = [];

        foreach ( $settings['custom_fields'] as $field ) {
            if ( ! is_array( $field ) ) {
                continue;
            }

            $label = trim( (string) ( $field['label'] ?? '' ) );
            $type  = trim( (string) ( $field['type'] ?? 'text' ) );

            if ( $label === '' ) {
                continue;
            }

            if ( ! in_array( $type, [ 'text', 'number', 'date', 'textarea', 'switch' ], true ) ) {
                $type = 'text';
            }

            if ( $type === 'time' || $type === 'cas' ) {
                $type = 'text';
            }

            if ( $type === 'number' || $type === 'textarea' ) {
                $type = 'text';
            }

            $entry = [
                'label' => $label,
                'type'  => $type,
            ];

            if ( $type === 'date' ) {
                $date_terms = elementsell_get_date_terms_from_field_settings( $field );

                if ( ! empty( $date_terms ) ) {
                    $entry['date_terms'] = $date_terms;
                }
            }

            $fields[] = $entry;
        }

        if ( ! empty( $fields ) ) {
            return $fields;
        }
    }

    if ( ! empty( $settings['show_custom_field'] ) && $settings['show_custom_field'] === 'yes' ) {
        $legacy_type = ! empty( $settings['custom_field_type'] )
            ? (string) $settings['custom_field_type']
            : 'text';

        if ( $legacy_type === 'number' || $legacy_type === 'textarea' ) {
            $legacy_type = 'text';
        }

        return [
            [
                'label' => ! empty( $settings['custom_field_label'] )
                    ? (string) $settings['custom_field_label']
                    : 'Vlastní pole',
                'type'  => $legacy_type,
            ],
        ];
    }

    return [];
}

/**
 * @param string $term_value
 * @return string
 */
function elementsell_normalize_date_term_value( $term_value ) {
    $term_value = trim( (string) $term_value );

    if ( $term_value === '' ) {
        return '';
    }

    if ( preg_match( '/^(\d{4}-\d{2}-\d{2})/', $term_value, $matches ) ) {
        return $matches[1];
    }

    $timestamp = strtotime( $term_value );

    if ( ! $timestamp ) {
        return '';
    }

    return wp_date( 'Y-m-d', $timestamp );
}

/**
 * @param string $date_value
 * @param string $time_value Nepoužívá se — zachováno kvůli zpětné kompatibilitě.
 * @return string
 */
function elementsell_build_date_term_value( $date_value, $time_value = '' ) {
    return elementsell_normalize_date_term_value( $date_value );
}

/**
 * @param string $line
 * @return string
 */
function elementsell_parse_date_term_line( $line ) {
    $line = trim( (string) $line );

    if ( $line === '' ) {
        return '';
    }

    if ( preg_match( '/^(\d{4}-\d{2}-\d{2})/', $line, $matches ) ) {
        return elementsell_normalize_date_term_value( $matches[1] );
    }

    return elementsell_normalize_date_term_value( $line );
}

/**
 * @param mixed $raw_terms
 * @return array<int, string>
 */
function elementsell_parse_date_terms_value( $raw_terms ) {
    $terms = [];

    if ( is_array( $raw_terms ) ) {
        foreach ( $raw_terms as $item ) {
            if ( is_array( $item ) ) {
                $normalized = elementsell_normalize_date_term_value(
                    $item['date'] ?? $item['value'] ?? ''
                );
            } else {
                $normalized = elementsell_parse_date_term_line( $item );
            }

            if ( $normalized !== '' ) {
                $terms[] = $normalized;
            }
        }

        return $terms;
    }

    if ( ! is_string( $raw_terms ) || trim( $raw_terms ) === '' ) {
        return [];
    }

    foreach ( preg_split( '/\R/', $raw_terms ) as $line ) {
        $normalized = elementsell_parse_date_term_line( $line );

        if ( $normalized !== '' ) {
            $terms[] = $normalized;
        }
    }

    return $terms;
}

/**
 * @param array $field
 * @return array<int, string>
 */
function elementsell_get_date_terms_from_field_settings( $field ) {
    if ( ! is_array( $field ) ) {
        return [];
    }

    $terms = elementsell_parse_date_terms_value( $field['date_terms'] ?? null );

    if ( ! empty( $terms ) ) {
        return $terms;
    }

    foreach ( [ 'date_term_1', 'date_term_2', 'date_term_3' ] as $term_key ) {
        $normalized = elementsell_normalize_date_term_value( $field[ $term_key ] ?? '' );

        if ( $normalized !== '' ) {
            $terms[] = $normalized;
        }
    }

    return $terms;
}

/**
 * @param string $date_value
 * @return string
 */
function elementsell_format_date_field_display( $date_value ) {
    $date_value = elementsell_normalize_date_term_value( $date_value );

    if ( $date_value === '' ) {
        return '';
    }

    $timestamp = strtotime( $date_value );

    if ( ! $timestamp ) {
        return (string) $date_value;
    }

    return wp_date( 'j. n. Y', $timestamp );
}

/**
 * @param array  $field
 * @param int    $index
 * @param bool   $is_editor
 * @param string $required_attr
 * @return void
 */
function elementsell_render_payment_custom_field( $field, $index, $is_editor, $required_attr = '' ) {
    $label = (string) ( $field['label'] ?? '' );
    $type  = (string) ( $field['type'] ?? 'text' );
    $name  = 'elementsell_custom_fields[' . (int) $index . ']';

    if ( $label === '' ) {
        return;
    }

    if ( $type === 'switch' ) {
        ?>
        <label class="elementsell-custom-switch">
            <input
                type="checkbox"
                name="<?php echo esc_attr( $name . '[value]' ); ?>"
                value="1"
            >
            <span><?php echo esc_html( $label ); ?></span>
        </label>
        <?php
    } elseif ( $type === 'date' ) {
        $date_terms = ! empty( $field['date_terms'] ) && is_array( $field['date_terms'] )
            ? array_values( array_filter( array_map( 'strval', $field['date_terms'] ) ) )
            : [];
        $field_id     = 'elementsell-custom-field-' . (int) $index;
        $value_name   = $name . '[value]';
        $terms_count  = count( $date_terms );
        ?>
        <div class="elementsell-custom-field elementsell-custom-field--date">
            <?php if ( $terms_count > 1 ) : ?>
                <label class="elementsell-field-label" for="<?php echo esc_attr( $field_id ); ?>">
                    <?php echo esc_html( $label ); ?>
                </label>
                <select
                    id="<?php echo esc_attr( $field_id ); ?>"
                    class="elementsell-field"
                    name="<?php echo esc_attr( $value_name ); ?>"
                    <?php echo $is_editor ? '' : $required_attr; ?>
                >
                    <option value=""><?php esc_html_e( 'Vyberte termín', 'platebni-formular' ); ?></option>
                    <?php foreach ( $date_terms as $date_term ) : ?>
                        <option value="<?php echo esc_attr( $date_term ); ?>">
                            <?php echo esc_html( elementsell_format_date_field_display( $date_term ) ); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            <?php elseif ( 1 === $terms_count ) : ?>
                <span class="elementsell-field-label"><?php echo esc_html( $label ); ?></span>
                <div class="elementsell-date-value">
                    <?php echo esc_html( elementsell_format_date_field_display( $date_terms[0] ) ); ?>
                </div>
                <input type="hidden" name="<?php echo esc_attr( $value_name ); ?>" value="<?php echo esc_attr( $date_terms[0] ); ?>">
            <?php else : ?>
                <label class="elementsell-field-label" for="<?php echo esc_attr( $field_id ); ?>">
                    <?php echo esc_html( $label ); ?>
                </label>
                <input
                    type="date"
                    id="<?php echo esc_attr( $field_id ); ?>"
                    class="elementsell-field"
                    name="<?php echo esc_attr( $value_name ); ?>"
                    <?php echo $is_editor ? '' : $required_attr; ?>
                >
            <?php endif; ?>
        </div>
        <?php
    } else {
        ?>
        <input
            type="text"
            class="elementsell-field"
            name="<?php echo esc_attr( $name . '[value]' ); ?>"
            placeholder="<?php echo esc_attr( $label ); ?>"
            <?php echo $is_editor ? '' : $required_attr; ?>
        >
        <?php
    }

    if ( ! $is_editor ) {
        ?>
        <input type="hidden" name="<?php echo esc_attr( $name . '[label]' ); ?>" value="<?php echo esc_attr( $label ); ?>">
        <input type="hidden" name="<?php echo esc_attr( $name . '[type]' ); ?>" value="<?php echo esc_attr( $type ); ?>">
        <?php
    }
}

/**
 * @param int $order_id
 * @return void
 */
function elementsell_save_custom_fields_from_post( $order_id ) {
    $order_id = (int) $order_id;

    if ( $order_id <= 0 ) {
        return;
    }

    if ( ! empty( $_POST['elementsell_custom_fields'] ) && is_array( $_POST['elementsell_custom_fields'] ) ) {
        foreach ( $_POST['elementsell_custom_fields'] as $field ) {
            if ( ! is_array( $field ) ) {
                continue;
            }

            $label = sanitize_text_field( (string) ( $field['label'] ?? '' ) );
            $type  = sanitize_key( (string) ( $field['type'] ?? 'text' ) );

            if ( $label === '' ) {
                continue;
            }

            if ( $type === 'switch' ) {
                $value = ! empty( $field['value'] ) ? 'Ano' : 'Ne';
            } else {
                $value = sanitize_textarea_field( (string) ( $field['value'] ?? '' ) );

                if ( $type === 'date' && $value !== '' ) {
                    $value = elementsell_format_date_field_display( $value );
                }
            }

            if ( $value === '' && $type !== 'switch' ) {
                continue;
            }

            elementsell_save_order_label_field( $order_id, $label, $value );
        }

        return;
    }

    if ( isset( $_POST['custom_field_value'] ) && (string) $_POST['custom_field_value'] !== '' ) {
        $label = isset( $_POST['custom_field_label'] )
            ? sanitize_text_field( wp_unslash( $_POST['custom_field_label'] ) )
            : 'Vlastní pole';

        elementsell_save_order_label_field(
            $order_id,
            $label,
            sanitize_textarea_field( wp_unslash( (string) $_POST['custom_field_value'] ) )
        );
    }
}

/**
 * @param int $post_id
 * @return array<int, string>
 */
function elementsell_collect_custom_field_labels_from_elements( $elements ) {
    $labels = [];

    foreach ( (array) $elements as $element ) {
        if (
            ! empty( $element['widgetType'] )
            && $element['widgetType'] === 'elementsell_payment_form'
            && ! empty( $element['settings'] )
            && is_array( $element['settings'] )
        ) {
            $settings = $element['settings'];

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

            foreach ( elementsell_get_custom_fields_from_widget_settings( $settings ) as $field ) {
                if ( ! empty( $field['label'] ) ) {
                    $labels[] = (string) $field['label'];
                }
            }
        }

        if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
            $labels = array_merge(
                $labels,
                elementsell_collect_custom_field_labels_from_elements( $element['elements'] )
            );
        }
    }

    return $labels;
}

/**
 * @param int $post_id
 * @return array<int, string>
 */
function elementsell_get_custom_field_labels_from_post( $post_id ) {
    $post_id = (int) $post_id;

    if ( $post_id <= 0 ) {
        return [];
    }

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

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

    $elements = json_decode( $raw, true );

    if ( ! is_array( $elements ) ) {
        return [];
    }

    return array_values( array_unique( elementsell_collect_custom_field_labels_from_elements( $elements ) ) );
}

/**
 * @param int $order_id
 * @return array<int, string>
 */
function elementsell_get_widget_custom_field_labels_for_order( $order_id ) {
    $order_id = (int) $order_id;

    if ( $order_id <= 0 ) {
        return [];
    }

    $post_id   = (int) elementsell_get_order_field( $order_id, 'elementsell_post_id' );
    $widget_id = trim( (string) elementsell_get_order_field( $order_id, 'elementsell_widget_id' ) );

    if ( $post_id <= 0 ) {
        $source_url = (string) elementsell_get_order_field( $order_id, 'source_page_url' );

        if ( $source_url !== '' ) {
            $post_id = (int) url_to_postid( $source_url );
        }
    }

    if ( $post_id <= 0 ) {
        return [];
    }

    if ( $widget_id !== '' && function_exists( 'elementsell_find_elementor_widget_settings' ) ) {
        $settings = elementsell_find_elementor_widget_settings( $post_id, $widget_id );

        if ( is_array( $settings ) ) {
            if ( function_exists( 'elementsell_merge_payment_widget_defaults' ) ) {
                $settings = elementsell_merge_payment_widget_defaults( $settings );
            }

            $labels = [];

            foreach ( elementsell_get_custom_fields_from_widget_settings( $settings ) as $field ) {
                if ( ! empty( $field['label'] ) ) {
                    $labels[] = (string) $field['label'];
                }
            }

            if ( ! empty( $labels ) ) {
                return $labels;
            }
        }
    }

    return elementsell_get_custom_field_labels_from_post( $post_id );
}
