<?php


namespace SMFWC\Shiperman\Shipping_Method;

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

use SMFWC\Shiperman\API\SMFWC_Shiperman_API;
use WC_Shipping_Method;

class SMFWC_Shiperman_Shipping_Method extends WC_Shipping_Method
{
    public function __construct()
    {
        $this->id = 'shiperman_shipping_method';
        $this->method_title = __('Shiperman Shipping', 'shiperman-for-woocommerce');
        $this->method_description = __('Shiperman API-driven shipping method', 'shiperman-for-woocommerce');
        $this->title = "Shiperman Shipping";


        $this->enabled = "yes";
        // Check if there are any products missing shipping info
        //$missing_info = $this->get_products_missing_shipping_info();

        // if (!empty($missing_info)) {
        //     // Disable the method
        //     $this->enabled = "no";
        //     // Optional: Add admin notice
        //     // add_action('admin_notices', [$this, 'admin_notice_invalid_products']);
        // } else {
        //     $this->enabled = "yes";
        // }

        $this->init();
    }


    private function get_products_missing_shipping_info()
    {
        $args = [
            'status' => 'publish',
            'limit'  => -1,
            'type'   => ['simple', 'variable'],
            'return' => 'objects'
        ];

        $products = wc_get_products($args);
        $invalid_products = [];

        foreach ($products as $product) {
            if ($product->is_virtual() || $product->is_downloadable()) {
                continue;
            }

            if (! $this->is_product_shipping_info_valid($product)) {
                $invalid_products[] = $product;
                
            }
        }

        return $invalid_products;
    }

    private function is_product_shipping_info_valid($product)
    {
        // Allow products with missing weight (will use default 1kg)
        // Only require length, width, and height to be valid
        return (float) $product->get_length() > 0 &&
            (float) $product->get_width() > 0 &&
            (float) $product->get_height() > 0;
    }

    // public function admin_notice_invalid_products()
    // {
    //     echo '<div class="notice notice-error"><p>';
    //     echo esc_html__('Shiperman Shipping cannot be enabled because some physical products are missing shipping dimensions or weight.', 'shiperman-for-woocommerce');
    //     echo '</p></div>';
    // }

    public function init()
    {
        $this->init_form_fields();
        $this->init_settings();
        add_action('woocommerce_update_options_shipping_' . $this->id, [$this, 'process_admin_options']);
    }

    public static function register()
    {
        add_filter('woocommerce_shipping_methods', function ($methods) {
            $methods['shiperman_shipping_method'] = self::class;
            return $methods;
        });
    }

    public function init_form_fields()
    {
        $this->form_fields = [
            'enabled' => [
                'title' => __('Enable', 'shiperman-for-woocommerce'),
                'type' => 'checkbox',
                'description' => __('Enable Shiperman shipping method.', 'shiperman-for-woocommerce'),
                'default' => 'yes',
            ],
            'title' => [
                'title' => __('Method Title', 'shiperman-for-woocommerce'),
                'type' => 'text',
                'description' => __('This controls the title displayed to customers at checkout.', 'shiperman-for-woocommerce'),
                'default' => __('Shiperman Shipping', 'shiperman-for-woocommerce'),
                'desc_tip' => true,
            ],
            'pricing_type' => [
                'title' => __('Pricing Type', 'shiperman-for-woocommerce'),
                'type' => 'select',
                'description' => __('Choose between Flat Rate or Margin Rate pricing.', 'shiperman-for-woocommerce'),
                'default' => 'flat_rate',
                'options' => [
                    'flat_rate' => __('Flat Rate', 'shiperman-for-woocommerce'),
                    'margin_rate' => __('Margin Rate', 'shiperman-for-woocommerce'),
                ],
            ],
            'flat_rate_cost' => [
                'title' => __('Flat Rate Cost', 'shiperman-for-woocommerce'),
                'type' => 'price',
                'description' => __('Enter the flat rate for shipping.', 'shiperman-for-woocommerce'),
                'default' => '5.00',
                'desc_tip' => true,
            ],
            'margin_rate' => [
                'title' => __('Margin Rate Multiplier', 'shiperman-for-woocommerce'),
                'type' => 'number',
                'description' => __('Enter the margin multiplier for Shiperman API rates.', 'shiperman-for-woocommerce'),
                'default' => '1.0',
                'desc_tip' => true,
                'custom_attributes' => ['step' => '0.01'],
            ],
            'free_shipping_threshold' => [
                'title' => __('Free Shipping Threshold', 'shiperman-for-woocommerce'),
                'type' => 'price',
                'description' => __('Enter the order amount above which free shipping applies.', 'shiperman-for-woocommerce'),
                'default' => '100.00',
                'desc_tip' => true,
            ],
        ];
    }

