<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\NumberRequest;
use App\Number;
use Exception;
use App\NumberDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class NumberController extends Controller
{

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

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

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Number::join('number_descriptions AS nd', 'numbers.id', 'nd.number_id')
            ->where('nd.language_id', currentLanguage()->id)
            ->select(['nd.title', 'numbers.*']);

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

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

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


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

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

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

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

    /**
     * Store a newly created resource in storage.
     * @param NumberRequest $request
     * @return JsonResponse
     */
    public function store(NumberRequest $request)
    {
        $number = Number::create($request->all());
        $this->saveData( $request, $number->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


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

        $query = NumberDescription::where('number_id', $number->id)
            ->join('languages', 'languages.id', 'number_descriptions.language_id')
            ->select(['number_descriptions.*', 'languages.local']);

        $numberDescription= $query->get();

        foreach ($numberDescription as $row) {
            $number[$row->local]= $row;
        }
        $local = getCurrentLocale();

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

    /**
     * Update the specified resource in storage.
     * @param NumberRequest $request
     * @param Number $number
     * @return JsonResponse
     */
    public function update(NumberRequest $request, Number $number)
    {
        $number->update($request->all());
        // Delete old description
        NumberDescription::where('number_id', $number->id)->delete();
        $this->saveData( $request, $number->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Handle Save form data
     *
     * @param NumberRequest $request
     * @param int $number_id
     * @return void
     */

    private function saveData(NumberRequest $request, int $number_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'number_id'=> $number_id,
                'language_id'=> $lang->id,
                'title'=> $requestData['title_'.$lang->local],
            ];
            NumberDescription::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
    {
        $number = Number::withTrashed()->find($id);
        if ($number) {
            if ($number->deleted_at) {
                $number->forceDelete();
            } else {
                $number->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

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

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

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