<?php

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

class AIEO_TRS_Zone_Admin {

    public static function register() {
        add_action('wp_ajax_aieo_trs_list',        array(__CLASS__, 'ajax_list'));
        add_action('wp_ajax_aieo_trs_save',        array(__CLASS__, 'ajax_save'));
        add_action('wp_ajax_aieo_trs_delete',      array(__CLASS__, 'ajax_delete'));
        add_action('wp_ajax_aieo_trs_reorder',     array(__CLASS__, 'ajax_reorder'));
        add_action('wp_ajax_aieo_trs_csv_export',  array(__CLASS__, 'ajax_csv_export'));
        add_action('wp_ajax_aieo_trs_csv_import',  array(__CLASS__, 'ajax_csv_import'));
        add_action('wp_ajax_aieo_trs_flip_method', array(__CLASS__, 'ajax_flip_method'));
    }

    private static function gate() {
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error(array('message' => 'permission_denied'), 403);
        }
        check_ajax_referer('aieo_trs_admin', 'nonce');
    }

    public static function ajax_list() {
        self::gate();
        $instance_id = (int) (sanitize_text_field( wp_unslash( $_REQUEST['instance_id'] ) ) ?? 0);
        if ($instance_id <= 0) {
            wp_send_json_success(array('rules' => array(), 'classes' => self::shipping_classes()));
        }
        $rows = AIEO_TRS_Rules::get_for_instance($instance_id);
        wp_send_json_success(array(
            'rules'   => $rows,
            'classes' => self::shipping_classes(),
        ));
    }

    public static function ajax_save() {
        self::gate();
        $payload = isset($_POST['rule']) && is_array( wp_unslash( $_POST['rule'] ) ) ? wp_unslash($_POST['rule']) : array();
        $check = AIEO_TRS_Validator::validate($payload);
        if (empty($check['ok'])) {
            wp_send_json_error(array('errors' => $check['errors']), 422);
        }
        $clean = $check['data'];

        $rule_id = (int) (sanitize_text_field( wp_unslash( $_POST['rule_id'] ) ) ?? 0);
        if ($rule_id > 0) {
            $r = AIEO_TRS_Rules::update($rule_id, $clean);
            if (empty($r['ok'])) { wp_send_json_error(array('errors' => array($r['error'] ?? 'update failed'))); }
            wp_send_json_success(array('id' => $rule_id, 'updated' => true));
        }
        $r = AIEO_TRS_Rules::create($clean);
        if (empty($r['ok'])) { wp_send_json_error(array('errors' => array($r['error'] ?? 'create failed'))); }
        wp_send_json_success(array('id' => (int) $r['id'], 'created' => true));
    }

    public static function ajax_delete() {
        self::gate();
        $rule_id = (int) (sanitize_text_field( wp_unslash( $_POST['rule_id'] ) ) ?? 0);
        if ($rule_id <= 0) { wp_send_json_error(array('message' => 'bad_id'), 400); }
        $ok = AIEO_TRS_Rules::delete($rule_id);
        wp_send_json_success(array('deleted' => (bool) $ok));
    }

    public static function ajax_reorder() {
        self::gate();
        
        
        
        
        $ids = isset($_POST['ids']) ? array_map('intval', (array) wp_unslash($_POST['ids'])) : array();
        $ids = array_values(array_filter($ids));
        $n = AIEO_TRS_Rules::reorder($ids);
        wp_send_json_success(array('reordered' => (int) $n));
    }

    public static function ajax_csv_export() {
        self::gate();
        $instance_id = isset($_REQUEST['instance_id']) && $_REQUEST['instance_id'] !== ''
            ? (int) $_REQUEST['instance_id']
            : null;
        $csv = AIEO_TRS_CSV::export($instance_id);
        nocache_headers();
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="aieo-shipping-rates-' . gmdate('Ymd-His') . '.csv"');
        echo $csv; 
        exit;
    }

    public static function ajax_csv_import() {
        self::gate();
        if (empty($_FILES['file']) || !is_array($_FILES['file'])) {
            wp_send_json_error(array('message' => 'no_file'), 400);
        }
        if ((int) $_FILES['file']['size'] > 2 * 1024 * 1024) { 
            wp_send_json_error(array('message' => 'file_too_large'), 413);
        }
        $tmp = (string) $_FILES['file']['tmp_name']; 
        if (!is_uploaded_file($tmp)) {
            wp_send_json_error(array('message' => 'bad_upload'), 400);
        }
        $body = file_get_contents($tmp);
        $default_instance = (int) (sanitize_text_field( wp_unslash( $_POST['instance_id'] ) ) ?? 0);
        $r = AIEO_TRS_CSV::import((string) $body, $default_instance);
        if (empty($r['ok'])) {
            wp_send_json_error($r, 422);
        }
        wp_send_json_success($r);
    }

    
    public static function ajax_flip_method() {
        self::gate();
        global $wpdb;
        $instance_id = (int) (sanitize_text_field( wp_unslash( $_POST['instance_id'] ) ) ?? 0);
        $target      = (string) (sanitize_text_field( wp_unslash( $_POST['target'] ) ) ?? '');
        if ($instance_id <= 0) {
            wp_send_json_error(array('message' => 'bad_instance'), 400);
        }
        if (!in_array($target, array('table_rate', 'aieo_table_rate'), true)) {
            wp_send_json_error(array('message' => 'bad_target'), 400);
        }

        $table = $wpdb->prefix . 'woocommerce_shipping_zone_methods';
        $current = $wpdb->get_row(
            $wpdb->prepare("SELECT zone_id, method_id FROM {$table} WHERE instance_id = %d LIMIT 1", $instance_id),
            ARRAY_A
        );
        if (!$current) {
            wp_send_json_error(array('message' => 'instance_not_found'), 404);
        }
        $previous = (string) $current['method_id'];
        if (!in_array($previous, array('table_rate', 'aieo_table_rate'), true)) {
            wp_send_json_error(array('message' => 'not_a_table_rate_instance'), 400);
        }
        if ($previous === $target) {
            wp_send_json_success(array('changed' => false, 'method_id' => $target));
        }

        
        
        
        self::copy_instance_settings($previous, $target, $instance_id);

        $r = $wpdb->update(
            $table,
            array('method_id' => $target),
            array('instance_id' => $instance_id),
            array('%s'),
            array('%d')
        );
        if ($r === false) {
            wp_send_json_error(array('message' => 'update_failed: ' . $wpdb->last_error), 500);
        }
        
        if (class_exists('WC_Cache_Helper') && method_exists('WC_Cache_Helper', 'get_transient_version')) {
            WC_Cache_Helper::get_transient_version('shipping', true);
        }
        if (class_exists('AIEO_Runtime_TRS_Cache') && method_exists('AIEO_Runtime_TRS_Cache', 'flush_request_cache')) {
            AIEO_Runtime_TRS_Cache::flush_request_cache();
        }
        do_action('aieo_trs_method_flipped', $instance_id, $target, $previous);
        wp_send_json_success(array(
            'changed'   => true,
            'method_id' => $target,
            'previous'  => $previous,
        ));
    }

    
    private static function copy_instance_settings($from_method_id, $to_method_id, $instance_id) {
        $from_key = sprintf('woocommerce_%s_%d_settings', $from_method_id, (int) $instance_id);
        $to_key   = sprintf('woocommerce_%s_%d_settings', $to_method_id,   (int) $instance_id);
        $src = get_option($from_key, array());
        $dst = get_option($to_key,   array());
        if (!is_array($src)) { $src = array(); }
        if (!is_array($dst)) { $dst = array(); }

        
        $carry = array('title', 'tax_status', 'enabled');
        foreach ($carry as $k) {
            $src_val = isset($src[$k]) ? $src[$k] : null;
            if ($src_val === null || $src_val === '') { continue; }
            
            
            $dst_val = isset($dst[$k]) ? $dst[$k] : null;
            if ($dst_val === null || $dst_val === '') {
                $dst[$k] = $src_val;
            }
        }
        
        
        if (!isset($dst['enabled']) || $dst['enabled'] === '') {
            $dst['enabled'] = 'yes';
        }
        update_option($to_key, $dst, false);
    }

    
    public static function shipping_classes() {
        $out = array(
            array('slug' => '',   'name' => __('Any class', 'ai-eshop-optimizer')),
            array('slug' => '0',  'name' => __('No shipping class', 'ai-eshop-optimizer')),
        );
        if (!class_exists('WC_Shipping')) { return $out; }
        $classes = WC_Shipping::instance()->get_shipping_classes();
        if (!is_array($classes)) { return $out; }
        foreach ($classes as $c) {
            $out[] = array(
                'slug' => (string) $c->slug,
                'name' => (string) $c->name,
            );
        }
        return $out;
    }
}
