<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function rm_wc_blocks_checkout_init() {
    static $registered_forms = array();

    if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) || is_user_logged_in() ) {
        return;
    }

    $wc_guest_checkout = get_option( 'woocommerce_enable_guest_checkout' );
    if ( $wc_guest_checkout === 'yes' ) {
        return;
    }

    $form_id = get_rm_wc_checkout_form();
    if ( ! $form_id || rm_is_form_expired( $form_id ) ) {
        return;
    }

    if ( isset( $registered_forms[ $form_id ] ) ) {
        return;
    }

    $registered_forms[ $form_id ] = true;

    foreach ( rm_wc_blocks_get_checkout_fields( $form_id ) as $field ) {
        try {
            woocommerce_register_additional_checkout_field( $field );
        } catch ( Exception $e ) {
            continue;
        }
    }
}

function rm_wc_blocks_get_checkout_fields( $form_id ) {
    $service = new RM_Front_Form_Service();
    $fields  = $service->get_all_form_fields( $form_id );
    $output  = array();

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

    foreach ( $fields as $field ) {
        if ( empty( $field ) || ! empty( $field->is_field_primary ) ) {
            continue;
        }

        if ( rm_wc_blocks_is_pricing_field( $field->field_type ) || rm_wc_blocks_is_wc_address_field( $field->field_type ) ) {
            continue;
        }

        $block_field = rm_wc_blocks_prepare_checkout_field( $field );
        if ( empty( $block_field ) ) {
            continue;
        }

        if ( rm_wc_blocks_is_multi_checkbox_field( $field->field_type ) ) {
            $output = array_merge( $output, $block_field );
        } else {
            $output[] = $block_field;
        }
    }

    return $output;
}

function rm_wc_blocks_is_pricing_field( $field_type ) {
    return in_array(
        strtolower( str_replace( array( '-', '_' ), '', $field_type ) ),
        array( 'price', 'pricev', 'subscription' ),
        true
    );
}

function rm_wc_blocks_is_wc_address_field( $field_type ) {
    return in_array(
        strtolower( str_replace( array( '-', '_' ), '', $field_type ) ),
        array( 'wcbilling', 'wcshipping', 'wcbillingphone' ),
        true
    );
}

function rm_wc_blocks_is_multi_checkbox_field( $field_type ) {
    return in_array(
        strtolower( str_replace( '-', '', $field_type ) ),
        array( 'checkbox', 'multidropdown' ),
        true
    );
}

function rm_wc_blocks_prepare_checkout_field( $field ) {
    $rm_type    = strtolower( str_replace( '-', '', $field->field_type ) );
    $field_name = $field->field_type . '_' . $field->field_id;
    $options    = maybe_unserialize( $field->field_options );
    $required   = ! empty( $options->field_is_required );
    $label      = wp_strip_all_tags( $field->field_label );

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

    $type_map = apply_filters(
        'rm_wc_blocks_field_type_map',
        array(
            'textbox'  => 'text',
            'text'     => 'text',
            'textarea' => 'text',
            'number'   => 'text',
            'mobile'   => 'text',
            'phone'    => 'text',
            'url'      => 'text',
            'website'  => 'text',
            'date'     => 'text',
            'fname'    => 'text',
            'lname'    => 'text',
            'binfo'    => 'text',
            'nickname' => 'text',
            'secemail' => 'text',
            'gender'   => 'select',
            'radio'    => 'select',
            'select'   => 'select',
            'country'  => 'select',
            'language' => 'select',
            'checkbox' => 'checkbox',
            'multidropdown' => 'checkbox',
            'terms'    => 'checkbox',
            'privacy'  => 'checkbox',
        )
    );

    $block_type = empty( $type_map[ $rm_type ] ) ? 'text' : $type_map[ $rm_type ];

    if ( rm_wc_blocks_is_multi_checkbox_field( $field->field_type ) ) {
        return rm_wc_blocks_get_checkbox_options( $field, $field_name, $required );
    }

    $block_field = array(
        'id'       => 'registrationmagic/' . $field_name,
        'label'    => $label,
        'location' => 'order',
        'type'     => $block_type,
        'required' => (bool) $required,
    );

    if ( ! empty( $options->field_placeholder ) && $block_field['type'] === 'text' ) {
        $block_field['placeholder'] = wp_strip_all_tags( $options->field_placeholder );
    }

    if ( $block_field['type'] === 'select' ) {
        $block_field['options'] = rm_wc_blocks_get_select_options( $field, $options );
        if ( empty( $block_field['options'] ) ) {
            $block_field['type'] = 'text';
            unset( $block_field['options'] );
        }
    }

    return apply_filters( 'rm_wc_blocks_checkout_field', $block_field, $field, $options );
}

function rm_wc_blocks_get_select_options( $field, $options ) {
    $choices = RM_Utilities::process_field_options( maybe_unserialize( $field->field_value ) );
    $output  = array();

    foreach ( $choices as $value => $label ) {
        if ( trim( (string) $value ) === '' ) {
            continue;
        }

        $output[] = array(
            'label' => wp_strip_all_tags( $label ),
            'value' => sanitize_text_field( $value ),
        );
    }

    return $output;
}

