<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Type;
use Illuminate\View\View;
use App\TypeDescription;
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\TypeRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class TypeController extends Controller
{

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

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

    /**
     * return data of the types.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Type::latest()
        ->join('type_descriptions AS cd', 'types.id', 'cd.type_id')
        ->join('languages', 'languages.id', 'cd.language_id')
        ->where('local', LaravelLocalization::getCurrentLocale())
        ->select(['cd.name', 'types.*']);

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

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

        if ($request->name) {
            $query->where('cd.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->vission) {
            $query->where('cd.vission', 'LIKE', '%'.$request->vission.'%');
        }
        if ($request->mission) {
            $query->where('cd.mission', 'LIKE', '%'.$request->mission.'%');
        }
        if ($request->goal) {
            $query->where('cd.goal', 'LIKE', '%'.$request->goal.'%');
        }

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

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

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

    /**
     * Store a newly created Type in storage.
     * @param TypeRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(TypeRequest $request) :RedirectResponse
    {
       

        $type = Type::create();
        
       
        // Insert Description
        $this->saveData( $request, $type->id );

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

    /**
     * Show the form for editing the specified Type.
     *
     * @param  Type  $type
     * @return View
     */
    public function edit(Type $type) :View
    {
        $action= route('types.update', $type->id);
        $head = __('types.edit');
        $query = TypeDescription::where('type_id', $type->id)
        ->join('languages', 'languages.id', 'type_descriptions.language_id')
        ->select(['type_descriptions.*', 'languages.local']);

        $typeDescription= $query->get();

        foreach ($typeDescription as $row) {
            $type[$row->local]= $row;
        }

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

    /**
     * Update the specified Type in storage.
     * @param TypeRequest $request
     * @param Type $type
     * @return RedirectResponse|Redirector
     */
    public function update(TypeRequest $request, Type $type) :RedirectResponse
    {
        // Update the "updated_at" column only
       
     	$type->update([
            ]);  

        // Delete old description
        TypeDescription::where('type_id', $type->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param TypeRequest $request
     * @param int $type_id
     * @return void
     */

     private function saveData(TypeRequest $request, int $type_id ) :void
     {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'type_id'=> $type_id,
                'language_id'=> $lang->id,
                
                'name'=> $requestData['name_'.$lang->local],
                
                
            ];

            TypeDescription::create($data);
        }

     }

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

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

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

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

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

    }

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