<?php

namespace App\Http\Controllers\Admin;

use App\Staff;
use App\StaffDescription;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\StaffRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;

class StaffController extends Controller
{

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

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

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

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

        if ($request->date_to) {
            $query->whereDate('staffs.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();
        }

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

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

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

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

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


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

        $query = StaffDescription::where('staff_id', $staff->id)
            ->join('languages', 'languages.id', 'staff_descriptions.language_id')
            ->select(['staff_descriptions.*', 'languages.local']);

        $staffDescription= $query->get();

        foreach ($staffDescription as $row) {
            $staff[$row->local]= $row;
        }

        $local = getCurrentLocale();

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

    /**
     * Update the specified resource in storage.
     *
     * @param StaffRequest $request
     * @param Staff $staff
     * @return RedirectResponse|Redirector
     */
    public function update(StaffRequest $request, Staff $staff) :RedirectResponse
    {
        $staff->update($request->all());

        // Delete old description
        StaffDescription::where('staff_id', $staff->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param StaffRequest $request
     * @param int $staff_id
     * @return void
     */

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

        foreach (languages() as $lang) {
            $data=[
                'staff_id'=> $staff_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'job_title'=> $requestData['job_title_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'brief'=> $requestData['brief_'.$lang->local],
                'practical_experience'=> $requestData['practical_experience_'.$lang->local],
                'training_courses'=> $requestData['training_courses_'.$lang->local],
                'skills'=> $requestData['skills_'.$lang->local],
                'practical_experience_title'=> $requestData['practical_experience_title_'.$lang->local],
                'training_courses_title'=> $requestData['training_courses_title_'.$lang->local],
                'skills_title'=> $requestData['skills_title_'.$lang->local],
            ];
            StaffDescription::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
    {
        $staff = Staff::withTrashed()->find($id);
        if ($staff) {
            if ($staff->deleted_at) {
                $staff->forceDelete();
            } else {
                $staff->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

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

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

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