<?php

namespace Bricks;

use \Bricksforge\ProForms\Helper as Helper;

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

class Brf_Pro_Forms_Map extends \Bricks\Element
{

    public $category = 'bricksforge forms';
    public $name = 'brf-pro-forms-field-map';
    public $icon = 'fa-solid fa-map-location-dot';
    public $css_selector = '';
    public $scripts = [];
    public $nestable = false;

    public function get_label()
    {
        return esc_html__("Map", 'bricksforge');
    }

    public function enqueue_scripts()
    {
        wp_enqueue_script('bricksforge-elements');

        $provider = isset($this->settings['mapProvider']) ? $this->settings['mapProvider'] : 'openstreetmap';

        if ($provider === 'openstreetmap') {
            wp_enqueue_script('bricksforge-leaflet');
            wp_enqueue_style('bricksforge-leaflet');
        }
    }

    public function set_control_groups()
    {
        $this->control_groups['general'] = [
            'title'    => esc_html__('General', 'bricksforge'),
            'tab'      => 'content',
        ];
        $this->control_groups['map'] = [
            'title'    => esc_html__('Map Settings', 'bricksforge'),
            'tab'      => 'content',
        ];
        $this->control_groups['style'] = [
            'title'    => esc_html__('Style', 'bricksforge'),
            'tab'      => 'content',
        ];
        $this->control_groups['conditions'] = [
            'title'    => esc_html__('Conditions', 'bricksforge'),
            'tab'      => 'content',
        ];
        $this->control_groups['validation'] = [
            'title'    => esc_html__('Validation', 'bricksforge'),
            'tab'      => 'content',
        ];
    }

