<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_DMM_Phone_Orders extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_phone_orders';

    public function get_id()       { return 'phone_orders'; }
    public function get_label()    { return __('Phone Orders', 'ai-eshop-optimizer'); }
    public function get_priority() { return 80; }
    public function get_group()    { return 'checkout_handling'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_phone_orders_save', array($this, 'ajax_save'));

        $s = $this->get_settings();
        if ($s['enabled'] !== 'yes') { return; }

        
        
        
        add_filter('wc_order_attribution_origin_formatted_source', array($this, 'origin_phone_label'), 10, 2);

        if ($s['admin_checkbox'] === 'yes') {
            add_action('woocommerce_admin_order_data_after_billing_address', array($this, 'render_admin_checkbox'));
            add_action('woocommerce_process_shop_order_meta',                  array($this, 'save_admin_checkbox'));
            add_action('admin_enqueue_scripts',                                array($this, 'admin_styles'));
        }
        if ($s['user_search_by_phone'] === 'yes') {
            add_action('pre_user_query', array($this, 'allow_user_search_by_phone'));
        }
    }

    
    public static function is_phone_order($order) {
        if (!is_a($order, 'WC_Order')) { return false; }
        if ('yes' === (string) $order->get_meta('_phone_order')) { return true; }
        if ('admin' === (string) $order->get_meta('_wc_order_attribution_source_type')) { return true; }
        return false;
    }

    
    public function origin_phone_label($formatted, $source) {
        if ('Web admin' === $source || $source === __('Web admin', 'woocommerce')) {
            return 'Phone Orders';
        }
        return $formatted;
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        return array_merge(array(
            'enabled'               => 'yes',
            'admin_checkbox'        => 'yes',
            'user_search_by_phone'  => 'yes',
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        update_option(self::OPTION_KEY, array(
            'enabled'              => !empty($_POST['enabled']) ? 'yes' : 'no',
            'admin_checkbox'       => !empty($_POST['admin_checkbox']) ? 'yes' : 'no',
            'user_search_by_phone' => !empty($_POST['user_search_by_phone']) ? 'yes' : 'no',
        ), false);
        wp_send_json_success(array('message' => __('Phone orders settings saved.', 'ai-eshop-optimizer')));
    }

    public function render_admin_checkbox($order) {
        if (!is_a($order, 'WC_Order')) { return; }
        $val = $order->get_meta('_phone_order');
        echo '<p class="form-field form-field-wide">';
        echo '<label for="phone_order" class="checkbox" style="display:inline-flex;align-items:center;gap:6px;">';
        echo '<input type="checkbox" name="phone_order" id="phone_order" value="yes" ' . ($val === 'yes' ? 'checked' : '') . ' style="width:20px;height:20px;">';
        echo esc_html__('Phone Order', 'ai-eshop-optimizer');
        echo '</label></p>';
    }

    public function save_admin_checkbox($order_id) {
        $order = wc_get_order($order_id);
        if (!$order) { return; }
        $val = isset($_POST['phone_order']) ? 'yes' : 'no';
        $order->update_meta_data('_phone_order', $val);
        $order->save();
    }

    public function admin_styles($hook) {
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if ($screen && in_array($screen->id, array('shop_order', 'woocommerce_page_wc-orders'), true)) {
            wp_add_inline_style('woocommerce_admin_styles', '#phone_order{width:20px;height:20px;}');
        }
    }

    public function allow_user_search_by_phone($user_query) {
        if (empty($_REQUEST['phone'])) { return; }
        $phone = sanitize_text_field(wp_unslash($_REQUEST['phone']));
        if ($phone === '') { return; }
        $user_query->meta_query->relation   = 'OR';
        $user_query->meta_query->queries[]  = array(
            'key'     => 'billing_phone',
            'value'   => $phone,
            'compare' => 'LIKE',
        );
    }

    public function render_subtab() {
        $s = $this->get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Phone Orders', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Two small admin conveniences: a "Phone Order" checkbox on the order edit page (saved to `_phone_order` order meta), and the ability to search WP users by their billing phone number.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-po-form" class="aieo-dmm-form aieo-dmm-card"><table class="form-table">';
        echo '<tr><th>' . esc_html__('Enable', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="enabled" value="1" ' . checked($s['enabled'] === 'yes', true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('Phone-order checkbox on admin order page', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="admin_checkbox" value="1" ' . checked($s['admin_checkbox'] === 'yes', true, false) . '></label></td></tr>';
        echo '<tr><th>' . esc_html__('User search by billing phone', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="user_search_by_phone" value="1" ' . checked($s['user_search_by_phone'] === 'yes', true, false) . '> ' . esc_html__('Adds &?phone=… filter to wp-admin/users.php queries', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '</table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-po-save">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-po-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p></form>';
        echo '<script>(function(){var f=document.getElementById("aieo-dmm-po-form");var b=document.getElementById("aieo-dmm-po-save");var s=document.getElementById("aieo-dmm-po-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_phone_orders_save");fd.set("nonce","' . esc_js($nonce) . '");s.style.color="#646970";s.textContent="' . esc_js(__('Saving…', 'ai-eshop-optimizer')) . '";fetch("' . esc_js($ajax) . '",{method:"POST",credentials:"same-origin",body:fd}).then(function(r){return r.json();}).then(function(j){if(j&&j.success){s.style.color="#15803d";s.textContent=j.data.message;}else{s.style.color="#b91c1c";s.textContent=(j&&j.data&&j.data.message)||"' . esc_js(__('Save failed.', 'ai-eshop-optimizer')) . '";}});});})();</script>';
        echo '</div>';
    }
}
