<?php

namespace App\Http\Controllers\Admin;

use App\VisitorMessageReply;
use Exception;
use App\VisitorMessage;
use http\Client\Curl\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Illuminate\Http\Request;
use App\Jobs\VisitorMessagesJob;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\VisitorMessageRequest;

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

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('visitorMessages.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 = VisitorMessage::latest();

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

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

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

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

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

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

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

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

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


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

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

    /**
     * Handle Save form data
     *
     * @param VisitorMessageRequest $request
     * @param $visitorMessage
     * @return void
     */

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

        VisitorMessageReply::create([
            'reply' => $request->reply,
            'visitor_email' => $request->visitor_email,
            'user_id' => Auth::id(),
            'visitor_message_id' => $visitorMessage ? $visitorMessage->id : null,
        ]);

        $visitorMessage ? $visitorMessage->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
    {
        $message = VisitorMessage::withTrashed()->find($id);
        if ($message) {
            if ($message->deleted_at) {
                $message->forceDelete();
            } else {
                $message->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) {
            VisitorMessage::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            VisitorMessage::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
    {
        $message = VisitorMessage::withTrashed()->find($id);

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