<?php
class kavehlocationwoo {
    public $options;
    public static $instance = null;
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function __construct() {

        $this->options = kaveh_get_options();
        if($this->options['kaveh_map_oncheckout'] === '1'){
            $this->init();
        }

    }
    
    public function init() {
        
            add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);
            add_action('admin_enqueue_scripts', [$this, 'enqueueAdminScripts']);
            add_action('woocommerce_after_order_notes', [$this, 'addMapFieldToCheckout']);
            add_action('woocommerce_checkout_update_order_meta', [$this, 'saveLocationToOrder']);
            add_action('woocommerce_admin_order_data_after_billing_address', [$this, 'displayLocationInAdmin']);
            add_action('woocommerce_order_details_after_order_table', [$this, 'displayLocationInCustomerAccount']);
            add_action('wp_footer', [$this, 'addCustomStyles']);
       
    }
    
    public function enqueueScripts() {
        if(class_exists('woocommerce')){
            if (is_checkout() || is_account_page()) {
                wp_enqueue_style('leaflet-css', KAVEH_TEMPLATE_URI . '/assets/css/leaflet.css');
                wp_enqueue_script('leaflet-js', KAVEH_TEMPLATE_URI . '/assets/js/leaflet.js', [], null, true);
                wp_enqueue_script('osm-map-checkout', KAVEH_TEMPLATE_URI .  '/assets/js/map.js', ['jquery', 'leaflet-js'], null, true);
            }
        }
    }
    
    public function enqueueAdminScripts($hook) {
        global $post;
        
        if ($hook == 'post.php' && $post && get_post_type($post->ID) == 'shop_order') {
            wp_enqueue_style('leaflet-css-admin', KAVEH_TEMPLATE_URI . '/assets/css/leaflet.css');
            wp_enqueue_script('leaflet-js-admin', KAVEH_TEMPLATE_URI . '/assets/js/leaflet.js', [], null, true);
        }
    }
    
    public function addMapFieldToCheckout($checkout) {
        echo '<div id="osm-map" style="width: 100%; height: 400px; margin-bottom: 20px;"></div>';
        woocommerce_form_field('osm_location', [
            'type' => 'hidden',
            'required' => true,
        ], $checkout->get_value('osm_location'));
    }
    
    public function saveLocationToOrder($order_id) {
        if (!empty($_POST['osm_location'])) {
            update_post_meta($order_id, '_osm_location', sanitize_text_field($_POST['osm_location']));
        }
    }
    
    public function displayLocationInAdmin($order) {
        $location = get_post_meta($order->get_id(), '_osm_location', true);
        if ($location) {
            $coords = $this->parseCoordinates($location);
            if ($coords) {
                $this->renderAdminMap($coords['lat'], $coords['lng'], $location);
            } else {
                echo '<p><strong>Selected Location:</strong> ' . esc_html($location) . '</p>';
            }
        }
    }
    
    public function displayLocationInCustomerAccount($order) {
        $location = get_post_meta($order->get_id(), '_osm_location', true);
        if ($location) {
            $coords = $this->parseCoordinates($location);
            if ($coords) {
                $this->renderCustomerMap($coords['lat'], $coords['lng']);
            }
        }
    }
    
    public function parseCoordinates($location) {
        $coords = explode(',', $location);
        if (count($coords) == 2) {
            return [
                'lat' => trim($coords[0]),
                'lng' => trim($coords[1])
            ];
        }
        return false;
    }
    
    public function renderAdminMap($lat, $lng, $location) {
        echo '<div class="clear"></div>';
        echo '<h3>Delivery Location</h3>';
        echo '<div id="admin-osm-map" style="width: 100%; height: 300px; margin-bottom: 20px; border-radius: 8px;"></div>';
        echo '<p><strong>Coordinates:</strong> ' . esc_html($location) . '</p>';
        
        $this->renderMapScript('admin-osm-map', $lat, $lng);
    }
    
    public function renderCustomerMap($lat, $lng) {
        echo '<h2 class="woocommerce-order-details__title">Delivery Location</h2>';
        echo '<div id="customer-osm-map" style="width: 100%; height: 300px; margin-bottom: 20px; border-radius: 8px;"></div>';
        
        $this->renderMapScript('customer-osm-map', $lat, $lng);
    }
    
    public function renderMapScript($mapId, $lat, $lng) {
        echo '<script type="text/javascript">
            jQuery(document).ready(function($) {
                var map = L.map("' . esc_js($mapId) . '").setView([' . esc_js($lat) . ', ' . esc_js($lng) . '], 15);
                L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
                    maxZoom: 19,
                }).addTo(map);
                L.marker([' . esc_js($lat) . ', ' . esc_js($lng) . ']).addTo(map);
            });
        </script>';
    }
    
    public function addCustomStyles() {
        ?>
        <style>
            div#osm-map {
                border-radius: 15px;
            }
            div#customer-osm-map {
                border-radius: 8px;
                border: 1px solid #eee;
            }
        </style>
        <?php
    }
}