<?php
namespace admin\controls;

class Newsletter
{
  public static function emails_list()
  {
    return \admin\view\Newsletter::emails_list();
  }

  public static function send()
  {
    if ( \admin\factory\Newsletter::send( \S::get( 'dates' ), \S::get('template')) )
      \S::alert( 'Newsletter został dodany do kolejki wysyłania.' );

    header( 'Location: /admin/newsletter/prepare/' );
    exit;
  }

  public static function prepare()
  {
    return \admin\view\Newsletter::prepare(
              \admin\factory\Newsletter::templates_list()
            );
  }

  public static function settings_save()
  {
    $settings = \admin\factory\Settings::settings_details();
    $values = json_decode( \S::get( 'values' ), true );

    \admin\factory\Settings::settings_update( 'newsletter_footer', $values['newsletter_footer'] );
    \admin\factory\Settings::settings_update( 'newsletter_header', $values['newsletter_header'] );

    \S::alert( 'Ustawienia zostały zapisane.' );

    echo json_encode( [ 'status' => 'ok', 'msg' => 'Ustawienia zostały zapisane.' ] );
    exit;
  }

  public static function settings()
  {
    return \admin\view\Newsletter::settings(
              \admin\factory\Settings::settings_details()
            );
  }

  public static function email_templates_user()
  {
    return \admin\view\Newsletter::email_templates_user();
  }

  public static function email_templates_admin()
  {
    return \admin\view\Newsletter::email_templates_admin();
  }

  public static function email_template_delete()
  {
    $is_admin = \admin\factory\Newsletter::is_admin_template( \S::get( 'id' ) );

    if ( !$is_admin and \admin\factory\Newsletter::newsletter_template_delete( \S::get( 'id' ) ) )
      \S::alert( 'Szablon newslettera został usunięty.' );

    if ( $is_admin )
      header( 'Location: /admin/newsletter/email_templates_admin/' );
    else
      header( 'Location: /admin/newsletter/email_templates_user/' );
    exit;
  }

  public static function email_template_edit()
  {
    return \admin\view\Newsletter::email_template_edit(
              \admin\factory\Newsletter::email_template_detalis(
                \S::get( 'id' )
                )
            );
  }

  public static function template_save()
  {
    $response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania wystąpił błąd. Proszę spróbować ponownie.' ];
    $values = json_decode( \S::get( 'values' ), true );

    if ( $id = \admin\factory\Newsletter::template_save( $values['id'], $values['name'], $values['text'] ) )
      $response = [ 'status' => 'ok', 'msg' => 'Zmiany zostały zapisane.', 'id' => $id ];

    echo json_encode( $response );
    exit;
  }
}
