<?php

namespace App\Http\Controllers\Admin;

use App\Consulting;
use App\Http\Requests\ConsultingRequest;
use App\Page;
use App\ConsultingDescription;
use Exception;
use App\Language;
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 ConsultingController extends Controller
{

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

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

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

    /**
     * return data of the consultings.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Consulting::orderBy('consultings.id', 'DESC')
            ->join('consulting_descriptions AS cd', 'consultings.id', 'cd.consulting_id')
            ->join('languages', 'languages.id', 'cd.language_id')
            ->where('cd.language_id', currentLanguage()->id)
            ->select(['cd.name', 'consultings.*']);

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

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param ConsultingRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ConsultingRequest $request) :RedirectResponse
    {
        $consulting = Consulting::create();
        // Insert Description
        $this->saveData($request, $consulting->id);

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


    /**
     * Show the form for editing the specified resource.
     *
     * @param Page $consulting
     * @return View
     */
    public function edit(Consulting $consulting) :View
    {
        $action= route('consultings.update', $consulting->id);
        $head = metaFields('consultings', 'edit', getCurrentLocale()) ?? __('consultings.edit');

        $query = ConsultingDescription::where('consulting_id', $consulting->id)
            ->join('languages', 'languages.id', 'consulting_descriptions.language_id')
            ->select(['consulting_descriptions.*', 'languages.local']);

        $consultingDescription= $query->get();

        foreach ($consultingDescription as $row) {
            $consulting[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param ConsultingRequest $request
     * @param Page $consulting
     * @return RedirectResponse|Redirector
     */
    public function update(ConsultingRequest $request, Consulting $consulting) :RedirectResponse
    {
        // Update image if request has it
        $consulting->touch();

        // Delete old description
        ConsultingDescription::where('consulting_id', $consulting->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param ConsultingRequest $request
     * @param int $consulting_id
     * @return void
     */

    private function saveData(ConsultingRequest $request, int $consulting_id ):void
    {
        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'consulting_id'=> $consulting_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
             ];
            ConsultingDescription::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
    {
        $consulting = Consulting::withTrashed()->find($id);
        if ($consulting) {
            if ($consulting->deleted_at) {
                $consulting->forceDelete();
            } else {
                $consulting->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

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

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

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