<?
namespace admin\factory;

class ShopProductSet
{
  // zapisywanie kompletu produktów
  static public function save( int $set_id, string $name, string $status, $set_products_id )
  {
    global $mdb;

    if ( !$set_id )
    {
      $mdb -> insert('pp_shop_product_sets', [
        'name' => $name,
        'status' => 'on' === $status ? 1 : 0
      ] );

      $id = $mdb -> id();

      if ( $set_products_id == null )
        $not_in = [ 0 ];
      elseif ( !is_array( $set_products_id ) )
        $not_in = [ 0, $set_products_id ];
      elseif ( is_array( $set_products_id ) )
        $not_in = $set_products_id;

      foreach ( $not_in as $product_id )
      {
        if ( $product_id != 0 )
          $mdb -> insert( 'pp_shop_product_sets_products', [ 'set_id' => $id, 'product_id' => $product_id ] );
      }

      \S::delete_dir('../temp/');
      \S::delete_dir('../thumbs/');

      return $id;
    }
    else
    {
      $mdb -> update('pp_shop_product_sets', [
        'name' => $name,
        'status' => 'on' === $status ? 1 : 0
      ], [
        'id' => (int)$set_id,
      ] );

      $mdb -> delete( 'pp_shop_product_sets_products', [ 'set_id' => $set_id ] );

      if ( $set_products_id == null )
        $not_in = [ 0 ];
      elseif ( !is_array( $set_products_id ) )
        $not_in = [ 0, $set_products_id ];
      elseif ( is_array( $set_products_id ) )
        $not_in = $set_products_id;

      foreach ( $not_in as $product_id )
      {
        if ( $product_id != 0 )
          $mdb -> insert( 'pp_shop_product_sets_products', [ 'set_id' => $set_id, 'product_id' => $product_id ] );
      }

      \S::delete_dir('../temp/');
      \S::delete_dir('../thumbs/');

      return $set_id;
    }
  }
}