<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class ShippingGuard_API {
    public function init() {
        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
    }

    public function register_routes() {
        register_rest_route( 'shippingguard/v1', '/settings', array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_settings' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'save_settings' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
        ) );

        // Provide categories + shipping methods for Smart Rules UI
        register_rest_route( 'shippingguard/v1', '/options', array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_options' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
        ) );

        // Proxy endpoint for Other Plugins to bypass CORS
        register_rest_route( 'shippingguard/v1', '/other-plugins', array(
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => array( $this, 'get_other_plugins_proxy' ),
                'permission_callback' => array( $this, 'permissions_check' ),
            ),
        ) );
    }

    public function permissions_check() {
        return current_user_can( 'manage_options' );
    }

    public function get_settings() {
        $settings = array(
            'is_enabled'     => get_option( 'shippingguard_is_enabled', 'yes' ),
            'pricing_method' => get_option( 'shippingguard_pricing_method', 'fixed' ),
            'fixed_fee'      => get_option( 'shippingguard_fixed_fee', '2.99' ),
            'percentage_fee' => get_option( 'shippingguard_percentage_fee', '2' ),
            'max_cap'        => get_option( 'shippingguard_max_cap', '5' ),
            'tier_rules'     => get_option( 'shippingguard_tier_rules', array(
                array( 'min' => 0, 'max' => 50, 'fee' => 1 ),
                array( 'min' => 50, 'max' => 100, 'fee' => 2 ),
                array( 'min' => 100, 'max' => '', 'fee' => 3 ),
            ) ),
            // Smart Rules
            'smart_rules_enabled'     => get_option( 'shippingguard_smart_rules_enabled', 'no' ),
            'smart_min_order'         => get_option( 'shippingguard_smart_min_order', '' ),
            // Branding
            'protection_name'         => get_option( 'shippingguard_protection_name', 'Shipping Protection' ),
            'protection_description'  => get_option( 'shippingguard_protection_description', 'Protect your order from damage, loss or theft' ),
            'checkout_label'         => get_option( 'shippingguard_checkout_label', 'Protect your order from damage, loss or theft' ),
            'protection_icon'        => get_option( 'shippingguard_protection_icon', '' ),
            'show_on_cart'           => get_option( 'shippingguard_show_on_cart', 'yes' ),
            'show_on_checkout'       => get_option( 'shippingguard_show_on_checkout', 'yes' ),
            // Exclusions
            'exclude_digital'         => get_option( 'shippingguard_exclude_digital', 'yes' ),
            'exclude_products'        => get_option( 'shippingguard_exclude_products', array() ),
            'exclude_categories'      => get_option( 'shippingguard_exclude_categories', array() ),
            
            // Modules
            'module_protection'       => get_option( 'shippingguard_module_protection', 'yes' ),
            'module_weight_shipping'  => get_option( 'shippingguard_module_weight_shipping', 'yes' ),
            'module_zero_emission'    => get_option( 'shippingguard_module_zero_emission', 'yes' ),

            // Weight Shipping Settings
            'weight_shipping_rate_per_kg'  => get_option( 'shippingguard_weight_shipping_rate_per_kg', '5.00' ),
            'weight_shipping_base_fee'     => get_option( 'shippingguard_weight_shipping_base_fee', '2.00' ),

            // Zero Emission Settings
            'zero_emission_fee'            => get_option( 'shippingguard_zero_emission_fee', '0.50' ),
            'zero_emission_label'          => get_option( 'shippingguard_zero_emission_label', 'Green Zero Emission Delivery' ),

            // EDD Settings
            'module_edd'                   => get_option( 'shippingguard_module_edd', 'yes' ),
            'edd_min_days'                 => get_option( 'shippingguard_edd_min_days', '3' ),
            'edd_max_days'                 => get_option( 'shippingguard_edd_max_days', '5' ),
            'edd_working_days'             => get_option( 'shippingguard_edd_working_days', array('Mon', 'Tue', 'Wed', 'Thu', 'Fri') ),
            'edd_cutoff_time'              => get_option( 'shippingguard_edd_cutoff_time', '15:00' ),
            'edd_selection_enabled'        => get_option( 'shippingguard_edd_selection_enabled', 'no' ),
            'edd_max_future_days'          => get_option( 'shippingguard_edd_max_future_days', '14' ),

            // Service Levels
            'service_standard_enabled'     => get_option( 'shippingguard_service_standard_enabled', 'yes' ),
            'service_standard_fee'         => get_option( 'shippingguard_service_standard_fee', '0' ),
            'service_standard_min'         => get_option( 'shippingguard_service_standard_min', '3' ),
            'service_standard_max'         => get_option( 'shippingguard_service_standard_max', '5' ),
            'service_express_enabled'      => get_option( 'shippingguard_service_express_enabled', 'no' ),
            'service_express_fee'          => get_option( 'shippingguard_service_express_fee', '15' ),
            'service_express_min'          => get_option( 'shippingguard_service_express_min', '1' ),
            'service_express_max'          => get_option( 'shippingguard_service_express_max', '2' ),

            // Volumetric
            'volumetric_enabled'           => get_option( 'shippingguard_volumetric_enabled', 'no' ),
            'volumetric_divisor'           => get_option( 'shippingguard_volumetric_divisor', '139' ),
            'weight_unit'                  => get_option( 'shippingguard_weight_unit', get_option('woocommerce_weight_unit', 'kg') ),

            // Free Shipping Bar
            'free_shipping_bar_enabled'    => get_option( 'shippingguard_free_shipping_bar_enabled', 'yes' ),
            'free_shipping_threshold'      => get_option( 'shippingguard_free_shipping_threshold', '100.00' ),
            'free_shipping_bar_color'      => get_option( 'shippingguard_free_shipping_bar_color', '#2563eb' ),
            'free_shipping_bar_position'   => get_option( 'shippingguard_free_shipping_bar_position', 'floating' ),

            // Table Rates
            'table_rate_rules'             => get_option( 'shippingguard_table_rate_rules', array() ),

            // Box Inventory
            'box_inventory'                => get_option( 'shippingguard_box_inventory', array() ),

            // Package Splitting
            'package_splitting_enabled'    => get_option( 'shippingguard_package_splitting_enabled', 'no' ),
        );
        return rest_ensure_response( $settings );
    }

    public function save_settings( $request ) {
        $params = $request->get_json_params();

        $text_fields = array(
            'is_enabled', 'pricing_method', 'smart_rules_enabled', 'smart_min_order',
            'protection_name', 'protection_description', 'checkout_label', 'protection_icon',
            'exclude_digital', 'show_on_cart', 'show_on_checkout',
            'module_protection', 'module_weight_shipping', 'module_zero_emission', 'module_edd',
            'zero_emission_label', 'edd_cutoff_time', 
            'volumetric_enabled', 'volumetric_divisor', 'free_shipping_bar_enabled', 'free_shipping_bar_color',
            'free_shipping_bar_position',
            'package_splitting_enabled', 'weight_unit', 'edd_selection_enabled',
            'service_standard_enabled', 'service_express_enabled'
        );
        foreach ( $text_fields as $field ) {
            if ( isset( $params[ $field ] ) ) {
                update_option( 'shippingguard_' . $field, sanitize_text_field( $params[ $field ] ) );
            }
        }

        $float_fields = array( 
            'fixed_fee', 'percentage_fee', 'max_cap', 'weight_shipping_rate_per_kg', 
            'weight_shipping_base_fee', 'zero_emission_fee', 'edd_min_days', 'edd_max_days', 
            'free_shipping_threshold', 'edd_max_future_days',
            'service_standard_fee', 'service_standard_min', 'service_standard_max',
            'service_express_fee', 'service_express_min', 'service_express_max'
        );
        foreach ( $float_fields as $field ) {
            if ( isset( $params[ $field ] ) ) {
                update_option( 'shippingguard_' . $field, floatval( $params[ $field ] ) );
            }
        }

        if ( isset( $params['edd_working_days'] ) && is_array( $params['edd_working_days'] ) ) {
            update_option( 'shippingguard_edd_working_days', array_map( 'sanitize_text_field', $params['edd_working_days'] ) );
        }

        if ( isset( $params['tier_rules'] ) && is_array( $params['tier_rules'] ) ) {
            $tier_rules = array_map( function( $rule ) {
                return array(
                    'min' => floatval( $rule['min'] ),
                    'max' => $rule['max'] === '' ? '' : floatval( $rule['max'] ),
                    'fee' => floatval( $rule['fee'] ),
                );
            }, $params['tier_rules'] );
            update_option( 'shippingguard_tier_rules', $tier_rules );
        }

        if ( isset( $params['exclude_products'] ) && is_array( $params['exclude_products'] ) ) {
            update_option( 'shippingguard_exclude_products', array_map( 'absint', $params['exclude_products'] ) );
        }
        if ( isset( $params['exclude_categories'] ) && is_array( $params['exclude_categories'] ) ) {
            update_option( 'shippingguard_exclude_categories', array_map( 'absint', $params['exclude_categories'] ) );
        }

        if (isset($params['table_rate_rules']) && is_array($params['table_rate_rules'])) {
            update_option('shippingguard_table_rate_rules', $params['table_rate_rules']);
        }
        if (isset($params['box_inventory']) && is_array($params['box_inventory'])) {
            update_option('shippingguard_box_inventory', $params['box_inventory']);
        }

        return rest_ensure_response(array('success' => true));
    }

    public function get_options() {
        // Product categories
        $categories = get_terms( array(
            'taxonomy'   => 'product_cat',
            'hide_empty' => false,
        ) );
        $cat_options = array();
        if ( ! is_wp_error( $categories ) ) {
            foreach ( $categories as $cat ) {
                $cat_options[] = array( 'value' => $cat->term_id, 'label' => $cat->name );
            }
        }

        // Products (for exclusion picker) - Limit to 100 for balance between usability and performance
        $products = wc_get_products( array( 'limit' => 100, 'status' => 'publish' ) );
        $product_options = array();
        foreach ( $products as $product ) {
            $product_options[] = array( 'value' => $product->get_id(), 'label' => $product->get_name() );
        }

        return rest_ensure_response( array(
            'categories'      => $cat_options,
            'products'        => $product_options,
        ) );
    }

    public function get_other_plugins_proxy() {
        $transient_key = 'shippingguard_other_plugins_cache';
        $cached_data   = get_transient( $transient_key );

        if ( false !== $cached_data ) {
            return rest_ensure_response( $cached_data );
        }

        $response = wp_remote_get( 'https://dominopress.com/api/wp-plugins', array(
            'timeout' => 15,
        ) );

        if ( is_wp_error( $response ) ) {
            return new WP_Error( 'fetch_failed', 'Failed to fetch plugins from DominoPress', array( 'status' => 500 ) );
        }

        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        if ( empty( $data ) || ! isset( $data['success'] ) ) {
            return new WP_Error( 'invalid_data', 'Invalid response from DominoPress API', array( 'status' => 500 ) );
        }

        // Cache for 12 hours
        set_transient( $transient_key, $data, 12 * HOUR_IN_SECONDS );

        return rest_ensure_response( $data );
    }
}
