<?php
namespace Bricks;
if ( ! defined( 'ABSPATH' ) ) exit;

class Bc_Image_Hotspots extends Element {
  public $category     = 'Next Bricks - Medias';
  public $name         = 'imagehotspots';
  public $icon         = 'ti-notepad';
  public $nestable     = true;

public function get_label() {
    return esc_html__( 'Image Hotspots', 'bricks' );
}

public function set_controls() {
  $this->controls['image'] = [
    'hasDynamicData' => true,
    'tab' => 'content',
    'label' => esc_html__( 'Image', 'bricks' ),
    'type' => 'image',
    'default' => [
      'url' => 'https://images.pexels.com/photos/45246/green-tree-python-python-tree-python-green-45246.jpeg?auto=compress&cs=tinysrgb&w=600',
    ],
  ];
  $this->controls['alt'] = [
    'tab' => 'content',
    'label' => esc_html__( 'Alt text', 'bricks' ),
    'type' => 'text',
    'inline' => true,
  ];
  $this->controls['_objectFit'] = [
    'label'   => esc_html__( 'Object fit', 'bricks' ),
    'type'    => 'select',
    'inline'  => true,
    'options' => $this->control_options['objectFit'],
    'css' => [
      [
        'property' => 'object-fit',
        'selector' => '.bc-image-hotspots__img',
      ],
    ],
    'default' => 'cover',
];
  $this->controls['_objectPosition'] = [
    'tab' => 'content',
    'label'  => esc_html__( 'Object position', 'bricks' ),
    'type'   => 'text',
    'inline' => true,
    'dd'     => false,
    'css' => [
      [
        'property' => 'object-position',
        'selector' => '.bc-image-hotspots__img',
      ],
    ],
  ];
  $this->controls['imageFilters'] = [
    'tab' => 'content',
    'label' => esc_html__( 'Filters', 'bricks' ),
    'type' => 'filters',
    'inline' => true,
    'css' => [
      [
        'property' => 'filter',
        'selector' => '.bc-image-hotspots__img',
      ],
    ],
  ];

  $this->controls['styleSeparator'] = [
    'label'      => esc_html__( 'Style', 'bricks' ),
    'type'       => 'separator',
];
$this->controls['width'] = [
    'hasDynamicData' => false,
    'tab' => 'content',
    'label' => esc_html__( 'Width', 'bricks' ),
    'type'  => 'number',
    'units' => true,
    'inline' => true,
    'css' => [
      [
        'property' => 'width',
        'selector' => '',
      ]
    ],
    'default' => '500px',
];
$this->controls['height'] = [
    'hasDynamicData' => false,
    'tab' => 'content',
    'label' => esc_html__( 'Height', 'bricks' ),
    'type'  => 'number',
    'units' => true,
    'inline' => true,
    'css' => [
      [
        'property' => 'height',
        'selector' => '',
      ]
    ],
    'default' => '400px',
];
    $this->controls['background'] = [
        'hasDynamicData' => false,
        'tab' => 'content',
        'label' => esc_html__( 'Background', 'bricks' ),
        'type' => 'background',
        'inline' => true,
        'css' => [
          [
            'property' => 'background',
            'selector' => '',
          ]
        ],
      'default' => [
        'color' => [
          'hex' => '#ffffff',
        ],
      ],
    ];


  $this->controls['separator'] = [
    'label'      => esc_html__( 'Hotspots', 'bricks' ),
    'type'       => 'separator',
];
  $this->controls['_children'] = [
    'type'          => 'repeater',
    'titleProperty' => 'label',
    'items'         => 'children',
  ];
}

public function get_nestable_item() {
  return [
    'name'     => 'imagehotspot',
    'label'    => esc_html__( 'Hotspot', 'bricks' ),
    'children' => [
      [
        'name'     => 'heading',
        'label'    => esc_html__( 'Heading', 'bricks' ),
        'settings' => [
            'text' => esc_html__( 'Hotspot', 'bricks' ),
            'tag'  => 'span',
        ],
      ],

      [
        'name'     => 'block',
        'label'    => esc_html__( 'Tooltip', 'bricks' ),
        'settings' => [
            '_hidden' => [
              '_cssClasses' => 'bc-image-hotspots__tooltip',
          ],
        ],
        'children' => [
          [
            'name'     => 'heading',
            'label'    => esc_html__( 'Heading', 'bricks' ),
            'settings' => [
                'text' => esc_html__( 'Heading', 'bricks' ),
                'tag'  => 'span',
            ],
          ]
        ],
      ],
    ],
  ];
}

public function get_nestable_children() {
  $children = [];

  for ( $i = 0; $i < 1; $i++ ) { /*Cantidad de item a generar*/
      $item = $this->get_nestable_item();

      // Replace {item_index} with $index
      $item       = json_encode( $item );
      $item       = str_replace( '{item_index}', $i + 1, $item );
      $item       = json_decode( $item, true );
      $children[] = $item;
  }

  return $children;
}

public function enqueue_scripts() {
  wp_enqueue_script( 'bc-image-hotspots', NEXTBRICKS_PLUGIN_URL . 'elements/js/bc_image_hotspots.min.js', array('bricks-scripts'), NEXTBRICKS_VERSION, false);
}

public function render() {
    $settings = $this->settings;
    $width = 1260;  // Default width
    $height = 750;  // Default height

    $include_image = true;

    //Render dynamic data
    if (isset($settings['image']['useDynamicData'])) {
        $images = $this->render_dynamic_data_tag($settings['image']['useDynamicData'], 'image');
        if (!empty($images) && isset($images[0])) {
            $last_image = wp_get_attachment_url($images[0]);
            $attachment_id = attachment_url_to_postid($last_image);
            $image_metadata = wp_get_attachment_metadata($attachment_id);
            
            if ($image_metadata && isset($image_metadata['width']) && isset($image_metadata['height'])) {
                $width = $image_metadata['width'];
                $height = $image_metadata['height'];
            }
        }
    }
    //Render normal image
    else if (isset($settings['image']['url'])) {
        $last_image = $settings['image']['url'];
        $image_dimensions = @getimagesize($last_image);
        
        if ($image_dimensions !== false) {
            $width = $image_dimensions[0];
            $height = $image_dimensions[1];
        }
    }
    //Render default
    else {
        $include_image = false;
    }

    // Ensure we have valid dimensions
    if ($width <= 0 || $height <= 0) {
        $width = 1260;  // Fallback width
        $height = 750;  // Fallback height
    }

    $alt = !empty($settings['alt']) ? "alt='{$settings['alt']}'" : '';

    $this->set_attribute('_root', 'class', 'bc-image-hotspots');

    if (strpos($last_image, 'cloudinary.com') !== false) {
      $src_decoding = 'decoding="async"';
    } else {
        $src_decoding = '';
    }

    $output = "<div {$this->render_attributes('_root')}>";
    if ($include_image) {
      $output .= "<img class='bc-image-hotspots__img' src='$last_image' width='$width' height='$height' $alt $src_decoding>";
    }
    $output .= Frontend::render_children($this);
    $output .= '</div>';

    echo $output;
}
}