<?php

namespace App\Http\Controllers\Admin;

use App\Service;
use App\ServiceDescription;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\ServiceRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;

class ServiceController extends Controller
{

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

    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= __('services.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the services.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Service::orderBy('services.id', 'DESC')
            ->join('service_descriptions AS sd', 'services.id', 'sd.service_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('sd.language_id', currentLanguage()->id)
            ->select(['sd.title', 'services.*']);

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

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

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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param ServiceRequest $request
     * @return JsonResponse
     */
    public function store(ServiceRequest $request) :JsonResponse
    {
        $descriptions = $this->descriptionData($request);
        $data['descriptions'] = $descriptions;
        $data['image'] = $request->image;
        $service = Service::create($data);
        // Insert Description
        $this->saveData( $request, $service->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('services.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


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

        $query = ServiceDescription::where('service_id', $service->id)
            ->join('languages', 'languages.id', 'service_descriptions.language_id')
            ->select(['service_descriptions.*', 'languages.local']);

        $serviceDescription= $query->get();

        foreach ($serviceDescription as $row) {
            $service[$row->local]= $row;
        }

        $local = getCurrentLocale();
        $service->descriptions = is_string($service->descriptions) ? json_decode($service->descriptions) : $service->descriptions;

        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ServiceRequest $request
     * @param Service $service
     * @return JsonResponse
     */
    public function update(ServiceRequest $request, Service $service) :JsonResponse
    {
        $descriptions = $this->descriptionData($request);
        $data['descriptions'] = $descriptions;
        $data['image'] = $request->image;
        $service->update($data);
        // Delete old description
        ServiceDescription::where('service_id', $service->id)->delete();

        // Insert new description
        $this->saveData( $request, $service->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('services.index')]);

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

    /**
     * Handle Save form data
     *
     * @param ServiceRequest $request
     * @param int $service_id
     * @return void
     */

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

        foreach (languages() as $lang) {
            $data=[
                'service_id'=> $service_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
            ];
            ServiceDescription::create($data);
        }

    }

    private function descriptionData($request){
        $description = [];
        foreach ($request->desc_ar as $key => $desc) {
            $description[] = [
                'icon' => $request->icon[$key],
                'desc_ar' => $desc,
                'desc_en' => $request->desc_en[$key],
            ];
        }

        $description = json_encode($description);
        return $description;

    }



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

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

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

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