<?php

namespace Dashboard\Controllers\Store;

use Dashboard\Core\Controller;

class CouponController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_STORE');
    }

    public function index()
    {
        $coupons = db()->query("SELECT * FROM ProductCoupons ORDER BY id DESC");
        $coupons = array_map(function($coupon) {
          if ($coupon["redeemLimit"] > 0) {
            $productCouponsHistory = db()->prepare("SELECT * FROM ProductCouponsHistory WHERE couponID = ?");
            $productCouponsHistory->execute(array($coupon["id"]));
            $coupon["left"] = max($coupon["redeemLimit"] - $productCouponsHistory->rowCount(), 0);
          }

          return $coupon;
        }, $coupons->fetchAll());

        return view('store.coupons.index', compact('coupons'));
    }

    public function create()
    {
        return view('store.coupons.create');
    }

    public function store()
    {
        validate([
            'name' => 'required',
            'productsStatus' => 'required',
            'products' => 'required_if:productsStatus,1',
            'discount' => 'required',
	          'expiryDate' => 'required_without:neverExpires',
		        'redeemLimit' => 'required_without:unlimitedRedeemLimit',
		        'redeemLimitPerCustomer' => 'required_without:unlimitedRedeemLimitPerCustomer',
            'minPayment' => 'required',
        ]);
	    
		    if (input("neverExpires")) {
			    set_input("expiryDate", '1000-01-01 00:00:00');
		    }
		    if (input('unlimitedRedeemLimit')) {
			    set_input('redeemLimit', -1);
		    }
		    if (input('unlimitedRedeemLimitPerCustomer')) {
			    set_input('redeemLimitPerCustomer', -1);
		    }
        if (input("productsStatus") == 0) {
            set_input("products", 0);
        }

        $insertProductCoupons = db()->prepare("INSERT INTO ProductCoupons (name, products, discount, redeemLimit, redeemLimitPerCustomer, minPayment, expiryDate, creationDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $insertProductCoupons->execute(array(str_replace(" ", "", input("name")), input("products"), input("discount"), input("redeemLimit"), input("redeemLimitPerCustomer"), input("minPayment"), input("expiryDate"), datetime()));
        return back()->flash("success", t__('Coupon has been added successfully!'));
    }

    public function edit($id)
    {
        $coupon = db()->prepare("SELECT * FROM ProductCoupons WHERE id = ?");
        $coupon->execute(array($id));
        $coupon = $coupon->fetch();

        if (!$coupon) return view('404');

        return view('store.coupons.edit', compact('coupon'));
    }

    public function update($id)
    {
        validate([
            'name' => 'required',
            'productsStatus' => 'required',
            'products' => 'required_if:productsStatus,1',
            'discount' => 'required',
		        'redeemLimit' => 'required_without:unlimitedRedeemLimit',
						'redeemLimitPerCustomer' => 'required_without:unlimitedRedeemLimitPerCustomer',
	          'expiryDate' => 'required_without:neverExpires',
	          'minPayment' => 'required',
        ]);
	    
		    if (input("neverExpires")) {
			    set_input("expiryDate", '1000-01-01 00:00:00');
		    }
		    if (input('unlimitedRedeemLimit')) {
			    set_input('redeemLimit', -1);
        }
		    if (input('unlimitedRedeemLimitPerCustomer')) {
			    set_input('redeemLimitPerCustomer', -1);
		    }
        if (input("productsStatus") == 0) {
          set_input("products", 0);
        }

        $updateProductCoupons = db()->prepare("UPDATE ProductCoupons SET name = ?, products = ?, discount = ?, expiryDate = ?, redeemLimit = ?, redeemLimitPerCustomer = ?, minPayment = ? WHERE id = ?");
        $updateProductCoupons->execute(array(str_replace(" ", "", input("name")), input("products"), input("discount"), input("expiryDate"), input("redeemLimit"), input('redeemLimitPerCustomer'), input("minPayment"), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

    public function destroy($id)
    {
        $deleteProductCoupon = db()->prepare("DELETE FROM ProductCoupons WHERE id = ?");
        $deleteProductCoupon->execute(array($id));
        return back();
    }
}