<?php

namespace App\Http\Controllers\Admin;

use App\Director;
use Exception;
use App\Language;
use App\DirectorDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\DirectorRequest;
use App\Http\Controllers\Controller;

class DirectorController extends Controller
{

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

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

    /**
     * return data of the directors.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Director::orderByDesc('directors.id')
            ->join('director_descriptions AS dDesc', 'directors.id', 'dDesc.director_id')
            ->where('dDesc.language_id', currentLanguage()->id)
            ->select(['dDesc.name', 'dDesc.specialist', 'directors.*']);

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

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

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

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

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

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

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

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

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

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


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

        $query = DirectorDescription::where('director_id', $director->id)
            ->join('languages', 'languages.id', 'director_descriptions.language_id')
            ->select(['director_descriptions.*', 'languages.local']);

        $directorDescription= $query->get();

        foreach ($directorDescription as $row) {
            $director[$row->local]= $row;
        }

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

    /**
     * Update the specified resource in storage.
     *
     * @param DirectorRequest $request
     * @param Director $director
     * @return JsonResponse
     */
    public function update(DirectorRequest $request, Director $director) : JsonResponse
    {
        // Update image if request has it
        $director->update($request->all());

        // Delete old description
        DirectorDescription::where('director_id', $director->id)->delete();

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

    /**
     * Handle Save form data
     *
     * @param DirectorRequest $request
     * @param int $directo_id
     * @return void
     */

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

        foreach ($languages as $lang) {
            $data=[
                'name'=> $requestData['name_'.$lang->local],
                'specialist'=> $requestData['specialist_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'director_id'=> $directo_id,
                'language_id'=> $lang->id,

            ];
            DirectorDescription::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
    {
        if (1 == $id) {
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }

        $director = Director::withTrashed()->find($id);
        if ($director) {
            if ($director->deleted_at) {
                $director->forceDelete();
            } else {
                $director->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several directors by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ( in_array( 1, $ids) ) {
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }

        if ($request->force) {
            Director::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Director::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
    {
        $director = Director::withTrashed()->find($id);

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

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