<?php
namespace front\factory;

class ShopPaymentMethod
{
  // get_sellasist_payment_method_id
  static public function get_sellasist_payment_method_id( $payment_method_id ) {
    global $mdb;
    return $mdb -> get( 'pp_shop_payment_methods', 'sellasist_payment_type_id', [ 'id' => $payment_method_id ] );
  }

  // get_apilo_payment_method_id
  static public function get_apilo_payment_method_id( $payment_method_id ) {
    global $mdb;
    return $mdb -> get( 'pp_shop_payment_methods', 'apilo_payment_type_id', [ 'id' => $payment_method_id ] );
  }

  public static function payment_methods_by_transport( $transport_method_id )
  {
    global $mdb, $settings;

    if ( !$payments = \Cache::fetch( 'payment_methods_by_transport' . $transport_method_id ) )
    {
      $results = $mdb -> query( 'SELECT '
                                    . 'pspm.id, name, description '
                                  . 'FROM '
                                    . 'pp_shop_payment_methods AS pspm '
                                    . 'INNER JOIN pp_shop_transport_payment_methods AS pstpm ON pstpm.id_payment_method = pspm.id '
                                  . 'WHERE '
                                      . 'status = 1 '
                                    . 'AND '
                                      . 'id_transport = ' . $transport_method_id ) -> fetchAll();
      if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
        $payments[] = $row;

      \Cache::store( 'payment_methods_by_transport' . $transport_method_id, $payments );
    }

    return $payments;
  }

  public static function is_payment_active( $payment_method_id )
  {
    global $mdb;
    return $mdb -> get( 'pp_shop_payment_methods', 'status', [ 'id' => $payment_method_id ] );
  }

  public static function payment_method( $payment_method_id )
  {
    global $mdb;

    if ( !$payment_method = \Cache::fetch( 'payment_method' . $payment_method_id ) )
    {
      $payment_method = $mdb -> get( 'pp_shop_payment_methods', '*', [
                        'AND' => [
                            'id' => $payment_method_id,
                            'status' => 1
                        ] ] );

      \Cache::store( 'payment_method' . $payment_method_id, $payment_method );
    }
    return $payment_method;
  }

  public static function payment_methods()
  {
    global $mdb;

    if ( !$payment_methods = \Cache::fetch( 'payment_methods' ) )
    {
      $results = $mdb -> select( 'pp_shop_payment_methods', '*', [ 'status' => 1 ] );
      if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
        $payment_methods[] = $row;

      \Cache::store( 'payment_methods', $payment_methods );
    }

    return $payment_methods;
  }
}