    public function calculate_shipping($package = [])
    {
        $pricing_type = $this->get_option('pricing_type');
        $cost = ($pricing_type === 'flat_rate') ? (float) $this->get_option('flat_rate_cost') : $this->get_dynamic_shipping_rate($package);

        $margin = ($pricing_type === 'margin_rate') ? (float) $this->get_option('margin_rate') : $this->get_dynamic_shipping_rate($package);
        if ($margin) {
            $cost = $cost * $margin;
        }

        if (WC()->cart->get_cart_contents_total() >= $this->get_option('free_shipping_threshold')) {
            $cost = 0;
        }

        $this->add_rate([
            'id' => $this->id,
            'label' => $this->title,
            'cost' => $cost,
            'calc_tax' => 'per_order',
        ]);
    }

    private function get_dynamic_shipping_rate($package)
    {
        $destination_country = $package['destination']['country'];

        $items = array_reduce($package['contents'], function ($carry, $item) {
            $product = $item['data'];
            $quantity = $item['quantity'];
            
            // Use default weight if missing
            $weight = (float) $product->get_weight();
            if ($weight <= 0) {
                $weight = 1.0; // Default 1kg
                // Set flag to show notice
                WC()->session->set('shiperman_default_weight_applied', true);
            }

            for ($i = 0; $i < $quantity; $i++) {
                $carry[] = [
                    'id'     => $product->get_id(),
                    'name'   => $product->get_name(),
                    'price'  => (float) $product->get_price(),
                    'weight' => $weight, // Use calculated weight
                    'length' => (float) $product->get_length(),
                    'width'  => (float) $product->get_width(),
                    'height' => (float) $product->get_height(),
                ];
            }

            return $carry;
        }, []);


        $body = [
            'items' => $items,
            'recipient' => ['countryCode' => $destination_country],
            'currency' => get_woocommerce_currency(),
        ];



        $response = SMFWC_Shiperman_API::get_instance()->make_authenticated_request('plugin/orders/check-price', 'POST', $body);

        // $logger = wc_get_logger();
        // $context = ['source' => 'shiperman-api-debug'];

        // $logger->info('Items Pretty: ' . json_encode($items, JSON_PRETTY_PRINT), $context);
        // $logger->info('Destination Country: ' . $destination_country, $context);
        // $logger->info('Items: ' . print_r($items, true), $context);
        // $logger->info('Request Body: ' . print_r($body, true), $context);
        // $logger->info('Response: ' . print_r($response, true), $context);


        return (!empty($response['status']) && $response['status'] === 'success' && !empty($response['data']['cost'])) ? $response['data']['cost'] : false;
    }

    public function process_admin_options()
    {
        /*$missing_info = $this->get_products_missing_shipping_info();
        if (!empty($missing_info)) {
            // Force-disable and show message
            $this->settings['enabled'] = 'no';
            update_option('woocommerce_' . $this->id . '_settings', $this->settings);

            add_action('admin_notices', function () {
                echo '<div class="notice notice-error is-dismissible">';
                echo '<p>' . esc_html__('Shiperman Shipping cannot be enabled until all physical products have valid length, width, and height. Weight will use default 1kg if not set.', 'shiperman-for-woocommerce') . '</p>';
                echo '<p><a href="' . esc_url(admin_url('admin.php?page=shiperman_validate_shop_tools')) . '" class="button button-primary">';
                echo esc_html__('Validate Products Now', 'shiperman-for-woocommerce');
                echo '</a></p>';
                echo '</div>';
            });


            return; // Don't save options
        }*/

        parent::process_admin_options();
    }

}