    public function set_controls()
    {
        $this->controls = array_merge($this->controls, Helper::get_default_controls('map'));

        // Map Provider
        $this->controls['mapProvider'] = [
            'group' => 'map',
            'label' => esc_html__('Map Provider', 'bricksforge'),
            'type' => 'select',
            'default' => 'openstreetmap',
            'options' => [
                'openstreetmap' => esc_html__('OpenStreetMap (Leaflet)', 'bricksforge'),
                'google' => esc_html__('Google Maps', 'bricksforge'),
            ],
            'description' => esc_html__('Select the map provider. Google Maps requires an API key configured in Bricksforge settings.', 'bricksforge'),
        ];

        // Google Maps API Key Info
        $this->controls['googleMapsInfo'] = [
            'group' => 'map',
            'type' => 'info',
            'content' => Helper::check_google_maps_configured()
                ? esc_html__('Google Maps API key is configured.', 'bricksforge')
                : esc_html__('Google Maps API key is not configured. Please add it in Bricksforge > Pro Forms settings.', 'bricksforge'),
            'required' => [['mapProvider', '=', 'google']],
        ];

        // Default Latitude
        $this->controls['defaultLat'] = [
            'group' => 'map',
            'label' => esc_html__('Default Latitude', 'bricksforge'),
            'type' => 'text',
            'default' => '51.505',
            'description' => esc_html__('Default latitude for the map center.', 'bricksforge'),
        ];

        // Default Longitude
        $this->controls['defaultLng'] = [
            'group' => 'map',
            'label' => esc_html__('Default Longitude', 'bricksforge'),
            'type' => 'text',
            'default' => '-0.09',
            'description' => esc_html__('Default longitude for the map center.', 'bricksforge'),
        ];

        // Default Zoom
        $this->controls['defaultZoom'] = [
            'group' => 'map',
            'label' => esc_html__('Default Zoom', 'bricksforge'),
            'type' => 'number',
            'default' => 13,
            'min' => 1,
            'max' => 20,
            'description' => esc_html__('Default zoom level (1-20).', 'bricksforge'),
        ];

        // Allow Search
        $this->controls['allowSearch'] = [
            'group' => 'map',
            'label' => esc_html__('Allow Search', 'bricksforge'),
            'type' => 'checkbox',
            'description' => esc_html__('Enable address search functionality.', 'bricksforge'),
        ];

        // Search Placeholder
        $this->controls['searchPlaceholder'] = [
            'group' => 'map',
            'label' => esc_html__('Search Placeholder', 'bricksforge'),
            'type' => 'text',
            'default' => esc_html__('Search address...', 'bricksforge'),
            'required' => [['allowSearch', '=', true]],
        ];

        // Allow Marker Drag
        $this->controls['allowMarkerDrag'] = [
            'group' => 'map',
            'label' => esc_html__('Allow Marker Drag', 'bricksforge'),
            'type' => 'checkbox',
            'description' => esc_html__('Allow users to reposition the marker by dragging.', 'bricksforge'),
        ];

        // Variable Usage Info
        $this->controls['variableUsageInfo'] = [
            'group' => 'map',
            'type' => 'info',
            'content' => '<strong>' . esc_html__('Variable Usage', 'bricksforge') . '</strong><br><br>' .
                '<code>{{field_id}}</code> - ' . esc_html__('Full object (for ACF, Metabox, etc.)', 'bricksforge') . '<br>' .
                '<code>{{field_id:address}}</code> - ' . esc_html__('Address only', 'bricksforge') . '<br>' .
                '<code>{{field_id:lat}}</code> - ' . esc_html__('Latitude', 'bricksforge') . '<br>' .
                '<code>{{field_id:lng}}</code> - ' . esc_html__('Longitude', 'bricksforge') . '<br>' .
                '<code>{{field_id:coords}}</code> - ' . esc_html__('Format "lat,lng"', 'bricksforge') . '<br>' .
                '<code>{{field_id:zoom}}</code> - ' . esc_html__('Zoom level', 'bricksforge'),
        ];

        // Map Height
        $this->controls['mapHeight'] = [
            'group' => 'map',
            'label' => esc_html__('Map Height', 'bricksforge'),
            'type' => 'number',
            'units' => true,
            'default' => '400px',
            'css' => [
                [
                    'selector' => '.brf-map-container',
                    'property' => 'height',
                ]
            ],
        ];

        // Map Border Radius
        $this->controls['mapBorderRadius'] = [
            'group' => 'map',
            'label' => esc_html__('Border Radius', 'bricksforge'),
            'type' => 'border',
            'css' => [
                [
                    'selector' => '.brf-map-container',
                    'property' => 'border',
                ]
            ],
        ];

        // Style Controls - Search Input
        $this->controls['searchInputBackground'] = [
            'group' => 'style',
            'label' => esc_html__('Search Input Background', 'bricksforge'),
            'type' => 'background',
            'css' => [
                [
                    'property' => 'background',
                    'selector' => '.brf-map-search-input',
                ],
            ],
        ];

        $this->controls['searchInputTypography'] = [
            'group' => 'style',
            'label' => esc_html__('Search Input Typography', 'bricksforge'),
            'type' => 'typography',
            'css' => [
                [
                    'property' => 'typography',
                    'selector' => '.brf-map-search-input',
                ],
            ],
        ];

        $this->controls['searchInputPadding'] = [
            'group' => 'style',
            'label' => esc_html__('Search Input Padding', 'bricksforge'),
            'type' => 'spacing',
            'css' => [
                [
                    'property' => 'padding',
                    'selector' => '.brf-map-search-input',
                ],
            ],
        ];

        $this->controls['searchInputBorder'] = [
            'group' => 'style',
            'label' => esc_html__('Search Input Border', 'bricksforge'),
            'type' => 'border',
            'css' => [
                [
                    'property' => 'border',
                    'selector' => '.brf-map-search-input',
                ],
            ],
        ];

        $this->controls['searchInputBoxShadow'] = [
            'group' => 'style',
            'label' => esc_html__('Search Input Box Shadow', 'bricksforge'),
            'type' => 'box-shadow',
            'css' => [
                [
                    'property' => 'box-shadow',
                    'selector' => '.brf-map-search-input',
                ],
            ],
        ];

        $this->controls['searchInputPlaceholderColor'] = [
            'group' => 'style',
            'label' => esc_html__('Placeholder Color', 'bricksforge'),
            'type' => 'color',
            'css' => [
                [
                    'property' => 'color',
                    'selector' => '.brf-map-search-input::placeholder',
                ],
                [
                    'property' => 'color',
                    'selector' => '.brf-map-search-input::-webkit-input-placeholder',
                ],
            ],
        ];

        // Style Controls - Search Results Dropdown (OpenStreetMap only)
        $this->controls['searchResultsBackground'] = [
            'group' => 'style',
            'label' => esc_html__('Search Results Background', 'bricksforge'),
            'type' => 'color',
            'css' => [
                [
                    'property' => 'background-color',
                    'selector' => '.brf-map-search-results',
                ],
            ],
            'required' => [['mapProvider', '=', 'openstreetmap']],
        ];

        $this->controls['searchResultsTypography'] = [
            'group' => 'style',
            'label' => esc_html__('Search Results Typography', 'bricksforge'),
            'type' => 'typography',
            'css' => [
                [
                    'property' => 'typography',
                    'selector' => '.brf-map-search-result-item',
                ],
            ],
            'required' => [['mapProvider', '=', 'openstreetmap']],
        ];

        $this->controls['searchResultsBorder'] = [
            'group' => 'style',
            'label' => esc_html__('Search Results Border', 'bricksforge'),
            'type' => 'border',
            'css' => [
                [
                    'property' => 'border',
                    'selector' => '.brf-map-search-results',
                ],
            ],
            'required' => [['mapProvider', '=', 'openstreetmap']],
        ];

        $this->controls['searchResultsBoxShadow'] = [
            'group' => 'style',
            'label' => esc_html__('Search Results Box Shadow', 'bricksforge'),
            'type' => 'box-shadow',
            'css' => [
                [
                    'property' => 'box-shadow',
                    'selector' => '.brf-map-search-results',
                ],
            ],
            'required' => [['mapProvider', '=', 'openstreetmap']],
        ];

        $this->controls['searchResultItemHoverBg'] = [
            'group' => 'style',
            'label' => esc_html__('Search Result Hover Background', 'bricksforge'),
            'type' => 'color',
            'css' => [
                [
                    'property' => 'background-color',
                    'selector' => '.brf-map-search-result-item:hover',
                ],
            ],
            'required' => [['mapProvider', '=', 'openstreetmap']],
        ];

        // Style Controls - Map Container
        $this->controls['mapContainerBoxShadow'] = [
            'group' => 'style',
            'label' => esc_html__('Map Box Shadow', 'bricksforge'),
            'type' => 'box-shadow',
            'css' => [
                [
                    'property' => 'box-shadow',
                    'selector' => '.brf-map-container',
                ],
            ],
        ];

        $this->controls = array_merge($this->controls, Helper::get_condition_controls());
        $this->controls = array_merge($this->controls, Helper::get_advanced_controls());
        $this->controls = array_merge($this->controls, Helper::get_validation_controls());
    }

