<?
namespace admin\factory;
class ShopProducer
{
  static public function all()
  {
    global $mdb;
    return $mdb -> select( 'pp_shop_producer', '*', [ 'ORDER' => [ 'name' => 'ASC' ] ] );
  }

  static public function delete( int $producer_id )
  {
    global $mdb;
    return $mdb -> delete( 'pp_shop_producer', [ 'id' => $producer_id ] );
  }

  static public function save( $producer_id, $name, int $status, $img, $description, $meta_title )
  {
    global $mdb;

    if ( !$producer_id )
    {
      $mdb -> insert( 'pp_shop_producer', [
                        'name' => $name,
                        'status' => $status,
                        'img' => $img
                      ] );

      $id = $mdb -> id();

      foreach ( $description as $key => $val )
      {
        $mdb -> insert( 'pp_shop_producer_lang', [
            'producer_id' => $id,
            'lang_id' => $key,
            'description' => $val,
            'meta_title' => $meta_title[$key]
          ] );
      }

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

      return $id;
    }
    else
    {
      $mdb -> update( 'pp_shop_producer', [
                'name' => $name,
                'status' => $status,
                'img' => $img
              ], [
                'id' => (int) $producer_id
              ] );

      foreach ( $description as $key => $val )
      {
        if ( $translation_id = $mdb -> get( 'pp_shop_producer_lang', 'id', [ 'AND' => [ 'producer_id' => $producer_id, 'lang_id' => $key ] ] ) )
          $mdb -> update( 'pp_shop_producer_lang', [
            'description' => $val,
            'meta_title' => $meta_title[$key]
          ], [
            'id' => $translation_id
          ] );
        else
          $mdb -> insert( 'pp_shop_producer_lang', [
            'producer_id' => $producer_id,
            'lang_id' => $key,
            'description' => $val,
            'meta_title' => $meta_title[$key]
          ] );
      }

      \S::htacces();
      \S::delete_dir( '../temp/' );
      return $producer_id;
    }
    return false;
  }
}