<?php

namespace App\Http\Controllers\Admin;

use App\WorkWay;
use Exception;
use App\Language;
use App\WorkWayDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\WorkWayRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;

class WorkWayController extends Controller
{

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

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

    /**
     * return data of the workWays.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = WorkWay::orderBy('work_ways.id', 'DESC')
            ->join('work_way_descriptions AS wd', 'work_ways.id', 'wd.work_way_id')
            ->join('languages', 'languages.id', 'wd.language_id')
            ->where('wd.language_id', currentLanguage()->id)
            ->select(['wd.title', 'work_ways.*']);

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

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

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

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

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

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

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

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

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


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

        $query = WorkWayDescription::where('work_way_id', $workWay->id)
            ->join('languages', 'languages.id', 'work_way_descriptions.language_id')
            ->select(['work_way_descriptions.*', 'languages.local']);

        $workWayDescription= $query->get();

        foreach ($workWayDescription as $row) {
            $workWay[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param WorkWayRequest $request
     * @param WorkWay $workWay
     * @return RedirectResponse|Redirector
     */
    public function update(WorkWayRequest $request, WorkWay $workWay) :RedirectResponse
    {
        // Update image if request has it
        $workWay->update(['image' => $request->image??null]);

        // Delete old description
        WorkWayDescription::where('work_way_id', $workWay->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param WorkWayRequest $request
     * @param int $work_way_id
     * @return void
     */

    private function saveData(WorkWayRequest $request, int $work_way_id ):void
    {
        $requestData= $request->all();
        $languages= Language::where('status', 1)->cursor();

        foreach ($languages as $lang) {
            $data=[
                'work_way_id'=> $work_way_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
//                'slug'=> $requestData['slug_'.$lang->local],
//                'keywords'=> $requestData['keywords_'.$lang->local],
//                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];
            WorkWayDescription::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
    {
        $workWay = WorkWay::withTrashed()->find($id);
        if ($workWay) {
            if ($workWay->deleted_at) {
                $workWay->forceDelete();
            } else {
                $workWay->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

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

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

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