<?php
namespace WTC_CHECKOUT\Modules\Forms\Frontend;
defined('ABSPATH') || exit;
class MyAccountViewModel {
    private $field_layouts;
    private $field_priorities;
    public function __construct() {
        $this->field_layouts = get_option('wtc_field_layouts', array());
        $this->field_priorities = get_option('wtc_field_priorities', array());
        add_filter('woocommerce_billing_fields', array($this, 'customize_billing_fields'), 20);
        add_filter('woocommerce_shipping_fields', array($this, 'customize_shipping_fields'), 20);
        add_action('woocommerce_after_save_address_validation', array($this, 'validate_tckn_my_account'), 10, 2);
        add_action('wp_ajax_wtc_get_cities', array($this, 'ajax_get_cities'));
        add_action('wp_ajax_wtc_get_neighborhoods', array($this, 'ajax_get_neighborhoods'));
        add_action('woocommerce_before_edit_account_address_form', array($this, 'add_myaccount_nonce_field'));
    }
    public function customize_billing_fields($fields) {
        if (!is_account_page() || !is_wc_endpoint_url('edit-address')) {
            return $fields;
        }
        $user_id = get_current_user_id();
        $default_invoice_type = get_user_meta($user_id, 'billing_invoice_type', true) ?: 'individual';
        $saved_state_code = get_user_meta($user_id, 'billing_state', true);
        $is_prefilled = !empty($saved_state_code);
        $state_code = $is_prefilled ? $saved_state_code : WC()->countries->get_base_state();
        $city = get_user_meta($user_id, 'billing_city', true);
        $billing_custom_fields = array(
            'billing_invoice_type' => array(
                'type' => 'select',
                'label' => __('Fatura Tipi', 'wtc-checkout'),
                'required' => true,
                'class' => array('select2'),
                'options' => array(
                    'individual' => __('Bireysel', 'wtc-checkout'),
                    'corporate' => __('Kurumsal', 'wtc-checkout')
                ),
                'default' => $default_invoice_type
            ),
            'billing_first_name' => array(
                'label' => __('Ad', 'wtc-checkout'),
                'required' => true,
                'class' => array('individual-field'),
                'autocomplete' => 'given-name'
            ),
            'billing_last_name' => array(
                'label' => __('Soyad', 'wtc-checkout'),
                'required' => true,
                'class' => array('individual-field'),
                'autocomplete' => 'family-name'
            ),
            'billing_tckn' => array(
                'label' => __('TC Kimlik No', 'wtc-checkout'),
                'required' => get_option('wtc_tckn_required', 'yes') === 'yes',
                'class' => array('individual-field'),
                'maxlength' => 11,
                'minlength' => 11,
                'custom_attributes' => array(
                    'pattern' => '[0-9]*'
                )
            ),
            'billing_company' => array(
                'label' => __('Firma Adı', 'wtc-checkout'),
                'required' => true,
                'class' => array('corporate-field'),
                'autocomplete' => 'organization'
            ),
            'billing_tax_number' => array(
                'label' => __('Vergi No', 'wtc-checkout'),
                'required' => true,
                'class' => array('corporate-field'),
                'maxlength' => 11,
                'minlength' => 10,
                'custom_attributes' => array(
                    'pattern' => '[0-9]*'
                )
            ),
            'billing_tax_office' => array(
                'label' => __('Vergi Dairesi', 'wtc-checkout'),
                'required' => true,
                'class' => array('corporate-field')
            ),
            'billing_country' => array(
                'type' => 'select',
                'label' => __('Ülke', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => array('TR' => __('Türkiye', 'wtc-checkout')),
                'autocomplete' => 'country'    
            ),
            'billing_state' => array(
                'type' => 'select',
                'label' => __('İl', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => WC()->countries->get_states('TR'),
                'autocomplete' => 'address-level1',
                'custom_attributes' => array(
                    'data-prefilled' => $is_prefilled ? 'true' : 'false'
                )           
            ),
            'billing_city' => array(
                'type' => 'select',
                'label' => __('İlçe', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => $this->get_cities($state_code),
                'autocomplete' => 'address-level2'
            ),
            'billing_address_1' => array(
                'type' => 'select',
                'label' => __('Mahalle', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => $this->get_neighborhoods($state_code, $city),
                'autocomplete' => 'address-line1'
            ),
            'billing_address_2' => array(
                'label' => __('Adres', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field'),
                'autocomplete' => 'address-line2',
                'placeholder' => __('Cadde, sokak, bina, daire no bilgilerinizi giriniz', 'wtc-checkout')
            ),
            'billing_postcode' => array(
                'label' => __('Posta Kodu', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field'),
                'custom_attributes' => array(
                    'readonly' => 'readonly'
                )
            ),
            'billing_phone' => array(
                'type' => 'tel',
                'label' => __('Telefon', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field'),
                'maxlength' => 19,
                'autocomplete' => 'tel'
            ),
        );
        $is_post_request = isset($_SERVER['REQUEST_METHOD']) && strtoupper(sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD']))) === 'POST';
        $invoice_type_posted = '';
        if ($is_post_request && isset($_POST['billing_invoice_type'])) {
            $invoice_type_posted = sanitize_text_field(wp_unslash($_POST['billing_invoice_type']));
        }
        if ($invoice_type_posted === 'individual') {
            unset($billing_custom_fields['billing_company'], $billing_custom_fields['billing_tax_office'], $billing_custom_fields['billing_tax_number']);
        } elseif ($invoice_type_posted === 'corporate') {
            unset($billing_custom_fields['billing_tckn']);
            if (get_option('wtc_corporate_names_required', 'no') !== 'yes') {
                unset($billing_custom_fields['billing_first_name'], $billing_custom_fields['billing_last_name']);
            }
        }
        $this->_apply_field_customizations($billing_custom_fields);
        return $billing_custom_fields;
    }
    public function customize_shipping_fields($fields) {
        if (!is_account_page() || !is_wc_endpoint_url('edit-address')) {
            return $fields;
        }
        $user_id = get_current_user_id();
        $saved_state_code = get_user_meta($user_id, 'shipping_state', true);
        $is_prefilled = !empty($saved_state_code);
        $state_code = $is_prefilled ? $saved_state_code : WC()->countries->get_base_state();
        $city = get_user_meta($user_id, 'shipping_city', true);
        $shipping_custom_fields = array(
            'shipping_first_name' => array(
                'label' => __('Ad', 'wtc-checkout'),
                'required' => true,
                'class' => array('individual-field'),
                'autocomplete' => 'given-name'
            ),
            'shipping_last_name' => array(
                'label' => __('Soyad', 'wtc-checkout'),
                'required' => true,
                'class' => array('individual-field'),
                'autocomplete' => 'family-name'
            ),
            'shipping_company' => array(
                'label' => __('Firma Adı', 'wtc-checkout'),
                'required' => false,
                'class' => array('corporate-field'),
                'autocomplete' => 'organization'
            ),          
            'shipping_country' => array(
                'type' => 'select',
                'label' => __('Ülke', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => array('TR' => __('Türkiye', 'wtc-checkout')),
                'autocomplete' => 'country'    
            ),
            'shipping_state' => array(
                'type' => 'select',
                'label' => __('İl', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => WC()->countries->get_states('TR'),
                'autocomplete' => 'address-level1',
                'custom_attributes' => array(
                    'data-prefilled' => $is_prefilled ? 'true' : 'false'
                )           
            ),
            'shipping_city' => array(
                'type' => 'select',
                'label' => __('İlçe', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => $this->get_cities($state_code),
                'autocomplete' => 'address-level2'
            ),
            'shipping_address_1' => array(
                'type' => 'select',
                'label' => __('Mahalle', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field', 'select2'),
                'options' => $this->get_neighborhoods($state_code, $city),
                'autocomplete' => 'address-line1'
            ),
            'shipping_address_2' => array(
                'label' => __('Adres', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field'),
                'autocomplete' => 'address-line2',
                'placeholder' => __('Cadde, sokak, bina, daire no bilgilerinizi giriniz', 'wtc-checkout')
            ),
            'shipping_postcode' => array(
                'label' => __('Posta Kodu', 'wtc-checkout'),
                'required' => true,
                'class' => array('address-field'),
                'custom_attributes' => array(
                    'readonly' => 'readonly'
                )
            ),
            'shipping_name' => array(
                'label' => __('Adres Başlığı', 'wtc-checkout'),
                'required' => false,
                'class' => array('address-field'),
                'placeholder' => __('Örnek: Evim, İş yerim vb.', 'wtc-checkout')
            ), 
        );
        $this->_apply_field_customizations($shipping_custom_fields);
        return $shipping_custom_fields;
    }
    public function validate_tckn_my_account($user_id, $load_address) {
        if ($load_address !== 'billing') {
            return;
        }
        if (!isset($_POST['_wtc_myaccount_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wtc_myaccount_nonce'])), 'wtc_myaccount_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));
    }
    private function _apply_field_customizations(&$fields) {
        foreach ($fields as $key => &$field) {
            if (isset($this->field_priorities[$key])) {
                $field['priority'] = $this->field_priorities[$key];
            }
            $existing_classes = isset($field['class']) ? (array)$field['class'] : array();
            $existing_classes = array_filter($existing_classes, function($class) {
                return strpos($class, 'wtc-') !== 0;
            });
            if (isset($this->field_layouts[$key])) {
                $existing_classes[] = $this->field_layouts[$key];
            }
            $field['class'] = array_unique($existing_classes);
        }
    }
    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_file = WTC_PLUGIN_DIR . '/data/districts.php';
        if (!file_exists($districts_file)) return $placeholder;
        $districts = include $districts_file;
        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 _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');
        }
    }
    public function add_myaccount_nonce_field() {
        echo '<input type="hidden" name="_wtc_myaccount_nonce" value="' . esc_attr(wp_create_nonce('wtc_myaccount_action')) . '">';
    }
}