<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class ShippingGuard_Admin
{
    public function init()
    {
        add_action('admin_menu', array($this, 'add_menu_page'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('woocommerce_admin_order_data_after_shipping_address', array($this, 'display_order_meta'));

        // WooCommerce Product Data Tabs
        add_filter('woocommerce_product_data_tabs', array($this, 'add_product_data_tab'));
        add_action('woocommerce_product_data_panels', array($this, 'add_product_data_panel'));
        add_action('woocommerce_process_product_meta', array($this, 'save_product_data'));

        // Admin footer sync script for weight
        add_action('admin_footer', array($this, 'add_weight_sync_script'));
    }

    public function add_menu_page()
    {
        // Main menu item points to Analytics by default
        add_menu_page(
            'ShippingGuard',
            'ShippingGuard',
            'manage_options',
            'shippingguard',
            array($this, 'render_admin_page'),
            'dashicons-shield',
            56
        );

        // First submenu item (Insights)
        add_submenu_page(
            'shippingguard',
            'Shipping Insights',
            'Insights',
            'manage_options',
            'shippingguard',
            array($this, 'render_analytics_page')
        );

        add_submenu_page(
            'shippingguard',
            'Claims',
            'Claims',
            'manage_options',
            'shippingguard-claims',
            array($this, 'render_claims_page')
        );

        add_submenu_page(
            'shippingguard',
            'Shipping Protection',
            'Protection',
            'manage_options',
            'shippingguard-protection',
            array($this, 'render_admin_page')
        );

        add_submenu_page(
            'shippingguard',
            'Weight Shipping',
            'Weight Shipping',
            'manage_options',
            'shippingguard-weight',
            array($this, 'render_admin_page')
        );

        add_submenu_page(
            'shippingguard',
            'Eco Delivery',
            'Eco Delivery',
            'manage_options',
            'shippingguard-eco',
            array($this, 'render_admin_page')
        );

        add_submenu_page(
            'shippingguard',
            'Delivery Dates',
            'Delivery Dates',
            'manage_options',
            'shippingguard-edd',
            array($this, 'render_admin_page')
        );

        add_submenu_page(
            'shippingguard',
            'Condition Engine',
            'Condition Engine',
            'manage_options',
            'shippingguard-conditions',
            array($this, 'render_admin_page')
        );

        add_submenu_page(
            'shippingguard',
            'Box Inventory',
            'Box Inventory',
            'manage_options',
            'shippingguard-boxes',
            array($this, 'render_admin_page')
        );

        add_submenu_page(
            'shippingguard',
            'Conversion Enhancers',
            'Conversion Booster',
            'manage_options',
            'shippingguard-conversion',
            array($this, 'render_admin_page')
        );

        add_submenu_page(
            'shippingguard',
            'Other Plugins',
            'Other Plugins',
            'manage_options',
            'shippingguard-other-plugins',
            array($this, 'render_other_plugins_page')
        );
    }

    public function enqueue_scripts($hook)
    {
        $admin_hooks = array(
            'toplevel_page_shippingguard',
            'shippingguard_page_shippingguard-claims',
            'shippingguard_page_shippingguard-protection',
            'shippingguard_page_shippingguard-weight',
            'shippingguard_page_shippingguard-eco',
            'shippingguard_page_shippingguard-edd',
            'shippingguard_page_shippingguard-conditions',
            'shippingguard_page_shippingguard-boxes',
            'shippingguard_page_shippingguard-conversion',
            'shippingguard_page_shippingguard-other-plugins'
        );
        if (!in_array($hook, $admin_hooks, true)) {
            return;
        }

        wp_enqueue_media();

        $script = 'admin';
        if ($hook === 'shippingguard_page_shippingguard-claims')
            $script = 'claims';
        if ($hook === 'shippingguard_page_shippingguard-analytics' || $hook === 'toplevel_page_shippingguard')
            $script = 'analytics';
        if ($hook === 'shippingguard_page_shippingguard-other-plugins')
            $script = 'other-plugins';
        // 'shippingguard_page_shippingguard-settings' uses 'admin' script (Settings)

        wp_enqueue_script(
            'shippingguard-' . $script,
            SHIPPINGGUARD_URL . 'assets/' . $script . '.js',
            array('wp-element', 'wp-api-fetch'),
            SHIPPINGGUARD_VERSION,
            true
        );

        wp_localize_script('shippingguard-' . $script, 'shippingGuardAdminData', array(
            'root' => esc_url_raw(rest_url()),
            'nonce' => wp_create_nonce('wp_rest'),
            'currency_symbol' => get_woocommerce_currency_symbol(),
            'weight_unit' => get_option('woocommerce_weight_unit', 'kg'),
            'is_pro' => (bool) shippingguard_is_pro(),
            'site_url' => get_site_url(),
            'user_name' => wp_get_current_user()->display_name,
            'user_email' => wp_get_current_user()->user_email,
            'dim_unit' => get_option('woocommerce_dimension_unit', 'cm'),
        ));
    }

    public function render_admin_page()
    {
        echo '<div class="wrap">';
        echo '<div id="shippingguard-admin-root"></div>';
        echo '</div>';
    }

    public function render_claims_page()
    {
        echo '<div class="wrap">';
        echo '<div id="shippingguard-claims-root"></div>';
        echo '</div>';
    }

    public function render_analytics_page()
    {
        echo '<div class="wrap">';
        echo '<div id="shippingguard-analytics-root"></div>';
        echo '</div>';
    }

    public function render_other_plugins_page()
    {
        echo '<div class="wrap">';
        echo '<div id="shippingguard-other-plugins-root"></div>';
        echo '</div>';
    }

    public function display_order_meta($order)
    {
        $enabled = $order->get_meta('_shipping_protection_enabled');
        $fee = $order->get_meta('_shipping_protection_fee');

        if ('yes' === $enabled) {
            echo '<div class="shipping-protection-meta" style="margin-top: 15px;">';
            echo '<p><strong>Shipping Protection:</strong> Enabled</p>';
            echo '<p><strong>Protection Fee:</strong> ' . wp_kses_post( wc_price( $fee ) ) . '</p>';
            echo '</div>';
        }
    }

    public function add_product_data_tab($tabs)
    {
        $tabs['shippingguard'] = array(
            'label'    => __('ShippingGuard', 'shippingguard'),
            'target'   => 'shippingguard_product_data',
            'class'    => array('show_if_simple', 'show_if_variable'),
            'priority' => 80
        );
        return $tabs;
    }

    public function add_product_data_panel()
    {
        global $post;
        $is_pro = shippingguard_is_pro();
        $unit = get_option('woocommerce_weight_unit', 'kg');

        echo '<div id="shippingguard_product_data" class="panel woocommerce_options_panel">';
        echo '<div class="options_group">';
        
        echo '<p style="padding: 0 12px; margin-bottom: 20px; font-weight: bold; border-left: 4px solid #cc3333;">Fulfillment Strategy</p>';

        woocommerce_wp_text_input(
            array(
                'id'          => '_shippingguard_custom_weight',
                'label'       => sprintf(__('Fulfillment Weight (%s)', 'shippingguard'), $unit),
                'description' => __('Override weight specifically for ShippingGuard calculations.', 'shippingguard'),
                'desc_tip'    => true,
                'type'        => 'text',
            )
        );

        woocommerce_wp_text_input(
            array(
                'id'          => '_shippingguard_fixed_fee',
                'label'       => __('Fixed Handling Fee', 'shippingguard'),
                'description' => __('Add a mandatory surcharge for this specific product (e.g. for fragile items).', 'shippingguard'),
                'desc_tip'    => true,
                'type'        => 'text',
            )
        );

        woocommerce_wp_checkbox(
            array(
                'id'          => '_shippingguard_is_free',
                'label'       => __('Free Shipping Override', 'shippingguard'),
                'description' => __('Check this to grant global free shipping if this item is in cart.', 'shippingguard')
            )
        );

        echo '</div>';
        echo '<div class="options_group" style="padding-top: 15px; border-top: 1px solid #eee;">';
        echo '<p style="padding: 0 12px; margin-bottom: 10px; font-size: 11px; color: #777; text-transform: uppercase; letter-spacing: 0.5px;">Advanced Logistics (Requires Pro)</p>';

        woocommerce_wp_checkbox(
            array(
                'id'          => '_shippingguard_disable_eco',
                'label'       => __('Restrict Eco Delivery ' . (!$is_pro ? '<span style="color: #667eea; font-weight: bold;">(Pro)</span>' : ''), 'shippingguard'),
                'description' => __('Strictly exclude this heavy/non-green item from Eco Delivery options.', 'shippingguard')
            )
        );

        woocommerce_wp_checkbox(
            array(
                'id'          => '_shippingguard_split_shipment',
                'label'       => __('Enable Multi-Box Split ' . (!$is_pro ? '<span style="color: #667eea; font-weight: bold;">(Pro)</span>' : ''), 'shippingguard'),
                'description' => __('Force this item into its own separate shipment box at checkout.', 'shippingguard')
            )
        );

        echo '</div>';
        echo '</div>';
    }

    public function save_product_data($post_id)
    {
        $custom_weight = isset($_POST['_shippingguard_custom_weight']) ? sanitize_text_field($_POST['_shippingguard_custom_weight']) : '';
        update_post_meta($post_id, '_shippingguard_custom_weight', $custom_weight);

        $fixed_fee = isset($_POST['_shippingguard_fixed_fee']) ? sanitize_text_field($_POST['_shippingguard_fixed_fee']) : '';
        update_post_meta($post_id, '_shippingguard_fixed_fee', $fixed_fee);

        $is_free = isset($_POST['_shippingguard_is_free']) ? 'yes' : 'no';
        update_post_meta($post_id, '_shippingguard_is_free', $is_free);

        $disable_eco = isset($_POST['_shippingguard_disable_eco']) ? 'yes' : 'no';
        update_post_meta($post_id, '_shippingguard_disable_eco', $disable_eco);

        $split_ship = isset($_POST['_shippingguard_split_shipment']) ? 'yes' : 'no';
        update_post_meta($post_id, '_shippingguard_split_shipment', $split_ship);
    }

    public function add_weight_sync_script()
    {
        $screen = get_current_screen();
        if (!$screen || $screen->id !== 'product') return;
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                var $wcWeight = $('#_weight');
                var $sgWeight = $('#_shippingguard_custom_weight');

                // Initial sync if SG is empty
                if ($sgWeight.val() === '' && $wcWeight.val() !== '') {
                    $sgWeight.val($wcWeight.val());
                }

                $wcWeight.on('input change', function() {
                    $sgWeight.val($(this).val());
                });

                $sgWeight.on('input change', function() {
                    $wcWeight.val($(this).val());
                });
            });
        </script>
        <?php
    }
}
