<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\VisitorMessagesJob;
use App\VisitorRequestReply;
use App\VisitorRequest;
use Exception;
use Illuminate\Support\Facades\Auth;
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\VisitorRequestRequest;

class VisitorRequestController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/admin/visitorRequests';
    /** View folder */
    private $viewDirectory= 'admin.visitor_requests.';

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

    /**
     * return data of the newsletters.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = VisitorRequest::latest();

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

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

        if ($request->name) {
            $query->where('visitor_requests.subject', 'LIKE', '%'.$request->name.'%');
        }

        if ($request->email) {
            $query->where('visitor_requests.email', 'LIKE', '%'.$request->email.'%');
        }

        if ($request->phone) {
            $query->where('visitor_requests.phone', 'LIKE', '%'.$request->phone.'%');
        }

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

        $visitorRequests= $query->paginate(10);

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param VisitorRequestRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(VisitorRequestRequest $request) :RedirectResponse
    {
        $this->saveData($request);
        return redirect($this->redirectSuccessPath)->with('message', __('visitorRequests.email_success'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param VisitorRequest $visitorRequest
     * @return View
     */
    public function edit(VisitorRequest $visitorRequest) :View
    {
        $replies = $visitorRequest->replies;
        $visitorRequest->update(['read' => 1]);
        $action= route('visitorRequests.update', $visitorRequest->id);
        return view( $this->viewDirectory.'form', compact('visitorRequest','replies', 'action') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param VisitorRequestRequest $request
     * @param VisitorRequest $visitorRequest
     * @return RedirectResponse|Redirector
     */
    public function update(VisitorRequestRequest $request, VisitorRequest $visitorRequest) :RedirectResponse
    {
        $this->saveData($request, $visitorRequest);
        return redirect($this->redirectSuccessPath)->with('message', __('visitorRequests.email_success'));
    }

    /**
     * Handle Save form data
     *
     * @param VisitorRequestRequest $request
     * @param $visitorRequest
     * @return void
     */

    private function saveData(VisitorRequestRequest $request, $visitorRequest = null):void
    {
        $this->dispatch(new VisitorMessagesJob($request->all(), $this->viewDirectory.'email'));

        VisitorRequestReply::create([
            'reply' => $request->reply,
            'visitor_email' => $request->visitor_email,
            'user_id' => Auth::id(),
            'visitor_request_id' => $visitorRequest ? $visitorRequest->id : null,
        ]);

        $visitorRequest ? $visitorRequest->update(['reply' => 1]) : null;
    }


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

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