<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\Occasion;
use Illuminate\View\View;
use App\OccasionDescription;
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\OccasionRequest;

class OccasionController extends Controller
{

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

    public function __construct()
    {
        $this->redirectSuccessPath = getCurrentLocale().$this->redirectSuccessPath;
    }

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

    /**
     * return data of the occasions.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Occasion::orderByDesc('occasions.id');
//        ->join('occasion_descriptions AS od', 'occasions.id', 'od.occasion_id')
//        ->join('languages', 'languages.id', 'od.language_id')
//        ->where('local', getCurrentLocale())
//        ->select(['od.name', 'occasions.*']);

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

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

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

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

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

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

    /**
     * Store a newly created occasion in storage.
     * @param OccasionRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(OccasionRequest $request) :RedirectResponse
    {
        $data = $request->all();
        $occasion = Occasion::create($data);
//        $this->saveData( $request, $occasion->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified occasion.
     *
     * @param  Occasion  $occasion
     * @return View
     */
    public function edit(Occasion $occasion) :View
    {
        $action= route('occasions.update', $occasion->id);
        $head = metaFields('occasions', 'edit', getCurrentLocale()) ?? __('occasions.edit');
        $title = $head;
//        $query = OccasionDescription::where('occasion_id', $occasion->id)
//        ->join('languages', 'languages.id', 'occasion_descriptions.language_id')
//        ->select(['occasion_descriptions.*', 'languages.local']);
//
//        $occasionDescription= $query->get();
//
//        foreach ($occasionDescription as $row) {
//            $occasion[$row->local]= $row;
//        }

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

    /**
     * Update the specified occasion in storage.
     * @param OccasionRequest $request
     * @param Occasion $occasion
     * @return RedirectResponse|Redirector
     */
    public function update(OccasionRequest $request, Occasion $occasion) :RedirectResponse
    {
        $data = $request->all();
        $occasion->update($data);
//        OccasionDescription::where('occasion_id', $occasion->id)->delete();
//        $this->saveData( $request, $occasion->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param OccasionRequest $request
     * @param int $occasion_id
     * @return void
     */

     private function saveData(OccasionRequest $request, int $occasion_id ) :void
     {

        $requestData= $request->all();

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

            OccasionDescription::create($data);
        }

     }

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

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

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

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

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

    }

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