<?php
namespace front\factory;
class ShopTransport
{
  static public function get_apilo_carrier_account_id( $transport_method_id )
  {
    global $mdb;
    $repo = new \Domain\Transport\TransportRepository($mdb);
    return $repo->getApiloCarrierAccountId($transport_method_id);
  }

  public static function transport_methods( $basket, $coupon )
  {
    global $mdb, $settings;

    $cacheHandler = new \Shared\Cache\CacheHandler();
    $cacheKey = "\front\factory\ShopTransport::transport_methods";

    $objectData = $cacheHandler -> get( $cacheKey );

    if ( !$objectData )
    {
      $repo = new \Domain\Transport\TransportRepository($mdb);
      $transports_tmp = $repo->allActive();

      $cacheHandler -> set( $cacheKey, $transports_tmp );
    }
    else
    {
      $transports_tmp = unserialize( $objectData );
    }

    $wp_summary = \front\factory\ShopBasket::summary_wp( $basket );

    foreach ( $transports_tmp as $tr )
    {
      if ( $tr['max_wp'] == null )
        $transports[] = $tr;
      elseif ( $tr['max_wp'] != null and $wp_summary <= $tr['max_wp'] )
        $transports[] = $tr;
    }


    if ( \Shared\Helpers\Helpers::normalize_decimal( \front\factory\ShopBasket::summary_price( $basket, $coupon ) ) >= \Shared\Helpers\Helpers::normalize_decimal( $settings['free_delivery'] ) )
    {
      for ( $i = 0; $i < count( $transports ); $i++ ){
        if($transports[ $i ]['delivery_free'] == 1) {
          $transports[ $i ]['cost'] = 0.00;
        }
      }
    }

    return $transports;
  }

  public static function transport_cost( $transport_id )
  {
      global $mdb;

      $cacheHandler = new \Shared\Cache\CacheHandler();
      $cacheKey = 'transport_cost_' . $transport_id;
      $objectData = $cacheHandler->get( $cacheKey );

      if ( !$objectData )
      {
        $repo = new \Domain\Transport\TransportRepository($mdb);
        $cost = $repo->getTransportCost($transport_id);

        $cacheHandler->set( $cacheKey, $cost );
      }
      else
      {
        return unserialize( $objectData );
      }
      return $cost;
  }

  public static function transport( $transport_id )
  {
    global $mdb;

    $cacheHandler = new \Shared\Cache\CacheHandler();
    $cacheKey = 'transport' . $transport_id;
    $objectData = $cacheHandler->get( $cacheKey );

    if ( !$objectData )
    {
      $repo = new \Domain\Transport\TransportRepository($mdb);
      $transport = $repo->findActiveById($transport_id);

      $cacheHandler->set( $cacheKey, $transport );
    }
    else
    {
      return unserialize( $objectData );
    }
    return $transport;
  }
}
