<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Location;
use Illuminate\View\View;
use App\LocationDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Http\RedirectResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\LocationRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class LocationController extends Controller
{

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

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

    /**
     * return data of the locations.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Location::latest()
        ->join('location_descriptions AS ld', 'locations.id', 'ld.location_id')
        ->join('languages', 'languages.id', 'ld.language_id')
        ->where('local', LaravelLocalization::getCurrentLocale())
        ->select(['ld.name','ld.address', 'locations.*']);

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

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

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

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

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

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

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

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

    /**
     * Store a newly created location in storage.
     * @param LocationRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(LocationRequest $request) :RedirectResponse
    {
        $data= [
            'image'=>  $request->image ?? null,
            'meta'=> [
                'latitude'=> $request->latitude ?? null,
                'longitude'=> $request->longitude ?? null,
                'phone'=> $request->phone ?? null,
                'fax'=> $request->fax ?? null,
                'email'=> $request->email ?? null,
            ]
        ];
        // dd($data, $request->all());
        $location = Location::create($data);

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

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

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

        $query = LocationDescription::where('location_id', $location->id)
        ->join('languages', 'languages.id', 'location_descriptions.language_id')
        ->select(['location_descriptions.*', 'languages.local']);

        $locationDescription= $query->get();

        foreach ($locationDescription as $row) {
            $location[$row->local]= $row;
        }

        $images = $location['images'] ?? [];

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

    /**
     * Update the specified location in storage.
     * @param LocationRequest $request
     * @param Location $location
     * @return RedirectResponse|Redirector
     */
    public function update(LocationRequest $request, Location $location) :RedirectResponse
    {
        $data= [
            'image'=>  $request->image ?? null,
            'meta'=> [
                'latitude'=> $request->latitude ?? null,
                'longitude'=> $request->longitude ?? null,
                'phone'=> $request->phone ?? null,
                'fax'=> $request->fax ?? null,
                'email'=> $request->email ?? null,
            ]
        ];
        // dd($data);
        $location->update($data);

        // Delete old description
        LocationDescription::where('location_id', $location->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param LocationRequest $request
     * @param int $location_id
     * @return void
     */

     private function saveData(LocationRequest $request, int $location_id ) :void
     {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'location_id'=> $location_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'address'=> $requestData['address_'.$lang->local],
                'box'=> $requestData['box_'.$lang->local],
                'slug'=> $requestData['slug_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];

            LocationDescription::create($data);
        }

     }

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

    /**
     * Remove several locations by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

        if ($request->force) {
            Location::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Location::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified location from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $location= Location::withTrashed()->find($id);
        if ($location) {
            $location->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);

    }

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