    public function render()
    {
        $settings = $this->settings;
        $parent_settings = Helper::get_nestable_parent_settings($this->element) ? Helper::get_nestable_parent_settings($this->element) : [];
        $random_id = Helpers::generate_random_id(false);
        $id = $this->id ? $this->id : false;

        if (isset($settings['id']) && $settings['id']) {
            $id = $settings['id'];
        }

        $label = isset($settings['label']) ? $settings['label'] : false;
        $required = isset($settings['required']) ? $settings['required'] : false;

        $show_labels = true;
        if (isset($parent_settings) && !empty($parent_settings) && !isset($parent_settings['showLabels'])) {
            $show_labels = false;
        }

        if (isset($settings['showLabel']) && $settings['showLabel']) {
            $show_labels = true;
        }

        $value = isset($settings['value']) ? bricks_render_dynamic_data($settings['value']) : '';

        // Map settings
        $map_provider = isset($settings['mapProvider']) ? $settings['mapProvider'] : 'openstreetmap';
        $default_lat = isset($settings['defaultLat']) ? $settings['defaultLat'] : '51.505';
        $default_lng = isset($settings['defaultLng']) ? $settings['defaultLng'] : '-0.09';
        $default_zoom = isset($settings['defaultZoom']) ? intval($settings['defaultZoom']) : 13;
        $allow_search = isset($settings['allowSearch']) && $settings['allowSearch'];
        $search_placeholder = isset($settings['searchPlaceholder']) ? $settings['searchPlaceholder'] : esc_html__('Search address...', 'bricksforge');
        $allow_marker_drag = isset($settings['allowMarkerDrag']) && $settings['allowMarkerDrag'];
        $map_height = isset($settings['mapHeight']) ? $settings['mapHeight'] : '400px';

        // Get Google Maps API key if provider is Google
        $api_key = '';
        if ($map_provider === 'google') {
            $api_key = Helper::get_google_maps_api_key();
        }

        /**
         * Wrapper
         */
        $this->set_attribute('_root', 'class', 'pro-forms-builder-field');
        $this->set_attribute('_root', 'class', 'form-group');
        $this->set_attribute('_root', 'data-element-id', $this->id);

        // Post Context
        if (isset($settings['postContext'])) {
            $this->set_attribute('_root', 'data-context', bricks_render_dynamic_data($settings['postContext']));
        }

        if ($id !== $this->id) {
            $this->set_attribute('_root', 'data-custom-id', $id);
        }

        if (isset($settings['cssClass']) && !empty($settings['cssClass'])) {
            $this->set_attribute('_root', 'class', $settings['cssClass']);
        }

        // Conditions
        if (isset($settings['hasConditions']) && isset($settings['conditions']) && $settings['conditions']) {
            $this->set_attribute('_root', 'data-brf-conditions', json_encode($settings['conditions']));
        }
        if (isset($settings['conditionsRelation']) && $settings['conditionsRelation']) {
            $this->set_attribute('_root', 'data-brf-conditions-relation', $settings['conditionsRelation']);
        }

        // Required Asterisk
        if (isset($parent_settings['requiredAsterisk']) && $parent_settings['requiredAsterisk'] == true && $required) {
            $this->set_attribute("label", 'class', 'required');
        }

        /**
         * Map Field Wrapper
         */
        $this->set_attribute('map_field', 'class', 'brf-map-field');
        $this->set_attribute('map_field', 'data-provider', esc_attr($map_provider));
        $this->set_attribute('map_field', 'data-default-lat', esc_attr($default_lat));
        $this->set_attribute('map_field', 'data-default-lng', esc_attr($default_lng));
        $this->set_attribute('map_field', 'data-default-zoom', esc_attr($default_zoom));
        $this->set_attribute('map_field', 'data-allow-search', $allow_search ? 'true' : 'false');
        $this->set_attribute('map_field', 'data-allow-drag', $allow_marker_drag ? 'true' : 'false');

        if ($map_provider === 'google' && $api_key) {
            $this->set_attribute('map_field', 'data-api-key', esc_attr($api_key));
        }

        /**
         * Hidden Input Field
         */
        $this->set_attribute('field', 'type', 'hidden');
        $this->set_attribute('field', 'id', 'form-field-' . $id);
        $this->set_attribute('field', 'name', 'form-field-' . $id);
        $this->set_attribute('field', 'class', 'brf-map-value');
        $this->set_attribute('field', 'data-label', $label);

        if ($required) {
            $this->set_attribute('field', 'required', $required);
        }

        if ($value) {
            $this->set_attribute('field', 'value', esc_attr($value));
        }

        // Validation
        $validation = isset($settings['validation']) ? $settings['validation'] : false;

        if ($validation) {
            $this->set_attribute('field', 'data-validation', json_encode($validation));

            if (isset($settings['enableLiveValidation']) && $settings['enableLiveValidation'] == true) {
                $this->set_attribute('field', 'data-live-validation', 'true');
            }

            if (isset($settings['showValidationMessage']) && $settings['showValidationMessage'] == true) {
                $this->set_attribute('field', 'data-show-validation-message', 'true');
            }

            if (isset($settings['showMessageBelowField']) && $settings['showMessageBelowField'] == true) {
                $this->set_attribute('field', 'data-show-message-below-field', 'true');
            }
        }

?>
        <div <?php echo $this->render_attributes('_root'); ?>>
            <?php if ($label && $show_labels) : ?>
                <label <?php echo $this->render_attributes('label'); ?> for="form-field-<?php echo esc_attr($id); ?>">
                    <?php echo wp_kses_post($label); ?>
                </label>
            <?php endif; ?>

            <div <?php echo $this->render_attributes('map_field'); ?>>
                <?php if ($allow_search) : ?>
                    <div class="brf-map-search">
                        <input type="text" class="brf-map-search-input" placeholder="<?php echo esc_attr($search_placeholder); ?>" autocomplete="off">
                    </div>
                <?php endif; ?>

                <?php if (bricks_is_builder() || bricks_is_builder_call()) : ?>
                    <div class="brf-map-container brf-map-placeholder">
                        <div class="brf-map-placeholder-content">
                            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                <circle cx="12" cy="10" r="3"></circle>
                            </svg>
                            <span class="brf-map-placeholder-label"><?php echo $map_provider === 'google' ? 'Google Maps' : 'OpenStreetMap'; ?></span>
                        </div>
                    </div>
                <?php else : ?>
                    <div class="brf-map-container"></div>
                <?php endif; ?>
            </div>

            <input <?php echo $this->render_attributes('field'); ?>>
        </div>
<?php
    }
}
