<?php
namespace Nahiro\InteractiveMap\Admin;

class MapMetabox
{

    public function __construct()
    {
        add_action('add_meta_boxes', [$this, 'nahiroimap_add_metabox']);
        add_action('save_post', [$this, 'nahiroimap_metabox_save'], 10, 2);
    }

    /**
     * Call the metabox generator function and adds it to the post type
     *
     * @return void
     */
    public function nahiroimap_add_metabox()
    {
        // Map preview metabox
        add_meta_box(
            'nahiroimap_map_preview-meta_box', // Unique ID
            __('Map Preview', 'store-locations-map'), // Box title
            array($this, 'nahiroimap_map_preview_metabox_html'), // Content callback, must be of type callable
            'nahiroimap-maps' // Post type
        );
        // Post type data metabox
        add_meta_box(
            'nahiroimap_meta_box', // Unique ID
            __('Map Settings', 'store-locations-map'), // Box title
            array($this, 'nahiroimap_metabox_html'), // Content callback, must be of type callable
            'nahiroimap-maps' // Post type
        );
    }

    public function nahiroimap_metabox_h($post)
    {
        $map_id = get_post_meta($post->ID, '_map_id', true);
        ?>
        <h1><?php echo esc_html($map_id); ?></h1>
        <?php
    }

    /**
     * Saves the metabox data
     *
     * @param int $post_id
     * @return void
     */
    public function nahiroimap_metabox_save($post_id)
    {
		

        if (!isset( $_POST['nahiroimap_metabox_nonce'] ))
            return $post_id;
		
		$nonce =  sanitize_text_field( wp_unslash( $_POST['nahiroimap_metabox_nonce'] ) ) ;
		

        if (!wp_verify_nonce( $nonce , 'nahiroimap_metabox'))
            return $post_id;

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return $post_id;
		
		
		if (!isset( $_POST['post_type'] ))
            return $post_id;

        if ('nahiroimap-maps' != $_POST['post_type'])
            return $post_id;

        if (!current_user_can('edit_post', $post_id))
            return $post_id;

        // All checks passed, save the data
        $map_fields = [
            'map_id',
            'map_country',
            'map_width_cont',
            'map_width_cont_unit',
            'map_size_relation',
            'map_color',
            'map_color_mouse_over',
            'stroke_color',
            'stroke_width',
            'bound_velocity',
            'pines_text_color',
            'pines_display_shape',
            'pines_shape_color',
            'pin_width',
            'pin_padding_top',
            'pin_name_vertical_position',
            'pin_name_text',
            'pic_hide',
            'pic_position'
        ];

        foreach ($map_fields as $field) {
            if (isset($_POST[$field])) {
			   // Unsplash the $_POST value before sanitization
				$value =  sanitize_text_field( wp_unslash($_POST[$field]) );
							
				if (in_array($field, ['map_color', 'map_color_mouse_over', 'stroke_color', 'pines_text_color', 'pines_shape_color'])) {
					// Sanitize as a hex color
					$sanitized_value = sanitize_hex_color($value);
				} elseif (in_array($field, ['map_width_cont', 'map_size_relation', 'stroke_width', 'bound_velocity', 'pin_width', 'pin_padding_top', 'pin_name_vertical_position', 'pin_name_text'])) {
					// Sanitize as an integer
					$sanitized_value = intval($value);
				} else {
					// Sanitize as a generic text field
					$sanitized_value = sanitize_text_field($value);
				}

				// Only update post meta if the sanitized value is not null or empty
				if ($sanitized_value !== null && $sanitized_value !== '') {
					update_post_meta($post_id, '_' . $field, $sanitized_value);
				}
				
				
            }
        }

        if (isset($_POST['circle_coordinates'])) {
            $circle_coordinates = [];
			//unslash the array, sanitization comes later
			//sanitize the individual fields not the array
            foreach ( wp_unslash( $_POST['circle_coordinates'] )  as $circle_coordinate) {
                $arr_people = [];
                if (isset($circle_coordinate['people'])) {
                    foreach ($circle_coordinate['people'] as $card) {
                        $arr_people[] = [
                            'person_name' => sanitize_text_field($card['person_name']),
                            'person_image' => [
                                'url' => sanitize_text_field($card['person_image']['url'])
                            ],
                            'person_phone' => sanitize_text_field($card['person_phone']),
                            'person_email' => sanitize_text_field($card['person_email']),
                            'person_position' => sanitize_text_field($card['person_position'])
                        ];
                    }
                }
                $circle_coordinates[] = [
                    'cx' => intval($circle_coordinate['cx']),
                    'cy' => intval($circle_coordinate['cy']),
                    'circle_name' => sanitize_text_field($circle_coordinate['circle_name']),
                    'circle_hide' => sanitize_text_field($circle_coordinate['circle_hide']),
                    'circle_color' => sanitize_hex_color($circle_coordinate['circle_color']),
                    'circle_ratio' => intval($circle_coordinate['circle_ratio']),
                    'left' => intval($circle_coordinate['left']),
                    'top' => intval($circle_coordinate['top']),
                    'circle_image' => [
                        'url' => sanitize_text_field($circle_coordinate['circle_image']['url'])
                    ],
                    'people' => $arr_people
                ];
            }
            update_post_meta($post_id, '_circle_coordinates', $circle_coordinates);
        } else {
            delete_post_meta($post_id, '_circle_coordinates');
        }
    }

