<?php

namespace admin\factory;

class Banners
{
  public static function banner_delete( $banner_id )
  {
    global $mdb;

    $result = $mdb -> delete( 'pp_banners', [ 'id' => (int) $banner_id ] );
    \S::delete_dir( '../temp/' );

    return $result;
  }

  public static function banner_save( $banner_id, $name, $status, $date_start, $date_end, $home_page, $src, $url, $html, $text )
  {
    global $mdb;

    if ( !$banner_id )
    {
      $mdb -> insert( 'pp_banners', [
                      'name'       => $name,
                      'status'     => $status == 'on' ? 1 : 0,
                      'date_start' => $date_start != '' ? $date_start : null,
                      'date_end'   => $date_end != '' ? $date_end : null,
                      'home_page'  => $home_page == 'on' ? 1 : 0
              ] );

      $id = $mdb -> id();

      if ( $id )
      {
        foreach ( $src as $key => $val )
        {
          $mdb -> insert( 'pp_banners_langs', [
            'id_banner' => (int)$id,
            'id_lang' => $key,
            'src' => $src[$key],
            'url' => $url[$key],
            'html' => $html[$key],
            'text' => $text[$key]
          ] );
        }

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

        return $id;
      }
    }
    else
    {
      $mdb -> update( 'pp_banners', [
        'name'       => $name,
        'status'     => $status == 'on' ? 1 : 0,
        'date_start' => $date_start != '' ? $date_start : null,
        'date_end'   => $date_end != '' ? $date_end : null,
        'home_page'  => $home_page == 'on' ? 1 : 0
        ], [
        'id' => (int)$banner_id
      ] );

      foreach ( $src as $key => $val )
      {
        if ( $translation_id = $mdb -> get( 'pp_banners_langs', 'id', [ 'AND' => [ 'banner_id' => $banner_id, 'lang_id' => $key ] ] ) )
          $mdb -> update( 'pp_banners_langs', [
            'id_lang' => $key,
            'src' => $src[$key],
            'url' => $url[$key],
            'html' => $html[$key],
            'text' => $text[$key]
          ], [
            'id' => $translation_id
          ] );
        else
          $mdb -> insert( 'pp_banners_langs', [
            'id_banner' => (int)$banner_id,
            'id_lang' => $key,
            'src' => $src[$key],
            'url' => $url[$key],
            'html' => $html[$key],
            'text' => $text[$key]
          ] );
      }

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

      return $banner_id;
    }
    return false;
  }

  public static function banner_details( $id_banner )
  {
    global $mdb;

    $banner = $mdb -> get( 'pp_banners', '*', [ 'id' => (int)$id_banner ] );

    $results = $mdb -> select( 'pp_banners_langs', '*', [ 'id_banner' => (int)$id_banner ] );
    if ( is_array( $results ) ) foreach ( $results as $row )
      $banner['languages'][$row['id_lang']] = $row;

    return $banner;
  }

}
?>