<?php

namespace App\Http\Controllers\Admin;

use App\Models\City;
use App\Models\ShippingCity;
use Exception;
use App\Models\Country;
use App\Models\Shipping;
use Illuminate\View\View;
use App\Models\ShippingDescription;
use Illuminate\Http\Request;
use App\Services\Response\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ShippingRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class ShippingController extends Controller
{

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

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

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Shipping::latest()
            ->join('shipping_descriptions AS ad', 'shippings.id', 'ad.shipping_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.name', 'shippings.*']);

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

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

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

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('shippings.store');
        $head= __('shippings.new');


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

    /**
     * Store a newly created resource in storage.
     *
     * @param ShippingRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ShippingRequest $request)
    {
        $data = $request->all();

        $shipping = Shipping::create($data);

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

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Shipping $shipping
     * @return View
     */
    public function edit(Shipping $shipping) :View
    {
        $action= route('shippings.update', $shipping->id);
        $head= __('shippings.edit');
        
        $query = ShippingDescription::where('shipping_id', $shipping->id)
            ->join('languages', 'languages.id', 'shipping_descriptions.language_id')
            ->select(['shipping_descriptions.*', 'languages.local']);

        $shippingDescription= $query->get();

        foreach ($shippingDescription as $row) {
            $shipping[$row->local]= $row;
        }
        $countries = Country::withDescription()->cursor();
        $cities = City::withDescription()->cursor();
        $shippingCities = ShippingCity::where('shipping_id',$shipping->id)->cursor();
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param ShippingRequest $request
     * @param Shipping $shipping
     * @return RedirectResponse|Redirector
     */
    public function update(ShippingRequest $request, Shipping $shipping)
    {
        $data = $request->all();

        $shipping->update($data);

        // Delete old description
        ShippingDescription::where('shipping_id', $shipping->id)->delete();
        ShippingCity::where('shipping_id', $shipping->id)->delete();

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

        session()->flash('message', __('dashboard.saveDone'));
        $response = [
            'status'=>200,
            'message'=>__('web.success'),
            'data'=> $this->redirectSuccessPath,
        ];
        return ResponseService::response($response);
    }

    /**
     * Handle Save form data
     *
     * @param ShippingRequest $request
     * @param int $shipping_id
     * @return void
     */

    private function saveData(ShippingRequest $request, int $shipping_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'shipping_id'=> $shipping_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
            ];
            ShippingDescription::create($data);
        }
        if(isset($request->cities))
        {
            foreach ($request->cities as $row)
            {
                ShippingCity::create([
                    'shipping_id'=>$shipping_id,
                    'city_id'=>$row['city_id'],
                    'tax'=>$row['tax'],
                    'timing' => json_encode(['ar'=>$row['timing_ar'],'en'=>$row['timing_en']])
                ]);
            }
        }
    }

    public function addCity(Request $request)
    {
        $countries = Country::withDescription()->cursor();
        $cities = City::withDescription()->cursor();
        $key = $request->key;
        return view( $this->viewAjax.'cities', compact('key','cities','countries') );

    }

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

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