<?php
namespace WTC_CHECKOUT\Modules\Forms\Frontend;
defined('ABSPATH') || exit;
class CheckoutViewModel {
    private $default_classes;
    public function __construct() {
        add_filter('woocommerce_checkout_fields', array($this, 'customize_checkout_fields'));
        add_filter('woocommerce_checkout_fields', array($this, 'custom_fields_woocommerce'));
        add_filter('woocommerce_default_address_fields', array($this, 'customize_default_address_fields'));
        add_filter('woocommerce_billing_fields', array($this, 'customize_billing_fields'));
        add_filter('woocommerce_order_get_billing_first_name', array($this, 'override_first_name'), 10, 2);
        add_filter('woocommerce_order_get_billing_last_name', array($this, 'override_last_name'), 10, 2);
        add_action('woocommerce_checkout_process', array($this, 'validate_tckn'));
        add_action('woocommerce_checkout_order_processed', array($this, 'save_customer_meta_data'), 10, 3);
        add_action('wp_ajax_wtc_get_cities', array($this, 'ajax_get_cities'));
        add_action('wp_ajax_nopriv_wtc_get_cities', array($this, 'ajax_get_cities'));
        add_action('wp_ajax_wtc_get_neighborhoods', array($this, 'ajax_get_neighborhoods'));
        add_action('wp_ajax_nopriv_wtc_get_neighborhoods', array($this, 'ajax_get_neighborhoods'));
        add_action('woocommerce_checkout_before_customer_details', array($this, 'add_checkout_nonce_field'));
    }
    public function override_first_name($value, $order) {
        if (get_option('wtc_corporate_names_required', 'no') === 'yes') {
            return $value;
        }
        $parts = $this->_get_company_name_parts_from_order($order);
        return $parts ? ($parts[0] ?? '') : $value;
    }
    public function override_last_name($value, $order) {
        if (get_option('wtc_corporate_names_required', 'no') === 'yes') {
            return $value;
        }
        $parts = $this->_get_company_name_parts_from_order($order);
        if ($parts) {
            if (count($parts) > 1) {
                array_shift($parts);
                return implode(' ', $parts);
            }
            return ' '; 
        }
        return $value;
    }
    public function customize_checkout_fields($fields) {
        $field_layouts = get_option('wtc_field_layouts', array());
        if (isset($fields['billing'])) {
            $this->_apply_field_customizations($fields['billing'], $field_layouts);
        }
        if (isset($fields['shipping'])) {
            $this->_apply_field_customizations($fields['shipping'], $field_layouts);
        }
        return $fields;
    }
    public function customize_default_address_fields($fields) {
        $field_priorities = get_option('wtc_field_priorities', array());
        foreach ($fields as $key => &$field) {
            $billing_key = 'billing_' . $key;
            $shipping_key = 'shipping_' . $key;
            if (isset($field_priorities[$billing_key])) {
                $field['priority'] = $field_priorities[$billing_key];
            } elseif (isset($field_priorities[$shipping_key])) {
                $field['priority'] = $field_priorities[$shipping_key];
            }
        }
        return $fields;
    }
    public function customize_billing_fields($fields) {
        $field_priorities = get_option('wtc_field_priorities', array());
        foreach ($fields as $key => &$field) {
            if (isset($field_priorities[$key])) {
                $field['priority'] = $field_priorities[$key];
            }
        }
        return $fields;
    }
    public function custom_fields_woocommerce($fields) {
        $field_layouts = get_option('wtc_field_layouts', array());
        $field_priorities = get_option('wtc_field_priorities', array());
        $default_invoice_type = $this->_get_checkout_value('invoice_type', 'billing', 'individual');
        $selected_billing_country = $this->_get_checkout_value('country', 'billing', 'TR');
        $selected_billing_state = $this->_get_checkout_value('state', 'billing');
        $selected_billing_city = $this->_get_checkout_value('city', 'billing');
        $selected_billing_address_1 = $this->_get_checkout_value('address_1', 'billing');
        $selected_shipping_country = $this->_get_checkout_value('country', 'shipping', 'TR');
        $selected_shipping_state = $this->_get_checkout_value('state', 'shipping');
        $selected_shipping_city = $this->_get_checkout_value('city', 'shipping');
        $selected_shipping_address_1 = $this->_get_checkout_value('address_1', 'shipping');
        $billing_custom_fields = $this->_get_billing_field_definitions($default_invoice_type, $selected_billing_country, $selected_billing_state, $selected_billing_city, $selected_billing_address_1);
        $shipping_custom_fields = $this->_get_shipping_field_definitions($selected_shipping_country, $selected_shipping_state, $selected_shipping_city, $selected_shipping_address_1);
        $this->_manage_order_notes_field($fields);
        $this->_apply_field_customizations($billing_custom_fields, $field_layouts, $field_priorities);
        $this->_apply_field_customizations($shipping_custom_fields, $field_layouts, $field_priorities);
        $fields['billing'] = array_merge($fields['billing'] ?? [], $billing_custom_fields);
        $fields['shipping'] = array_merge($fields['shipping'] ?? [], $shipping_custom_fields);
        if (!isset($_POST['_wtc_checkout_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_checkout_nonce'])), 'wtc_checkout_action')) {
            $invoice_type_posted = '';
        } else {
            $invoice_type_posted = isset($_POST['billing_invoice_type']) ? sanitize_text_field(wp_unslash($_POST['billing_invoice_type'])) : '';
        }
        if ($invoice_type_posted === 'individual') {
            unset($fields['billing']['billing_company'], $fields['billing']['billing_tax_office'], $fields['billing']['billing_tax_number']);
        } elseif ($invoice_type_posted === 'corporate') {
            unset($fields['billing']['billing_tckn']);
            if (get_option('wtc_corporate_names_required', 'no') !== 'yes') {
                unset($fields['billing']['billing_first_name'], $fields['billing']['billing_last_name']);
            }
        }
        return $fields;
    }
    public function save_customer_meta_data($order_id, $posted_data, $order) {
        $user_id = $order->get_customer_id();
        if (!$user_id) {
            return;
        }
        if (!isset($_POST['_wtc_checkout_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_checkout_nonce'])), 'wtc_checkout_action')) {
            return;
        }
        $fields_to_save = [
            'billing_invoice_type', 'billing_first_name', 'billing_last_name', 'billing_tckn',
            'billing_company', 'billing_tax_number', 'billing_tax_office', 'billing_country',
            'billing_state', 'billing_city', 'billing_address_1', 'billing_address_2',
            'billing_postcode', 'billing_phone', 'shipping_first_name', 'shipping_last_name',
            'shipping_company', 'shipping_country', 'shipping_state', 'shipping_city',
            'shipping_address_1', 'shipping_address_2', 'shipping_postcode', 'shipping_name'
        ];
        foreach ($fields_to_save as $field_key) {
            if (isset($_POST[$field_key])) {
                update_user_meta($user_id, $field_key, sanitize_text_field(wp_unslash($_POST[$field_key])));
            }
        }
    }
    public function validate_tckn() {
        if (!isset($_POST['_wtc_checkout_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_checkout_nonce'])), 'wtc_checkout_action')) {
            return;
        }
        $billing_invoice_type = isset($_POST['billing_invoice_type']) ? sanitize_text_field(wp_unslash($_POST['billing_invoice_type'])) : '';
        if (empty($billing_invoice_type)) {
            return;
        }
        
        if ($billing_invoice_type === 'individual') {
            if (get_option('wtc_tckn_validation_enabled', 'no') !== 'yes') {
                return;
            }
            $tckn = sanitize_text_field(isset($_POST['billing_tckn']) ? wp_unslash($_POST['billing_tckn']) : '');
            
            if (!empty($tckn) && !$this->is_valid_tckn($tckn)) {
                wc_add_notice(__('TC Kimlik numarası geçersiz.', 'wtc-checkout'), 'error');
            }
        } elseif ($billing_invoice_type === 'corporate') {
            if (get_option('wtc_corporate_tax_validation_enabled', 'no') !== 'yes') {
                return;
            }
            $tax_number = sanitize_text_field(isset($_POST['billing_tax_number']) ? wp_unslash($_POST['billing_tax_number']) : '');
            $length = mb_strlen($tax_number);

            if (!empty($tax_number)) {
                if ($length !== 10 && $length !== 11) {
                    wc_add_notice(__('Vergi numarası 10 veya 11 haneli olmalıdır.', 'wtc-checkout'), 'error');
                } elseif ($length === 11) {
                    if (!$this->is_valid_tckn($tax_number)) {
                        wc_add_notice(__('Girdiğiniz 11 haneli Vergi No (TC Kimlik Numarası) geçersiz.', 'wtc-checkout'), 'error');
                    }
                } elseif ($length === 10) {
                    if (!$this->is_valid_tax_number($tax_number)) {
                        wc_add_notice(__('Girdiğiniz 10 haneli Vergi Numarası geçersiz.', 'wtc-checkout'), 'error');
                    }
                }
            }
        }
    }
    public function ajax_get_cities() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wtc-nonce')) {
            wp_die('Güvenlik kontrolü başarısız');
        }
        $state_code = '';
        if (isset($_POST['state_code'])) {
            $state_code = sanitize_text_field(wp_unslash($_POST['state_code']));
        }
        if (empty($state_code)) {
            wp_send_json_error('İl kodu gerekli');
        }
        wp_send_json_success($this->get_cities($state_code));
    }
    public function ajax_get_neighborhoods() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wtc-nonce')) {
            wp_die('Güvenlik kontrolü başarısız');
        }
        $state_code = '';
        $city_name = '';
        if (isset($_POST['state_code'])) {
            $state_code = sanitize_text_field(wp_unslash($_POST['state_code']));
        }
        if (isset($_POST['city'])) {
            $city_name = sanitize_text_field(wp_unslash($_POST['city']));
        }
        if (empty($state_code) || empty($city_name)) {
            wp_send_json_error('İl kodu ve ilçe adı gerekli');
        }
        wp_send_json_success($this->get_neighborhoods($state_code, $city_name));
    }
    public function add_checkout_nonce_field() {
        echo '<input type="hidden" name="_wtc_checkout_nonce" value="' . esc_attr(wp_create_nonce('wtc_checkout_action')) . '">';
    }
    private function _apply_field_customizations(&$fields, $layouts, $priorities = []) {
        foreach ($fields as $key => &$field) {
            if (!empty($priorities) && isset($priorities[$key])) {
                $field['priority'] = $priorities[$key];
            }
            $existing_classes = array_filter((array)($field['class'] ?? []), function($class) {
                return strpos($class, 'wtc-') !== 0;
            });
            if (isset($layouts[$key])) {
                $existing_classes[] = $layouts[$key];
            }
            $field['class'] = array_unique($existing_classes);
        }
    }
    private function _get_checkout_value($field_key, $prefix = 'billing', $default = '') {
        $meta_key = $prefix . '_' . $field_key;
        $value = '';
        if (is_user_logged_in()) {
            $value = get_user_meta(get_current_user_id(), $meta_key, true);
        } else {
            $value = WC()->checkout()->get_value($meta_key);
            if (!$value) {
                $customer_method = "get_{$meta_key}";
                if (method_exists(WC()->customer, $customer_method)) {
                    $value = WC()->customer->$customer_method();
                }
            }
        }
        return !empty($value) ? $value : $default;
    }
    private function _manage_order_notes_field(&$fields) {
        $hide_order_notes = get_option('wtc_hide_order_notes', 'no');
        if ($hide_order_notes === 'yes') {
            unset($fields['order']['order_comments']);
            return;
        }
        add_action('woocommerce_before_order_notes', function() {
            echo '<div class="form-row wtc-full"><label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox"><input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox" id="toggle-order-notes"> <span>' . esc_html__('Sipariş notu eklemek istiyorum', 'wtc-checkout') . '</span></label></div>';
        });
        $fields['order']['order_comments'] = [
            'class' => ['notes-field', 'wtc-full'],
            'type'  => 'textarea',
        ];
    }
    private function _verify_ajax_nonce() {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'wtc-nonce')) {
            wp_die('Güvenlik kontrolü başarısız');
        }
    }
    private function _get_company_name_parts_from_order($order) {
        if (!is_checkout() || $order->get_meta('_billing_invoice_type') !== 'corporate') {
            return null;
        }
        $company = trim($order->get_billing_company());
        return preg_split('/\s+/', $company, -1, PREG_SPLIT_NO_EMPTY);
    }
    private function is_valid_tckn($tckn) {
        if (!preg_match('/^[1-9][0-9]{10}$/', $tckn)) return false;
        $odd_sum = $tckn[0] + $tckn[2] + $tckn[4] + $tckn[6] + $tckn[8];
        $even_sum = $tckn[1] + $tckn[3] + $tckn[5] + $tckn[7];
        if ((($odd_sum * 7) - $even_sum) % 10 != $tckn[9]) return false;
        $total_sum = 0;
        for ($i = 0; $i < 10; $i++) $total_sum += $tckn[$i];
        if ($total_sum % 10 != $tckn[10]) return false;
        return true;
    }
    private function is_valid_tax_number($tax_number) {
        if (!preg_match('/^[0-9]{10}$/', $tax_number)) return false;

        $sum = 0;
        for ($i = 0; $i < 9; $i++) {
            $p = ($tax_number[$i] + 10 - ($i + 1)) % 10;
            if ($p == 9) {
                $q = 9;
            } else {
                $q = ($p * pow(2, 10 - ($i + 1))) % 9;
            }
            $sum += $q;
        }

        $c1 = (10 - ($sum % 10)) % 10;

        return $c1 == $tax_number[9];
    }
    private function get_cities($state_code) {
        $placeholder = ['' => __('İlçe seçiniz', 'wtc-checkout')];
        if (empty($state_code)) return $placeholder;
        $districts = include WTC_PLUGIN_DIR . '/data/districts.php';
        if (isset($districts[$state_code])) {
            return $placeholder + array_combine($districts[$state_code], $districts[$state_code]);
        }
        return $placeholder;
    }
    private function get_neighborhoods($state_code, $city_name) {
        $placeholder = ['' => __('Mahalle seçiniz', 'wtc-checkout')];
        if (empty($state_code) || empty($city_name)) return $placeholder;
        $file_path = WTC_PLUGIN_DIR . '/data/neighborhoods/' . $state_code . '.php';
        if (!file_exists($file_path)) return $placeholder;
        $all_neighborhoods = include $file_path;
        if (isset($all_neighborhoods[$city_name])) {
            $neighborhoods = [];
            foreach ($all_neighborhoods[$city_name] as $data) {
                list($name, $postal_code) = explode(',', $data);
                $neighborhoods[$name] = $postal_code;
            }
            return $placeholder + $neighborhoods;
        }
        return $placeholder;
    }
    private function _get_billing_field_definitions($default_invoice_type, $country, $state, $city, $address_1) {
        $final_state = $state;
        if (empty($final_state)) {
            $final_state = WC()->countries->get_base_state();
        }
        return [
            'billing_invoice_type' => [
                'type' => 'select', 
                'label' => __('Fatura Tipi', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['select2'], 
                'options' => [
                    'individual' => __('Bireysel', 'wtc-checkout'), 
                    'corporate' => __('Kurumsal', 'wtc-checkout')
                ], 
                'default' => $default_invoice_type
            ],
            'billing_first_name' => [
                'label' => __('Ad', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['individual-field'],
                'autocomplete' => 'given-name'
            ],
            'billing_last_name' => [
                'label' => __('Soyad', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['individual-field'],
                'autocomplete' => 'family-name'
            ],
            'billing_tckn' => [
                'label' => __('TC Kimlik No', 'wtc-checkout'), 
                'required' => get_option('wtc_tckn_required', 'yes') === 'yes', 
                'class' => ['individual-field'], 
                'maxlength' => 11, 
                'minlength' => 11, 
                'custom_attributes' => [
                    'pattern' => '[0-9]*'
                    ]
            ],
            'billing_company' => [
                'label' => __('Firma Adı', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['corporate-field'],
                'autocomplete' => 'organization'
            ],
            'billing_tax_number' => [
                'label' => __('Vergi No', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['corporate-field'], 
                'maxlength' => 11, 
                'minlength' => 10, 
                'custom_attributes' => [
                    'pattern' => '[0-9]*'
                    ]
            ],
            'billing_tax_office' => [
                'label' => __('Vergi Dairesi', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['corporate-field']
            ],
            'billing_country' => [
                'type' => 'select', 
                'label' => __('Ülke', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => ['TR' => __('Türkiye', 'wtc-checkout')], 
                'default' => $country, 
                'autocomplete' => 'country'
            ],
            'billing_state' => [
                'type' => 'select', 
                'label' => __('İl', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => WC()->countries->get_states($country), 
                'default' => $state, 
                'autocomplete' => 'address-level1',
                'custom_attributes' => [
                    'data-prefilled' => !empty($state) ? 'true' : 'false'
                ]
            ],
            'billing_city' => [
                'type' => 'select', 
                'label' => __('İlçe', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => $this->get_cities($final_state),
                'default' => $city, 
                'autocomplete' => 'address-level2'
            ],
            'billing_address_1' => [
                'type' => 'select', 
                'label' => __('Mahalle', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => $this->get_neighborhoods($state, $city), 
                'default' => $address_1, 
                'autocomplete' => 'address-line1'
            ],
            'billing_address_2' => [
                'label' => __('Adres', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field'], 
                'autocomplete' => 'address-line2', 
                'placeholder' => __('Cadde, sokak, bina, daire no bilgilerinizi giriniz', 'wtc-checkout')
            ],
            'billing_postcode' => [
                'label' => __('Posta Kodu', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field'], 
                'custom_attributes' => [
                    'readonly' => 'readonly'
                    ]
            ],
            'billing_phone' => [
                'type' => 'tel', 
                'label' => __('Telefon', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field'], 
                'maxlength' => 19, 
                'autocomplete' => 'tel'
            ],
        ];
    }
    private function _get_shipping_field_definitions($country, $state, $city, $address_1) {
        $final_state = $state;
        if (empty($final_state)) {
            $final_state = WC()->countries->get_base_state();
        }
        return [
            'shipping_first_name' => [
                'label' => __('Ad', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['individual-field'],
                'autocomplete' => 'given-name'
            ],
            'shipping_last_name' => [ 
                'label' => __('Soyad', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['individual-field'],
                'autocomplete' => 'family-name'
            ],
            'shipping_company' => [
                'label' => __('Firma Adı', 'wtc-checkout'), 
                'required' => false, 
                'class' => ['corporate-field'],
                'autocomplete' => 'organization'
            ],
            'shipping_country' => [
                'type' => 'select', 
                'label' => __('Ülke', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => ['TR' => __('Türkiye', 'wtc-checkout')], 
                'default' => $country, 
                'autocomplete' => 'country'
            ],
            'shipping_state' => [
                'type' => 'select', 
                'label' => __('İl', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => WC()->countries->get_states($country), 
                'default' => $state, 
                'autocomplete' => 'address-level1',
                'custom_attributes' => [
                    'data-prefilled' => !empty($state) ? 'true' : 'false'
                ]
            ],
            'shipping_city' => [
                'type' => 'select', 
                'label' => __('İlçe', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => $this->get_cities($final_state),
                'default' => $city, 
                'autocomplete' => 'address-level2'
            ],
            'shipping_address_1' => [
                'type' => 'select', 
                'label' => __('Mahalle', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field', 'select2'], 
                'options' => $this->get_neighborhoods($state, $city), 
                'default' => $address_1, 
                'autocomplete' => 'address-line1'
            ],
            'shipping_address_2' => [
                'label' => __('Adres', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field'], 
                'autocomplete' => 'address-line2', 
                'placeholder' => __('Cadde, sokak, bina, daire no bilgilerinizi giriniz', 'wtc-checkout')
            ],
            'shipping_postcode' => [
                'label' => __('Posta Kodu', 'wtc-checkout'), 
                'required' => true, 
                'class' => ['address-field'], 
                'custom_attributes' => [
                    'readonly' => 'readonly'
                    ]
            ],
            'shipping_name' => [
                'label' => __('Adres Başlığı', 'wtc-checkout'), 
                'required' => false, 
                'class' => ['address-field'], 
                'placeholder' => __('Örnek: Evim, İş yerim vb.', 'wtc-checkout')
            ],
        ];
    }
}