<?php
namespace admin\controls;

class ShopCoupon
{
  public static function coupon_delete()
  {
    $coupon = new \shop\Coupon( (int)\S::get( 'id' ) );
    if ( $coupon -> delete() )
      \S::alert( 'Kupon został usunięty.' );
    header( 'Location: /admin/shop_coupon/view_list/' );
    exit;
  }

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

    if ( $values['categories'] != null )
      $categories = is_array( $values['categories'] ) ? json_encode( $values['categories'] ) : json_encode( [ $values['categories'] ] );
    else
      $categories = null;

    if ( \admin\factory\ShopCoupon::save(
            $values['id'],
            $values['name'],
            $values['status'] == 'on' ? 1 : 0,
            $values['send'] == 'on' ? 1 : 0,
            $values['used'] == 'on' ? 1 : 0,
            $values['type'],
            $values['amount'],
            $values['one_time'] == 'on' ? 1 : 0,
            $values['include_discounted_product'] == 'on' ? 1 : 0,
            $categories
          )
    )
      $response = [ 'status' => 'ok', 'msg' => 'Kupon został zapisany.', 'id' => $values['id'] ];

    echo json_encode( $response );
    exit;
  }

  public static function coupon_edit()
  {
    return \Tpl::view( 'shop-coupon/coupon-edit', [
          'coupon' => \admin\factory\ShopCoupon::details( (int)\S::get( 'id' ) ),
          'categories' => \admin\factory\ShopCategory::subcategories( null ),
          'dlang' => \front\factory\Languages::default_language()
      ] );
  }

  public static function view_list()
  {
    return \Tpl::view( 'shop-coupon/view-list' );
  }

}