<?php
namespace admin\factory;

class Scontainers
{
  public static function container_delete( $container_id )
  {
    global $mdb;
    return $mdb -> delete( 'pp_scontainers', [ 'id' => (int)$container_id ] );
  }

  public static function container_save( $container_id, $title, $text, $status, $show_title )
  {
    global $mdb;

    if ( !$container_id )
    {
      $mdb -> insert( 'pp_scontainers', [
        'status' => $status == 'on' ? 1 : 0,
        'show_title' => $show_title == 'on' ? 1 : 0
      ] );

      $id = $mdb -> id();

      if ( $id )
      {
        foreach ( $title as $key => $val )
        {
          $mdb -> insert( 'pp_scontainers_langs', [
            'container_id' => (int)$id,
            'lang_id' => $key,
            'title' => $title[$key],
            'text' => $text[$key]
          ] );
        }

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

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

      foreach ( $title as $key => $val )
      {
        if ( $translation_id = $mdb -> get( 'pp_scontainers_langs', 'id', [ 'AND' => [ 'container_id' => $container_id, 'lang_id' => $key ] ] ) )
          $mdb -> update( 'pp_scontainers_langs', [
            'lang_id' => $key,
            'title' => $title[$key],
            'text' => $text[$key]
          ], [
            'id' => $translation_id
          ] );
        else
          $mdb -> insert( 'pp_scontainers_langs', [
            'container_id' => (int)$container_id,
            'lang_id' => $key,
            'title' => $title[$key],
            'text' => $text[$key]
          ] );
      }

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

      return $container_id;
    }
  }

  public static function container_details( $container_id )
  {
    global $mdb;

    $container = $mdb -> get( 'pp_scontainers', '*', [ 'id' => (int)$container_id ] );

    $results = $mdb -> select( 'pp_scontainers_langs', '*', [ 'container_id' => (int)$container_id ] );
    if ( is_array( $results ) ) foreach ( $results as $row )
      $container['languages'][ $row['lang_id'] ] = $row;

    return $container;
  }
}
