<?php

namespace App\Http\Controllers;

use App\Http\Component\AppController;
use App\Http\Services\CouponService;
use App\Models\Coupon;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class CouponController extends AppController
{
    private $coupon;
    private $activeTemplate;

    public function __construct(
        CouponService $coupon
    )
    {
        $this->coupon = $coupon;
        $this->activeTemplate = activeTemplate();
    }

    public function useCoupon(Request $request){

       // Validate
       $validator = Validator::make($request->all(),[
        'amount' => 'required|numeric',
        'code' => 'required|string',
        'package' => ''
        ]);

        // Failed to validate
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            $notify[] = ['error', implode(' ', $errors)];
            return $this->handleResponse($request, implode(' ', $errors), 401, $notify);
        }

        // User
       $user = User::find(\auth()->user()->id);

        // Verify Coupon
       $coupon = $this->coupon->verifyCoupon($user, 'invest', $request->code, $request->amount, $request->package);
       
       // Exception
       if($coupon instanceof \Exception) {
        // Redirect
        $notify[] = ['error', $coupon->getMessage()];
        return $this->handleResponse($request, $coupon->getMessage(), 401, $notify);
       }

       // Success Response
       return $this->handleResponse($request, 'Successful', 200, $coupon);

    }

    public function coupon($expired = 0)
    {
        $pageTitle = 'My Coupons';
        $user = Auth::user();
        $coupons = Coupon::where(['user_id' => $user->id,'public' => 0,  'expired' => $expired, 'status' => 1])->orderBy('created_at')->get();
        $pub_coupons = Coupon::where(['public' => 1, 'expired' => $expired, 'status' => 1])->orderBy('created_at')->get();
        
        return view($this->activeTemplate. 'user.coupon.view', compact(
            'expired',
            'pageTitle',
            'user',
            'coupons',
            'pub_coupons'
        ));
    }

    public function index()
    {
        $pageTitle = 'My Coupons';
        $user = Auth::user();
        $coupons = Coupon::where(['user_id' => $user->id,'public' => 0,  'status' => 1])->orderBy('created_at')->get();
        $pub_coupons = Coupon::where(['public' => 1, 'status' => 1])->orderBy('created_at')->get();
        
        return view($this->activeTemplate. 'user.coupon.index', compact(
            'pageTitle',
            'user',
            'coupons',
            'pub_coupons'
        ));
    }


}
