<?php

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

class AIEO_DMM_Min_Order extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_dmm_min_order';

    public function get_id()       { return 'min_order'; }
    public function get_label()    { return __('Minimum Order', 'ai-eshop-optimizer'); }
    public function get_priority() { return 50; }
    public function get_group()    { return 'checkout_handling'; }

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

        
        
        
        
        
        if (defined('AIEO_RUNTIME_OWNS_MIN_ORDER')) { return; }

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

        add_action('woocommerce_checkout_process',     array($this, 'enforce_on_submit'));
        
        
        add_action('woocommerce_store_api_cart_errors', array($this, 'enforce_block_checkout'), 10, 2);
        add_action('woocommerce_before_cart',          array($this, 'cart_notice'));
        add_action('woocommerce_before_checkout_form', array($this, 'checkout_notice'), 5);
    }

    public function get_settings() {
        $stored = get_option(self::OPTION_KEY, array());
        if (!is_array($stored)) { $stored = array(); }
        return array_merge(array(
            'enabled'   => 'no',  
            'threshold' => 5.00,
            'message'   => __('Minimum order amount is {min}. Add {remaining} more to proceed to checkout.', 'ai-eshop-optimizer'),
        ), $stored);
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $patch = array(
            'enabled'   => !empty($_POST['enabled']) ? 'yes' : 'no',
            'threshold' => isset($_POST['threshold']) ? max(0, (float) $_POST['threshold']) : 0,
            'message'   => isset($_POST['message']) ? sanitize_text_field(wp_unslash($_POST['message'])) : '',
        );
        if ($patch['message'] === '') {
            $patch['message'] = __('Minimum order amount is {min}. Add {remaining} more to proceed to checkout.', 'ai-eshop-optimizer');
        }
        update_option(self::OPTION_KEY, $patch, false);
        wp_send_json_success(array('message' => __('Minimum order settings saved.', 'ai-eshop-optimizer')));
    }

    private function current_subtotal() {
        if (function_exists('WC') && WC() && WC()->cart) {
            return (float) WC()->cart->get_subtotal();
        }
        return 0.0;
    }

    private function build_message($min, $current) {
        $s = $this->get_settings();
        $template = (string) $s['message'];
        return strtr($template, array(
            '{min}'       => wp_strip_all_tags(wc_price($min)),
            '{remaining}' => wp_strip_all_tags(wc_price(max(0, $min - $current))),
            '{current}'   => wp_strip_all_tags(wc_price($current)),
        ));
    }

    public function enforce_on_submit() {
        $s = $this->get_settings();
        $min = (float) $s['threshold'];
        $cur = $this->current_subtotal();
        if ($cur > 0 && $cur < $min) {
            wc_add_notice($this->build_message($min, $cur), 'error');
        }
    }

    
    public function enforce_block_checkout($errors, $cart) {
        if (!is_wp_error($errors)) { return; }
        $s   = $this->get_settings();
        $min = (float) $s['threshold'];
        $cur = ($cart && is_callable(array($cart, 'get_subtotal'))) ? (float) $cart->get_subtotal() : $this->current_subtotal();
        if ($cur > 0 && $cur < $min) {
            $errors->add('aieo_min_order', $this->build_message($min, $cur));
        }
    }

    public function cart_notice() {
        $s = $this->get_settings();
        $min = (float) $s['threshold'];
        $cur = $this->current_subtotal();
        if ($cur > 0 && $cur < $min) {
            wc_print_notice($this->build_message($min, $cur), 'notice');
        }
    }

    public function checkout_notice() {
        if (!function_exists('WC') || !WC() || !WC()->cart) { return; }
        $s = $this->get_settings();
        $min = (float) $s['threshold'];
        $cur = $this->current_subtotal();
        if ($cur > 0 && $cur < $min) {
            wc_print_notice($this->build_message($min, $cur), 'error');
        }
    }

    public function render_subtab() {
        $s = $this->get_settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        $currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : 'EUR';
        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Minimum Order', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Block checkout submission below a configurable cart subtotal. Shown to the customer at cart, checkout entry, and as a hard error on submit.', 'ai-eshop-optimizer') . '</p>';
        echo '<form id="aieo-dmm-mo-form" class="aieo-dmm-form aieo-dmm-card"><table class="form-table">';
        echo '<tr><th>' . esc_html__('Enable minimum order', 'ai-eshop-optimizer') . '</th><td>';
        echo '<label><input type="checkbox" name="enabled" value="1" ' . checked($s['enabled'] === 'yes', true, false) . '> ' . esc_html__('Block checkout below the threshold', 'ai-eshop-optimizer') . '</label></td></tr>';
        echo '<tr><th>' . esc_html__('Threshold', 'ai-eshop-optimizer') . ' (' . esc_html($currency) . ')</th><td>';
        echo '<input type="number" name="threshold" step="0.01" min="0" value="' . esc_attr((string) $s['threshold']) . '" style="width:140px;">';
        echo '<p class="description">' . esc_html__('Cart subtotal floor. Compared against `WC()->cart->get_subtotal()`, which excludes shipping + fees.', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr>';
        echo '<tr><th>' . esc_html__('Message', 'ai-eshop-optimizer') . '</th><td>';
        echo '<input type="text" name="message" value="' . esc_attr((string) $s['message']) . '" class="large-text">';
        echo '<p class="description">' . esc_html__('Tokens: {min} {remaining} {current}', 'ai-eshop-optimizer') . '</p>';
        echo '</td></tr></table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-dmm-mo-save">' . esc_html__('Save settings', 'ai-eshop-optimizer') . '</button>';
        echo ' <span id="aieo-dmm-mo-status" style="margin-left:10px;color:#646970;font-size:13px;"></span></p></form>';
        echo '<script>(function(){var f=document.getElementById("aieo-dmm-mo-form");var b=document.getElementById("aieo-dmm-mo-save");var s=document.getElementById("aieo-dmm-mo-status");if(!b)return;b.addEventListener("click",function(){var fd=new FormData(f);fd.set("action","aieo_dmm_min_order_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>';
    }
}