    /**
     * Retrieves the post saved data and displays it in the metabox html
     *
     * @param WP_Post $post
     * @return void
     */
    public function nahiroimap_metabox_html($post)
    {
        // Default values for circle_coordinates
        $arrval = [
            [
                'cx' => 465,
                'cy' => 300,
                'circle_name' => __('Alexander Platz', 'store-locations-map'),
                'circle_image' => [
                    'url' => NAHIROIMAP_PLUGIN_URL . 'assets/img/alexanderplatz.jpg'
                ],
                'circle_hide' => 'yes',
                'circle_color' => '#fff',
                'circle_ratio' => 1,
                'left' => 0,
                'top' => 70,
                'people' => [
                    [
                        'person_name' => __('Come Visit!', 'store-locations-map'),
                        'person_position' => __('"Impressive architecture!"', 'store-locations-map'),
                        'person_phone' => '+ 49 XX XXX XXXX',
                        'person_email' => 'mail@mail.com',
                        'person_image' => [
                            'url' => NAHIROIMAP_PLUGIN_URL . 'assets/img/placeholder.png'
                        ]
                    ]
                ]
            ],
            [
                'cx' => 246,
                'cy' => 197,
                'circle_name' => __('Hamburg Port', 'store-locations-map'),
                'circle_image' => [
                    'url' => NAHIROIMAP_PLUGIN_URL . 'assets/img/hamburg-port.jpg'
                ],
                'circle_hide' => 'yes',
                'circle_color' => '#fff',
                'circle_ratio' => 1,
                'left' => 0,
                'top' => 70,
                'people' => [
                    [
                        'person_name' => __('Bus tours everyday', 'store-locations-map'),
                        'person_position' => __('"Five stars sightseeing!"', 'store-locations-map'),
                        'person_phone' => '+49 XX XXX XXXX',
                        'person_email' => 'mail@mail.com',
                        'person_image' => [
                            'url' => NAHIROIMAP_PLUGIN_URL . 'assets/img/placeholder.png'
                        ]
                    ]
                ]
            ]
        ];

        $meta_fields = [
            'map_id' => '',
            'map_country' => get_option('nahiroimap_country_option', 'germany'),
            'map_width_cont' => 50,
            'map_width_cont_unit' => '%',
            'map_size_relation' => 100,
            'map_color' => '#F1ECE9',
            'map_color_mouse_over' => '#F1ECE9',
            'stroke_color' => '#E7E2DF',
            'stroke_width' => 2,
            'bound_velocity' => 1500,
            'pines_text_color' => '#837B72',
            'pines_display_shape' => '',
            'pines_shape_color' => '#89849b',
            'circle_coordinates' => $arrval,
            'pin_width' => 55,
            'pin_padding_top' => 0,
            'pin_name_vertical_position' => 0,
            'pin_name_text' => 16,
            'pic_hide' => 'n',
            'pic_position' => 'left'
        ];

        // Loop through each field and retrieve its meta value or use the default
        foreach ($meta_fields as $field => $default) {
            $$field = get_post_meta($post->ID, "_$field", true) ?: $default;
        }

        // Security nonce for verification
        wp_nonce_field('nahiroimap_metabox', 'nahiroimap_metabox_nonce');

        // Metabox HTML
        require_once 'metabox-html.php';
    }

    public function nahiroimap_map_preview_metabox_html($post)
    {
        require_once 'map-preview-metabox-html.php';
    }
}
