<?php

namespace App\Http\Controllers\Admin;

use App\Category;
use App\Coupon;
use App\Course;
use App\Product;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\CouponRequest;

class CouponController extends Controller
{

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

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('coupons.head');
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the coupons.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Coupon::orderBy('id', 'desc');

        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->name) {
            $query->where('coupons.name', 'LIKE', '%'.$request->name.'%');
        }

        if ($request->course_id) {
            $query->where('course_id', $request->course_id);
//            $query->join('courses', 'courses.id', 'coupons.course_id')
//                ->join('course_descriptions AS cd', 'courses.id', 'cd.course_id')
//                ->where('cd.language_id', currentLanguage()->id)
//                ->where('coupons.course_id', $request->course_id)
//                ->select(['cd.name as course_name','coupons.*']);
        }

        if ($request->product_id) {
            $query->where('product_id', $request->product_id);
//            $query->join('products', 'products.id', 'coupons.product_id')
//                ->join('product_descriptions AS pd', 'products.id', 'pd.product_id')
//                ->where('pd.language_id', currentLanguage()->id)
//                ->where('coupons.product_id', $request->product_id)
//                ->select(['pd.name as product_name', 'coupons.*']);
        }

//        if ($request->category_id) {
//            $query->join('categories', 'categories.id', 'coupons.category_id')
//                ->join('category_descriptions AS cat_d', 'categories.id', 'cat_d.category_id')
//                ->where('cat_d.language_id', currentLanguage()->id)
//                ->where('coupons.category_id', $request->category_id)
//                ->select(['cat_d.name as category_name', 'coupons.*']);
//        }

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('coupons.store');
        $head = metaFields('coupons', 'add_new', getCurrentLocale()) ?? __('coupons.new');
        $products = Product::withDescription();
        return view( $this->viewDirectory.'form', compact('action', 'head', 'products'));
    }

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param Coupon $coupon
     * @return View
     */
    public function edit(Coupon $coupon) :View
    {
        $action = route('coupons.update', $coupon->id);
        $head = metaFields('coupons', 'edit', getCurrentLocale()) ?? __('coupons.edit');
        $products = Product::withDescription();
        return view( $this->viewDirectory.'form', compact('coupon', 'action', 'head', 'products'));
    }

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

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

    }

    public function getProducts(Request $request)
    {
        if ($request->ajax()){
            $products = Product::withDescription([$request->category_id]);
            $coupon = Coupon::where('category_id', $request->category_id)->first();
            return view($this->viewDirectory.'.get_products', compact('products', 'coupon'));
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $coupon = Coupon::withTrashed()->find($id);
        if ($coupon) {
            if ($coupon->deleted_at) {
                $coupon->forceDelete();
            } else {
                $coupon->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
    {
        $coupon = Coupon::withTrashed()->find($id);

        if ($coupon){
            $coupon->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
    {
        $coupons = Coupon::whereIn('id', $request->ids)->onlyTrashed();
        if ($coupons){
            $coupons->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
