<?php
namespace front\Controllers;

class ShopProductController
{
  private $categoryRepository;

  public function __construct( \Domain\Category\CategoryRepository $categoryRepository )
  {
    $this->categoryRepository = $categoryRepository;
  }

  public function lazyLoadingProducts()
  {
    global $lang_id;

    $output = '';
    $categoryId = (int)\Shared\Helpers\Helpers::get( 'category_id' );
    $products_ids = $this->categoryRepository->productsId(
      $categoryId,
      $this->categoryRepository->getCategorySort( $categoryId ),
      $lang_id,
      8,
      (int)\Shared\Helpers\Helpers::get( 'offset' )
    );

    $productRepo = new \Domain\Product\ProductRepository( $GLOBALS['mdb'] );
    if ( is_array( $products_ids ) ): foreach ( $products_ids as $product_id ):
      $output .= \Shared\Tpl\Tpl::view( 'shop-product/product-mini', [
        'product' => $productRepo->findCached( $product_id, $lang_id )
      ] );
      endforeach;
    endif;

    echo json_encode( [ 'html' => $output ] );
    exit;
  }

  public function warehouseMessage()
  {
    global $lang_id;

    $values = json_decode( \Shared\Helpers\Helpers::get( 'values' ), true );

    $attributes = [];
    foreach ( $values as $key => $val )
    {
      if ( $key != 'product-id' and $key != 'quantity' )
        $attributes[] = $val;
    }

    $productRepo = new \Domain\Product\ProductRepository( $GLOBALS['mdb'] );
    $permutation = self::getPermutation( $attributes );
    $quantity = self::getPermutationQuantity( $values['product-id'], $permutation );
    global $settings;

    $result = [];
    if ( $quantity )
    {
      $msg = $productRepo->getWarehouseMessageNonzero( (int)$values['product-id'], $lang_id );
      if ( $msg )
        $result = [ 'msg' => $msg, 'quantity' => $quantity ];
      else if ( isset( $settings[ 'warehouse_message_nonzero_' . $lang_id ] ) && $settings[ 'warehouse_message_nonzero_' . $lang_id ] )
        $result = [ 'msg' => $settings[ 'warehouse_message_nonzero_' . $lang_id ], 'quantity' => $quantity ];
    }
    else
    {
      $msg = $productRepo->getWarehouseMessageZero( (int)$values['product-id'], $lang_id );
      if ( $msg )
        $result = [ 'msg' => $msg, 'quantity' => $quantity ];
      else if ( isset( $settings[ 'warehouse_message_zero_' . $lang_id ] ) && $settings[ 'warehouse_message_zero_' . $lang_id ] )
        $result = [ 'msg' => $settings[ 'warehouse_message_zero_' . $lang_id ], 'quantity' => $quantity ];
    }

    echo json_encode( $result );
    exit;
  }

  public function drawProductAttributes()
  {
    global $lang_id;

    $selected_values = \Shared\Helpers\Helpers::get( 'selected_values' );

    // Sort by attribute ID to match permutation_hash order (generated with ksort)
    if ( is_array( $selected_values ) ) {
      usort( $selected_values, function ( $a, $b ) {
        return (int) explode( '-', $a )[0] - (int) explode( '-', $b )[0];
      } );
    }

    $combination = is_array( $selected_values ) ? implode( '|', $selected_values ) : '';

    $product_id = \Shared\Helpers\Helpers::get( 'product_id' );
    $productRepo = new \Domain\Product\ProductRepository( $GLOBALS['mdb'] );
    $product = $productRepo->findCached( $product_id, $lang_id );
    $product_data = $productRepo->getProductDataBySelectedAttributes( $product, $combination );

    echo json_encode( [ 'product_data' => $product_data ] );
    exit;
  }

  private static function getPermutation( $attributes )
  {
    if ( !is_array( $attributes ) || !count( $attributes ) ) return null;
    // Sort by attribute ID to match permutation_hash order (generated with ksort)
    usort( $attributes, function ( $a, $b ) {
      return (int) explode( '-', $a )[0] - (int) explode( '-', $b )[0];
    } );
    return implode( '|', $attributes );
  }

  private static function getPermutationQuantity( $productId, $permutation )
  {
    global $mdb;
    if ( !$permutation ) return $mdb->get( 'pp_shop_products', 'quantity', [ 'id' => $productId ] );
    $qty = $mdb->get( 'pp_shop_products', 'quantity', [ 'AND' => [ 'parent_id' => $productId, 'permutation_hash' => $permutation ] ] );
    if ( $qty !== null ) return $qty;
    return $mdb->get( 'pp_shop_products', 'quantity', [ 'id' => $productId ] );
  }
}