function rm_wc_blocks_get_checkbox_options( $field, $field_name, $required ) {
    $choices = RM_Utilities::process_field_options( maybe_unserialize( $field->field_value ) );
    $output  = array();
    $index   = 0;

    foreach ( $choices as $value => $label ) {
        if ( trim( (string) $value ) === '' ) {
            continue;
        }

        $output[] = array(
            'id'       => 'registrationmagic/' . $field_name . '__rmopt_' . $index,
            'label'    => wp_strip_all_tags( $label ),
            'location' => 'order',
            'type'     => 'checkbox',
            'required' => false,
        );

        $index++;
    }

    return $output;
}

function rm_wc_blocks_get_field_types_by_name( $form_id ) {
    $service = new RM_Front_Form_Service();
    $fields  = $service->get_all_form_fields( $form_id );
    $output  = array();

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

    foreach ( $fields as $field ) {
        if ( empty( $field ) ) {
            continue;
        }

        $output[ $field->field_type . '_' . $field->field_id ] = strtolower( str_replace( '-', '', $field->field_type ) );
    }

    return $output;
}

function rm_wc_blocks_get_checkbox_option_values( $form_id ) {
    $service = new RM_Front_Form_Service();
    $fields  = $service->get_all_form_fields( $form_id );
    $output  = array();

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

    foreach ( $fields as $field ) {
        if ( empty( $field ) || ! rm_wc_blocks_is_multi_checkbox_field( $field->field_type ) ) {
            continue;
        }

        $field_name = $field->field_type . '_' . $field->field_id;
        $choices    = RM_Utilities::process_field_options( maybe_unserialize( $field->field_value ) );
        $index      = 0;

        foreach ( $choices as $value => $label ) {
            if ( trim( (string) $value ) === '' ) {
                continue;
            }

            $output[ $field_name . '__rmopt_' . $index ] = array(
                'field_name' => $field_name,
                'value'      => sanitize_text_field( $value ),
            );
            $index++;
        }
    }

    return $output;
}

function rm_wc_blocks_checkout_update_order_from_request( $order, $request ) {
    if ( is_user_logged_in() ) {
        return;
    }

    $form_id = get_rm_wc_checkout_form();
    if ( ! $form_id || rm_is_form_expired( $form_id ) ) {
        return;
    }

    $field_types            = rm_wc_blocks_get_field_types_by_name( $form_id );
    $checkbox_option_values = rm_wc_blocks_get_checkbox_option_values( $form_id );

    foreach ( $field_types as $field_name => $field_type ) {
        if ( in_array( $field_type, array( 'checkbox', 'multidropdown' ), true ) ) {
            $_POST[ $field_name ] = array();
        }
    }

    rm_wc_blocks_populate_post_addresses( (array) $request['billing_address'], 'billing' );
    rm_wc_blocks_populate_post_addresses( (array) $request['shipping_address'], 'shipping' );

    if ( ! empty( $request['billing_address']['email'] ) ) {
        $_POST['email']         = sanitize_email( $request['billing_address']['email'] );
        $_POST['billing_email'] = sanitize_email( $request['billing_address']['email'] );
    }

    $additional_fields = (array) $request['additional_fields'];
    foreach ( $additional_fields as $field_id => $value ) {
        if ( strpos( $field_id, 'registrationmagic/' ) !== 0 ) {
            continue;
        }

        $rm_field_name           = substr( $field_id, strlen( 'registrationmagic/' ) );

        if ( isset( $checkbox_option_values[ $rm_field_name ] ) ) {
            if ( filter_var( $value, FILTER_VALIDATE_BOOLEAN ) ) {
                $checkbox_field = $checkbox_option_values[ $rm_field_name ]['field_name'];
                $_POST[ $checkbox_field ][] = $checkbox_option_values[ $rm_field_name ]['value'];
            }
            continue;
        }

        $rm_field_type           = isset( $field_types[ $rm_field_name ] ) ? $field_types[ $rm_field_name ] : '';
        $sanitized_value         = is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : sanitize_text_field( $value );

        if ( in_array( $rm_field_type, array( 'checkbox', 'multidropdown' ), true ) && ! is_array( $sanitized_value ) ) {
            $sanitized_value = $sanitized_value === '' ? array() : array( $sanitized_value );
        }

        if ( in_array( $rm_field_type, array( 'terms', 'privacy' ), true ) ) {
            $sanitized_value = filter_var( $value, FILTER_VALIDATE_BOOLEAN ) ? '1' : '';
        }

        $_POST[ $rm_field_name ] = $sanitized_value;
    }

    if ( empty( $_POST['stat_id'] ) ) {
        $_POST['stat_id'] = '__uninit';
    }
}

function rm_wc_blocks_populate_post_addresses( $address, $prefix ) {
    $keys = array(
        'first_name',
        'last_name',
        'company',
        'address_1',
        'address_2',
        'city',
        'state',
        'postcode',
        'country',
        'phone',
    );

    foreach ( $keys as $key ) {
        if ( isset( $address[ $key ] ) ) {
            $_POST[ $prefix . '_' . $key ] = sanitize_text_field( $address[ $key ] );
        }
    }
}
