<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Exception;
use App\Models\Review;
use Illuminate\View\View;
use App\Models\ReviewDescription;
use Illuminate\Http\Request;
use App\Services\Response\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Requests\Admin\ReviewRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ReviewController extends Controller
{

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

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

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Review::latest()
            ->join('review_descriptions AS ad', 'reviews.id', 'ad.review_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.user', 'reviews.*']);

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

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

        if ($request->user) {
            $query->where('ad.user', 'LIKE', '%'.$request->user.'%');
        }
        if ($request->type) {
            $query->where('type', $request->type);
        }

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param ReviewRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ReviewRequest $request) 
    {

        $review = Review::create($request->all());


        // Insert Description
        $this->saveData($request, $review->id);

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Review $review
     * @return View
     */
    public function edit(Review $review) :View
    {
        $action= route('reviews.update', $review->id);

        $query = ReviewDescription::where('review_id', $review->id)
            ->join('languages', 'languages.id', 'review_descriptions.language_id')
            ->select(['review_descriptions.*', 'languages.local']);
        $head= __('reviews.edit');

        $reviewDescription= $query->get();

        foreach ($reviewDescription as $row) {
            $review[$row->local]= $row;
        }

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

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

        // Update image and category id if request has it

        $review->update($request->all());

        // Delete old description
        ReviewDescription::where('review_id', $review->id)->delete();

        // Insert new description
        $this->saveData( $request, $review->id );

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }

    /**
     * Handle Save form data
     *
     * @param ReviewRequest $request
     * @param int $review_id
     * @return void
     */

    private function saveData(ReviewRequest $request, int $review_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'review_id'=> $review_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local]??null,
                'description'=> $requestData['description_'.$lang->local],
                'user'=> $requestData['user_'.$lang->local],
            ];
            ReviewDescription::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
    {
        $review = Review::withTrashed()->find($id);
        if ($review) {
            if ($review->deleted_at) {
                $review->forceDelete();
            } else {
                $review->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) {
            Review::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Review::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
    {
        $review = Review::withTrashed()->find($id);

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