<?php

namespace App\Http\Controllers\Admin;

use App\Coupon;
use App\User;
use Exception;
use Illuminate\Contracts\View\Factory;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\CouponRequest;

class MarketerCouponController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/marketerCoupons';
    /** View folder */
    private $viewDirectory = 'admin.marketer_coupons.';

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('marketerCoupons.head');
        $users = User::whereNotNull('name')->whereHas('coupon')->cursor();
        return view($this->viewDirectory.'index', get_defined_vars());
    }

    /**
     * return data of the coupons.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {

        $query = Coupon::orderBy('id', 'desc')
            ->join('users', 'users.id', 'coupons.user_id')
                ->select(['coupons.*', 'users.name as user_name']);


        if ($request->date_from) {
            $query->whereDate('coupons.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('coupons.created_at', '<=', $request->date_to);
        }

        if ($request->code) {
            $query->where('coupons.code', 'LIKE', '%'.$request->code.'%');
        }
        if ($request->user_id) {
            $query->where('coupons.user_id', $request->user_id);
        }

        if ($request->service_type) {
            $query->where('coupons.service_type', $request->service_type);
        }
        if ($request->discount_type) {
            $query->where('coupons.discount_type', $request->discount_type);
        }
        if ($request->coupon_status == 'active') {
            $query->where('coupons.status', 1);
        }
        if ($request->coupon_status == 'not_active') {
            $query->where('coupons.status', 0);
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $marketerCoupons= $query->paginate(100);

        return view($this->viewDirectory.'grid', get_defined_vars());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('marketerCoupons.store');
        $head = metaFields('marketerCoupons', 'new', getCurrentLocale()) ?? __('marketerCoupons.new');
        $title = $head;

        $users = User::whereNotNull('name')->where('role', 'user')->cursor();
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param CouponRequest $request
     * @return JsonResponse
     */
    public function store(CouponRequest $request) :JsonResponse
    {
        $data = $request->all();
        Coupon::create($data);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('marketerCoupons.index')]);
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Coupon $marketerCoupon
     * @return Factory|RedirectResponse|View
     */
    public function edit(Coupon $marketerCoupon)
    {
        if (!$marketerCoupon->user_id){
            return  redirect()->route('marketerCoupons.index');
        }
        $action = route('marketerCoupons.update', $marketerCoupon->id);
        $head = metaFields('marketerCoupons', 'edit', getCurrentLocale()) ?? __('marketerCoupons.edit');
        $title = $head;

        $users = User::whereNotNull('name')->whereHas('coupon')->cursor();
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param CouponRequest $request
     * @param Coupon $marketerCoupon
     * @return JsonResponse
     */
    public function update(CouponRequest $request, Coupon $marketerCoupon) :JsonResponse
    {
        $data = $request->all();
        $marketerCoupon->update($data);
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('marketerCoupons.index')]);
    }

    public function activeCoupon(Coupon $marketerCoupon)
    {
        if ($marketerCoupon->status){
            $marketerCoupon->update(['status' => 0]);
            return response()->json(['message' => __('members.de_active_success')]);
        } else {
            $marketerCoupon->update(['status' => 1]);
            return response()->json(['message' => __('members.active_success')]);
        }

    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $marketerCoupon = Coupon::withTrashed()->find($id);
        if ($marketerCoupon) {
            if ($marketerCoupon->deleted_at) {
                $marketerCoupon->forceDelete();
            } else {
                $marketerCoupon->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several coupons by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Coupon::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Coupon::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $marketerCoupon = Coupon::withTrashed()->find($id);

        if ($marketerCoupon){
            $marketerCoupon->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several coupons by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $marketerCoupons = Coupon::whereIn('id', $request->ids)->onlyTrashed();
        if ($marketerCoupons){
            $marketerCoupons->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
