<?php
namespace admin\factory;

class Newsletter
{
  public static function is_admin_template( $template_id )
  {
    global $mdb;
    return $mdb -> get( 'pp_newsletter_templates', 'is_admin', [ 'id' => (int)$template_id ] );
  }
  
  public static function newsletter_template_delete( $template_id )
  {
    global $mdb;
    return $mdb -> delete( 'pp_newsletter_templates', [ 'id' => (int)$template_id ] );
  }
  
  public static function send( $dates, $template )
  {
    global $mdb;
    
    $results = $mdb -> select( 'pp_newsletter', 'email', [ 'status' => 1 ] );
    if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
    {
      $mdb -> insert( 'pp_newsletter_send', [
                'email'       => $row,
                'dates'       => $dates,
                'id_template' => $template ? $template : null
              ] );
    }
    return true;    
  }
  
  public static function email_template_detalis ($id_template)
  {
    global $mdb;
    
    $result = $mdb -> get ('pp_newsletter_templates', '*', [ 'id' => (int)$id_template ]  );
    return $result;
  }
  
  public static function template_save( $id, $name, $text )
  {
    global $mdb;
    
    if ( !$id )
    {
      if ( $mdb -> insert( 'pp_newsletter_templates', [
              'name' => $name,
              'text' => $text
      ] ) )
      {
        \S::delete_dir( '../temp/' );
        return $mdb -> id();
      }
    }
    else
    {
      $mdb -> update( 'pp_newsletter_templates', [
              'name' => $name,
              'text' => $text
            ], [
              'id' => (int)$id
            ] );

      \S::delete_dir( '../temp/' );
      return $id;
    }
  }
  
  public static function templates_list()
  {
    global $mdb;
    return $mdb -> select( 'pp_newsletter_templates', '*', [ 'is_admin' => 0, 'ORDER' => [ 'name' => 'ASC' ] ] );
  }
}
