<?php

namespace Unlockafe_addons\Widgets;

use Unlockafe_addons\Traits\Utils as UnlockafeUtils;
use Unlockafe_addons\Traits\Widget_helper;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

/**
 * Advanced Google Map Widget
 *
 * @since 1.0.0
 */
class Advanced_Google_Map extends Widget_Base
{
    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     */
    public function get_name()
    {
        return 'unlockafe-advanced-google-map';
    }

    /**
     * Retrieve the widget title.
     */
    public function get_title()
    {
        return __('Advanced Google Map', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     */
    public function get_icon()
    {
        return 'eicon-google-maps ulicon';
    }

    /**
     * Retrieve the list of categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of keywords.
     */
    public function get_keywords()
    {
        return ['google', 'map', 'maps', 'location', 'marker', 'gps'];
    }

    /**
     * Retrieve the list of scripts.
     */
    public function get_script_depends()
    {
        return ['unlockafe-advanced-google-map-scripts'];
    }

    /**
     * Retrieve the list of styles.
     */
    public function get_style_depends()
    {
        return ['unlockafe-advanced-google-map-style'];
    }

    /**
     * Register widget controls.
     */
    protected function register_controls()
    {
        $this->register_content_controls();
        $this->register_style_controls();
    }

    /**
     * Register content controls.
     */
    protected function register_content_controls()
    {
        // General Settings
        $this->start_controls_section(
            'general_section',
            [
                'label' => __('General Settings', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'google_api_key',
            [
                'label' => __('Google Maps API Key (Optional)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '',
                'placeholder' => __('Leave empty to use plugin settings', 'unlock-addons-for-elementor'),
                'description' => __('Leave empty to use the API key from plugin settings. Or enter a custom key to override. Get your API key from <a href="https://console.cloud.google.com/google/maps-apis" target="_blank">Google Cloud Console</a>', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'map_height',
            [
                'label' => __('Map Height', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'vh'],
                'range' => [
                    'px' => [
                        'min' => 200,
                        'max' => 1000,
                        'step' => 10,
                    ],
                    'vh' => [
                        'min' => 20,
                        'max' => 100,
                        'step' => 5,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 500,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-google-map-container' => 'height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'map_zoom',
            [
                'label' => __('Zoom Level', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => [
                        'min' => 1,
                        'max' => 20,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 12,
                ],
            ]
        );

        $this->add_control(
            'map_type',
            [
                'label' => __('Map Type', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'roadmap' => __('Roadmap', 'unlock-addons-for-elementor'),
                    'satellite' => __('Satellite', 'unlock-addons-for-elementor'),
                    'hybrid' => __('Hybrid', 'unlock-addons-for-elementor'),
                    'terrain' => __('Terrain', 'unlock-addons-for-elementor'),
                ],
                'default' => 'roadmap',
            ]
        );

        $this->add_control(
            'map_style',
            [
                'label' => __('Map Style', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'default' => __('Default', 'unlock-addons-for-elementor'),
                    'silver' => __('Silver', 'unlock-addons-for-elementor'),
                    'retro' => __('Retro', 'unlock-addons-for-elementor'),
                    'dark' => __('Dark', 'unlock-addons-for-elementor'),
                    'night' => __('Night', 'unlock-addons-for-elementor'),
                    'aubergine' => __('Aubergine', 'unlock-addons-for-elementor'),
                ],
                'default' => 'default',
            ]
        );

        $this->end_controls_section();

        // Map Center
        $this->start_controls_section(
            'center_section',
            [
                'label' => __('Map Center', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'center_latitude',
            [
                'label' => __('Latitude', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '40.7128',
                'placeholder' => __('e.g., 40.7128', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'center_longitude',
            [
                'label' => __('Longitude', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '-74.0060',
                'placeholder' => __('e.g., -74.0060', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'center_address',
            [
                'label' => __('Or Enter Address', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => '',
                'placeholder' => __('e.g., New York, NY, USA', 'unlock-addons-for-elementor'),
                'description' => __('If address is provided, it will override latitude/longitude', 'unlock-addons-for-elementor'),
            ]
        );

        $this->end_controls_section();

        // Markers Section
        $this->start_controls_section(
            'markers_section',
            [
                'label' => __('Markers', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $repeater = new Repeater();

        $repeater->add_control(
            'marker_title',
            [
                'label' => __('Title', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('Marker Title', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter marker title', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'marker_latitude',
            [
                'label' => __('Latitude', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '40.7128',
                'placeholder' => __('e.g., 40.7128', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'marker_longitude',
            [
                'label' => __('Longitude', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '-74.0060',
                'placeholder' => __('e.g., -74.0060', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'marker_address',
            [
                'label' => __('Or Enter Address', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => '',
                'placeholder' => __('e.g., New York, NY, USA', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'marker_description',
            [
                'label' => __('Description', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => __('Marker description', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter marker description', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'marker_icon',
            [
                'label' => __('Custom Icon', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::MEDIA,
                'default' => [
                    'url' => '',
                ],
            ]
        );

        $repeater->add_control(
            'marker_icon_color',
            [
                'label' => __('Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ef4444',
            ]
        );

        $this->add_control(
            'map_markers',
            [
                'label' => __('Map Markers', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [
                    [
                        'marker_title' => __('New York', 'unlock-addons-for-elementor'),
                        'marker_latitude' => '40.7128',
                        'marker_longitude' => '-74.0060',
                        'marker_description' => __('This is New York', 'unlock-addons-for-elementor'),
                    ],
                ],
                'title_field' => '{{{ marker_title }}}',
            ]
        );

        $this->end_controls_section();

        // Controls Section
        $this->start_controls_section(
            'controls_section',
            [
                'label' => __('Map Controls', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'show_zoom_controls',
            [
                'label' => __('Show Zoom Controls', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_map_type_control',
            [
                'label' => __('Show Map Type Control', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_street_view',
            [
                'label' => __('Show Street View', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_fullscreen',
            [
                'label' => __('Show Fullscreen Control', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'enable_scroll_wheel',
            [
                'label' => __('Enable Scroll Wheel Zoom', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'enable_dragging',
            [
                'label' => __('Enable Dragging', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register style controls.
     */
    protected function register_style_controls()
    {
        // Container Style
        $this->start_controls_section(
            'container_style_section',
            [
                'label' => __('Container', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'container_border_radius',
            [
                'label' => __('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-google-map-container' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'container_box_shadow',
                'label' => __('Box Shadow', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlockafe-google-map-container',
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Get map style JSON
     */
    private function get_map_style($style_name) {
        $styles = [
            'silver' => [
                ['elementType' => 'geometry', 'stylers' => [['color' => '#f5f5f5']]],
                ['elementType' => 'labels.icon', 'stylers' => [['visibility' => 'off']]],
                ['elementType' => 'labels.text.fill', 'stylers' => [['color' => '#616161']]],
                ['elementType' => 'labels.text.stroke', 'stylers' => [['color' => '#f5f5f5']]],
            ],
            'retro' => [
                ['elementType' => 'geometry', 'stylers' => [['color' => '#ebe3cd']]],
                ['elementType' => 'labels.text.fill', 'stylers' => [['color' => '#523735']]],
                ['elementType' => 'labels.text.stroke', 'stylers' => [['color' => '#f5f1e6']]],
            ],
            'dark' => [
                ['elementType' => 'geometry', 'stylers' => [['color' => '#212121']]],
                ['elementType' => 'labels.icon', 'stylers' => [['visibility' => 'off']]],
                ['elementType' => 'labels.text.fill', 'stylers' => [['color' => '#757575']]],
                ['elementType' => 'labels.text.stroke', 'stylers' => [['color' => '#212121']]],
            ],
            'night' => [
                ['elementType' => 'geometry', 'stylers' => [['color' => '#242f3e']]],
                ['elementType' => 'labels.text.fill', 'stylers' => [['color' => '#746855']]],
                ['elementType' => 'labels.text.stroke', 'stylers' => [['color' => '#242f3e']]],
            ],
            'aubergine' => [
                ['elementType' => 'geometry', 'stylers' => [['color' => '#1d1c21']]],
                ['elementType' => 'labels.text.fill', 'stylers' => [['color' => '#746855']]],
                ['elementType' => 'labels.text.stroke', 'stylers' => [['color' => '#1d1c21']]],
            ],
        ];

        return isset($styles[$style_name]) ? json_encode($styles[$style_name]) : '[]';
    }

    /**
     * Render widget output on the frontend.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        // Get API key from widget settings or plugin settings
        $api_key = !empty($settings['google_api_key']) ? esc_attr($settings['google_api_key']) : get_option('unlockafe_google_map_api_key', '');
        $map_height = !empty($settings['map_height']['size']) ? intval($settings['map_height']['size']) : 500;
        $map_height_unit = !empty($settings['map_height']['unit']) ? esc_attr($settings['map_height']['unit']) : 'px';
        $map_zoom = !empty($settings['map_zoom']['size']) ? intval($settings['map_zoom']['size']) : 12;
        $map_type = !empty($settings['map_type']) ? esc_attr($settings['map_type']) : 'roadmap';
        $map_style = !empty($settings['map_style']) ? esc_attr($settings['map_style']) : 'default';
        $center_lat = !empty($settings['center_latitude']) ? floatval($settings['center_latitude']) : 40.7128;
        $center_lng = !empty($settings['center_longitude']) ? floatval($settings['center_longitude']) : -74.0060;
        $center_address = !empty($settings['center_address']) ? esc_html($settings['center_address']) : '';
        $markers = !empty($settings['map_markers']) ? $settings['map_markers'] : [];
        $show_zoom = $settings['show_zoom_controls'] === 'yes';
        $show_map_type = $settings['show_map_type_control'] === 'yes';
        $show_street_view = $settings['show_street_view'] === 'yes';
        $show_fullscreen = $settings['show_fullscreen'] === 'yes';
        $enable_scroll = $settings['enable_scroll_wheel'] === 'yes';
        $enable_dragging = $settings['enable_dragging'] === 'yes';

        $map_id = 'unlockafe-google-map-' . $this->get_id();
        $map_style_json = $this->get_map_style($map_style);

        if (empty($api_key)) {
            echo '<div class="unlockafe-google-map-error">' . __('Please enter your Google Maps API Key in widget settings.', 'unlock-addons-for-elementor') . '</div>';
            return;
        }

        ?>
        <div class="unlockafe-google-map-wrapper">
            <div id="<?php echo esc_attr($map_id); ?>" 
                 class="unlockafe-google-map-container"
                 style="height: <?php echo esc_attr($map_height . $map_height_unit); ?>;"
                 data-api-key="<?php echo esc_attr($api_key); ?>"
                 data-center-lat="<?php echo esc_attr($center_lat); ?>"
                 data-center-lng="<?php echo esc_attr($center_lng); ?>"
                 data-center-address="<?php echo esc_attr($center_address); ?>"
                 data-zoom="<?php echo esc_attr($map_zoom); ?>"
                 data-map-type="<?php echo esc_attr($map_type); ?>"
                 data-map-style="<?php echo esc_attr($map_style_json); ?>"
                 data-show-zoom="<?php echo $show_zoom ? 'yes' : 'no'; ?>"
                 data-show-map-type="<?php echo $show_map_type ? 'yes' : 'no'; ?>"
                 data-show-street-view="<?php echo $show_street_view ? 'yes' : 'no'; ?>"
                 data-show-fullscreen="<?php echo $show_fullscreen ? 'yes' : 'no'; ?>"
                 data-enable-scroll="<?php echo $enable_scroll ? 'yes' : 'no'; ?>"
                 data-enable-dragging="<?php echo $enable_dragging ? 'yes' : 'no'; ?>"
                 data-markers='<?php echo json_encode($markers); ?>'>
            </div>
        </div>
        <?php
    }
}

