<?php

class UserShippingMethodController
{
}

add_action('woocommerce_checkout_order_created', 'woocommerce_checkout_order_created');

function woocommerce_checkout_order_created($order_id)
{
    $order = wc_get_order($order_id);
    $chosen_shipping = wc_get_chosen_shipping_method_ids();
    if (count($chosen_shipping) === 0) {
        return;
    }
    $choose_logistics_id = $chosen_shipping[0];
    if (in_array($choose_logistics_id, ['bf_seven_eleven', 'bf_hi_life', 'bf_family_mart'])) {
        $boxful_cvs_store_id = isset($_COOKIE['boxful_cvs_store_id']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_id']) : '';
        $boxful_cvs_store_name = isset($_COOKIE['boxful_cvs_store_name']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_name']) : '';
        $boxful_cvs_store_address = isset($_COOKIE['boxful_cvs_store_address']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_address']) : '';
        $order->update_meta_data('boxful_cvs_store_id', $boxful_cvs_store_id);
        $order->update_meta_data('boxful_cvs_store_name', $boxful_cvs_store_name);
        $order->update_meta_data('boxful_cvs_store_address', $boxful_cvs_store_address);

        $order->set_shipping_company('');
        $order->set_shipping_address_2('');
        $order->set_shipping_city('');
        $order->set_shipping_state('');
        $order->set_shipping_postcode('');
        $order->set_shipping_address_1($boxful_cvs_store_address . "(" . $boxful_cvs_store_name . ")");

        $order->set_billing_address_2('');
        $order->set_billing_city('');
        $order->set_billing_state('');
        $order->set_billing_postcode('');
        $order->set_billing_address_1($boxful_cvs_store_address . "(" . $boxful_cvs_store_name . ")");

        $order->save();

        unsetCVSData();
    }

}

add_action('woocommerce_review_order_after_shipping', 'shipping_choose_cvs');
function shipping_choose_cvs()
{
    $chosen_shipping = wc_get_chosen_shipping_method_ids();
    $host = get_site_url();
    $current_url = $_SERVER['HTTP_REFERER'];
    $base64_url = base64_encode($current_url);
    $data = [];
    if (count($chosen_shipping) === 0) {
        unsetCVSData();
        return;
    }
    if (
        (isset($_COOKIE['boxful_cvs_open']) && $_COOKIE['boxful_cvs_open'] === 'family_mart' && $chosen_shipping[0] === 'bf_family_mart') ||
        (isset($_COOKIE['boxful_cvs_open']) && $_COOKIE['boxful_cvs_open'] === 'seven_eleven' && $chosen_shipping[0] === 'bf_seven_eleven') ||
        (isset($_COOKIE['boxful_cvs_open']) && $_COOKIE['boxful_cvs_open'] === 'hi_life' && $chosen_shipping[0] === 'bf_hi_life')
    ) {
        $boxful_cvs_store_id = isset($_COOKIE['boxful_cvs_store_id']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_id']) : '';
        $boxful_cvs_store_name = isset($_COOKIE['boxful_cvs_store_name']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_name']) : '';
        $boxful_cvs_store_address = isset($_COOKIE['boxful_cvs_store_address']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_address']) : '';
        $data = [
            'boxful_cvs_store_id'      => $boxful_cvs_store_id,
            'boxful_cvs_store_name'    => $boxful_cvs_store_name,
            'boxful_cvs_store_address' => $boxful_cvs_store_address
        ];
    } else {
        unsetCVSData();
    }
    if ($chosen_shipping[0] === 'bf_seven_eleven') {
        wc_get_template('cart/chooseSevenCVS.php', array_merge([
            'callback_url' => $host . '/wp-json/boxful-fulfillment/cvs-choose-callback/seven-eleven',
            'callback_data' => $base64_url,
            'protocol' => 'https://'
        ], $data), '', BOXFUL_FULFILLMENT_PLUGIN_DIR . 'templates/');
        setcookie("boxful_cvs_open", 'seven_eleven', time() + 3600, '/');
    }
    if ($chosen_shipping[0] === 'bf_family_mart') {
        wc_get_template('cart/chooseFamilyMartCVS.php', array_merge([
            'callback_url' => $host . '/wp-json/boxful-fulfillment/cvs-choose-callback/family-mart',
            'callback_data' => $base64_url,
            'protocol' => 'https://'
        ], $data), '', BOXFUL_FULFILLMENT_PLUGIN_DIR . 'templates/');
        setcookie("boxful_cvs_open", 'family_mart', time() + 3600, '/');
    }
    if ($chosen_shipping[0] === 'bf_hi_life') {
        wc_get_template('cart/chooseHiLifeCVS.php', array_merge([
            'callback_url' => $host . '/wp-json/boxful-fulfillment/cvs-choose-callback/hi-life',
            'callback_data' => $base64_url,
            'protocol' => 'https://'
        ], $data), '', BOXFUL_FULFILLMENT_PLUGIN_DIR . 'templates/');
        setcookie("boxful_cvs_open", 'hi_life', time() + 3600, '/');
    }
}

function unsetCVSData()
{
    setcookie("boxful_cvs_store_id", "", time() - 3600);
    setcookie("boxful_cvs_store_name", "", time() - 3600);
    setcookie("boxful_cvs_store_address", "", time() - 3600);
    setcookie("boxful_cvs_open", "", time() - 3600);
}

add_filter('woocommerce_package_rates', 'packageRate', 10, 2);

function packageRate($rates)
{
    global $woocommerce;
    $total = $woocommerce->cart->cart_contents_total;
    $fee_logistics_data = []; // key => [enabled, price]
    $weight = $woocommerce->cart->get_cart_contents_weight();
    $bf_cross_border_cost = 0;
    $shipping_method_list = $woocommerce->shipping->get_shipping_methods();
    foreach ($shipping_method_list as $method_id => $values) {
        if ('bf_cross_border' === $values->id && $bf_cross_border_cost == 0) {
            $title = 'range' . ((int)$weight - 1);
            $method_detail = $values->instance_settings;
            $bf_cross_border_cost = $method_detail[$title];
        }
        if (!array_key_exists($values->id, $fee_logistics_data)) {
            $fee_logistics_data[$values->id] = [
                'enabled_free_logistics' => $values->instance_settings['enabled_free_logistics'] ?? 'no',
                'free_logistics_price'   => $values->instance_settings['free_logistics_price'] ?? 9999999
            ];
        }
    }
    foreach ($rates as $key => $rate) {
        if ('bf_cross_border' === $rate->id) {
            $rates[$key]->cost = $bf_cross_border_cost;
            if ($bf_cross_border_cost == 0) {
                unset($rates[$key]);
            }
        }

        if ('bf_family_mart' === $rate->id && $weight > 5) {
            unset($rates[$key]);
        }

        if ('bf_seven_eleven' === $rate->id && $weight > 5) {
            unset($rates[$key]);
        }

        if ('bf_hi_life' === $rate->id && $weight > 5) {
            unset($rates[$key]);
        }

        if ($fee_logistics_data[$rate->id]['enabled_free_logistics'] === 'yes' && $total >= $fee_logistics_data[$rate->id]['free_logistics_price']) {
            if (isset($rates[$key])) {
                $rates[$key]->cost = 0;
            }
        }
    }
    return $rates;
}


add_action('woocommerce_checkout_process', 'checkout_field_process');

function checkout_field_process($a)
{
    global $woocommerce;
    $need_shipping = $woocommerce->cart->needs_shipping();
    $shipping_method = $woocommerce->session->get('chosen_shipping_methods');
    if (!$need_shipping || empty($shipping_method)) {
        return;
    }

    if (in_array($shipping_method[0], ['bf_family_mart', 'bf_seven_eleven', 'bf_hi_life', 'bf_ok'])) {
        $boxful_cvs_store_id = isset($_COOKIE['boxful_cvs_store_id']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_id']) : '';
        $boxful_cvs_store_name = isset($_COOKIE['boxful_cvs_store_name']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_name']) : '';
        $boxful_cvs_store_address = isset($_COOKIE['boxful_cvs_store_address']) ? sanitize_text_field($_COOKIE['boxful_cvs_store_address']) : '';
        if (!$boxful_cvs_store_id || !$boxful_cvs_store_name || !$boxful_cvs_store_address) {
            wc_add_notice('請選擇取貨門市', 'error');
        }
        $shipping_name = sanitize_text_field($_POST['billing_last_name']) . sanitize_text_field($_POST['billing_first_name']);
        $shipping_phone = sanitize_text_field($_POST['billing_phone']);
        if ($_POST['ship_to_different_address'] == '1') {
            $shipping_name = sanitize_text_field($_POST['shipping_last_name']) . sanitize_text_field($_POST['shipping_first_name']);
        }
        if ((!preg_match('/^([\x{4e00}-\x{9fff}\x{3400}-\x{4dbf}]{2,5}|[a-zA-Z]{4,10})$/u', $shipping_name))) {
            wc_add_notice('收件人姓名必須為中文2~5個字或英文4~10個字', 'error');
        }
        if (!preg_match('/^09[0-9]{8}$/', $shipping_phone)) {
            wc_add_notice('收件人電話請輸入手機號碼共10碼', 'error');
        }
        add_filter('woocommerce_checkout_fields', 'cvs_method_field_handle', 10000, 1);
    }
}

function cvs_method_field_handle($fields) {
    $fields['billing']['billing_country']['required']   = false;
    $fields['billing']['billing_address_1']['required'] = false;
    $fields['billing']['billing_address_2']['required'] = false;
    $fields['billing']['billing_city']['required']      = false;
    $fields['billing']['billing_state']['required']     = false;
    $fields['billing']['billing_postcode']['required']  = false;

    $fields['shipping']['shipping_country']['required']   = false;
    $fields['shipping']['shipping_address_1']['required'] = false;
    $fields['shipping']['shipping_address_2']['required'] = false;
    $fields['shipping']['shipping_city']['required']      = false;
    $fields['shipping']['shipping_state']['required']     = false;
    $fields['shipping']['shipping_postcode']['required']  = false;
    return $fields;
}

add_action('woocommerce_after_checkout_form', 'hiddenShippingField');
   
function hiddenShippingField($available_gateways) {
    global $woocommerce;
    $need_shipping = $woocommerce->cart->needs_shipping();
    $shipping_method = $woocommerce->session->get('chosen_shipping_methods');
    if (!$need_shipping || empty($shipping_method)) {
        return;
    }
    $choose_logistics_id = $shipping_method[0];
    if (in_array($choose_logistics_id, ['bf_seven_eleven', 'bf_hi_life', 'bf_family_mart'])) {
        wc_enqueue_js( "
            $( document ).ready(function() {
                let c_handleFieldList = ['#billing_country_field','#billing_address_1_field','#billing_address_2_field','#billing_city_field','#billing_state_field','#billing_country_field','#billing_postcode_field','#shipping_country_field','#shipping_address_1_field','#shipping_address_2_field','#shipping_city_field','#shipping_state_field','#shipping_country_field','#shipping_postcode_field'];
                c_handleFieldList.forEach(field => {
                    try {
                        $(field).hide(); 
                    } catch (e) {
                        console.log(e)
                    }
                })
            });
        ");
    }

    wc_enqueue_js("
        let cvsList = ['bf_seven_eleven', 'bf_hi_life', 'bf_family_mart'];
        let handleFieldList = ['#billing_country_field','#billing_address_1_field','#billing_address_2_field','#billing_city_field','#billing_state_field','#billing_country_field','#billing_postcode_field','#shipping_country_field','#shipping_address_1_field','#shipping_address_2_field','#shipping_city_field','#shipping_state_field','#shipping_country_field','#shipping_postcode_field'];
        let action = 'hidden';
        $('form.checkout').on('change','input[name^=\"shipping_method\"]',function() {
            var val = $(this).val();
            if(cvsList.includes(val)){
                action = 'hidden'
            }else{
                action = 'show'
            }
            handleFieldList.forEach(field => {
                try {
                    if(action === 'show'){
                        $(field).show();

                    }else{
                        $(field).hide();
                    }
                } catch (e) {
                    console.log(e)
                }
            })

        })
    ");

}



new UserShippingMethodController();