<?php
/**
 * OrokuBlocks WooCommerce Product
 * 
 * @package OrokuBlocks
 * @author OrokuBlocks (https://orokublocks.com/)
 * 
 * @since 1.0.0
 * 
 */

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

class OrokuBlocks_WoocommerceProduct_Widget extends OrokuBlocks_Widget {
  /**
   * Initialize property values
   * 
   * @since 1.0.0
   * 
   * @access protected
   */
  protected function initialize() {
    $this->widget_id = 'woocommerce_product';

    $this->defaults = [
      'theme'                       => 'light',
      'light_primary_color'         => '#00d4cf',
      'light_background_color'      => '#ffffff',
      'light_background_alt_color'  => '#f7f7f9',
      'light_line_color'            => '#c7cdd6',
      'light_text_color'            => '#22212c',
      'dark_primary_color'          => '#09dfb9',
      'dark_background_color'       => '#2b2a3b',
      'dark_background_alt_color'   => '#21202e',
      'dark_line_color'             => '#38374b',
      'dark_text_color'             => '#ffffff',
      'rating_color'                => '#ffd200',
      'rating_underline_color'      => '#d9d9d9',
      'use_plugin_font'             => true,
      'font_scale'                  => 1,
      'card_border_radius'          => 24,
      'card_image_border_radius'    => 14,
      'width'                       => 0,
      'image_url'                   => '',
      'gallery_image_urls'          => [],
      'title'                       => '',
      'title_link'                  => '',
      'subtitle'                    => '',
      'summary'                     => '',
      'score_value'                 => 5,
      'score_max_value'             => 5,
      'decimal_points'              => 0,
      'price'                       => '',
      'previous_price'              => '',
      'attributes_display'          => '',
      'attributes'                  => [],
      'colors'                      => [],
      'footer_left_title'           => 'SHARE:',
      'share_facebook_enabled'      => true,
      'share_x_enabled'             => true,
      'shortcode'                   => false
    ];

    $this->control_modules = [
      'woocommerce_product_content' => [],
      'woocommerce_product_attributes' => [],
      'share_actions' => [],
      'theme' => [],
      'theme_light' => [],
      'theme_dark' => [],
      'font' => [],
      'card' => [],
      'media_style' => [],
      'rating_style' => []
    ];

    $this->control_section_conditions = [
      'woocommerce_product_attributes' => [
        'condition'  => [
          'version'  => [ 'v1', 'v2', 'v3' ]
        ]
      ]
    ];
  }

  /**
   * Convert Elementor control settings structure to widget arguments structure
   * 
   * @since 1.0.0
   * 
   * @param array   $control_settings       Elementor control setting values.
   * @return array  $widget_args            Widget compatible arguments.
   */
  public function parseElementorControlSettings( $control_settings ) {
    $widget_args = parent::parseElementorControlSettings( $control_settings );

    // if user has not entered a product id
    if ( $widget_args['product_id'] === '' ) {
      $widget_args['orokublocks_widget_content_needs_user_input'] = true;
      
      return $widget_args;
    }

    $product = OrokuBlocks_Woocommerce::productGet( $widget_args['product_id'] );

    // // if a product with that id exists
    if ( $product ) {
      $widget_args['title'] = $product['name'];
      $widget_args['title_link'] = $product['permalink'];
      $widget_args['summary'] = $product['short_description'];
      $widget_args['image_url'] = $product['image_url'];

      if ( count( $product['gallery_image_urls'] ) > 0 ) {
        $gallery_image_urls = $product['gallery_image_urls'];

        if ( $product['image_url'] !== '' ) {
          $gallery_image_urls = array_merge( [ $product['image_url'] ] , $gallery_image_urls );
        }

        $widget_args['gallery_image_urls'] = $gallery_image_urls;
      }

      if ( array_key_exists( 'variation_price', $product ) ) {
        $widget_args['price'] = $product['variation_price'];
      } else {
        $widget_args['price'] = $product['price'];

        if ( $product['on_sale'] ) {
          $widget_args['previous_price'] = $product['regular_price'];
        }
      }
      $widget_args['score_value'] = $product['average_rating'];

      $categories = [];

      foreach ( $product['categories'] as $category ) {
        $categories[] = $category['name'];
      }

      $widget_args['subtitle'] = implode( ', ', $categories );

      // set attributes
      $widget_args['attributes'] = [];
      $widget_args['colors'] = [];
      
      if ( array_key_exists('attributes_display', $widget_args ) ) {
        $attribute_ids = explode( ',', $widget_args['attributes_display'] );
        // remove whitespace from attribute ids
        $attribute_ids = array_map(
          function ( $attribute_id ) {
            return trim( $attribute_id );
          },
          $attribute_ids
        );

        $attributes = array_filter(
          $product['attributes'],
          function ( $attribute, $attribute_id ) use ( $attribute_ids ) {
            return in_array( $attribute_id, $attribute_ids );
          },
          ARRAY_FILTER_USE_BOTH
        );

        $non_color_attributes = array_filter(
          $attributes,
          function ( $attribute ) {
            return $attribute['type'] !== 'color';
          }
        );

        $widget_args['attributes'] = $non_color_attributes;

        $color_attributes = array_filter(
          $attributes,
          function ( $attribute ) {
            return $attribute['type'] === 'color';
          }
        );

        if ( count( $color_attributes ) > 0 ) {
          $first_color = array_keys( $color_attributes )[0];
          $widget_args['colors'] = $color_attributes[$first_color];
        }
      }
    } else {
      $widget_args['orokublocks_widget_content_error'] = [
        'title' => __( 'WooCommerce Product', 'orokublocks' ),
        'text'  => __( 'A product with that id could not be found. Please ensure that the id you entered exactly matches the id of the product you want to display.', 'orokublocks' )
      ];
    }

    return $widget_args;
  }
}