<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\SellerRequest;
use App\Models\CobonUser;
use App\Models\User;
use Exception;
use App\Models\Cobon;
use App\Models\CobonDescription;
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 Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class SellerController extends Controller
{

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

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

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Cobon::where('seller_id','!=',null);

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

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

        if ($request->code) {
            $query->where('code', 'LIKE', '%'.$request->code.'%');
        }
        if ($request->start_date) {
            $query->where('start_date', $request->start_date);
        }
        if ($request->end_date) {
            $query->where('end_date', $request->end_date);
        }
        if ($request->discount_amount) {
            $query->where('discount_amount', $request->discount_amount);
        }
        if ($request->discount_type) {
            $query->where('discount_type', $request->discount_type);
        }
        if ($request->seller_id) {
            $query->where('seller_id', $request->seller_id);
        }
        if ($request->count) {
            $query->where('count', $request->count);
        }

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create(Request $request) :View
    {
        $action= route('sellers.store');
        $head= __('sellers.new');
        $sellers = User::where('role','seller')->cursor();

        return view( $this->viewDirectory.'form', compact('action', 'head','sellers') );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param SellerRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(SellerRequest $request)
    {
        $seller = Cobon::create($request->all());
        $seller->users()->attach($request->user_ids);
        $this->saveData($request, $seller->id);

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Seller  $seller
     * @return View
     */
    public function edit(Cobon  $seller) :View
    {
        $head= __('sellers.edit');
        $action= route('sellers.update', $seller->id);
        $ids = CobonUser::where('cobon_id',$seller->id)->pluck('user_id')->toArray();
        $users = User::find($ids);

        $query = cobonDescription::where('cobon_id', $seller->id)
            ->join('languages', 'languages.id', 'cobon_descriptions.language_id')
            ->select(['cobon_descriptions.*', 'languages.local']);

        $cobonDescription= $query->get();

        foreach ($cobonDescription as $row) {
            $seller[$row->local]= $row;
        }
        $sellers = User::where('role','seller')->cursor();

        return view( $this->viewDirectory.'form', compact('seller', 'action','head','sellers','users') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param SellerRequest $request
     * @param Cobon  $seller
     * @return RedirectResponse|Redirector
     */
    public function update(SellerRequest $request, Cobon  $seller)
    {

        // Update image and category id if request has it

        $seller->update($request->all());
        $seller->users()->sync($request->user_ids);
        CobonDescription::where('cobon_id',$seller->id)->delete();
        $this->saveData($request, $seller->id);

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param SellerRequest $request
     * @param int $seller_id
     * @return void
     */

    private function saveData(SellerRequest $request, int $seller_id ):void
    {

        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'cobon_id'=> $seller_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            cobonDescription::create($data);
        }
    }

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

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Cobon::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Cobon::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
    {
        $seller = Cobon::withTrashed()->find($id);

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

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