<?php

namespace App\Http\Controllers\Admin;

use App\HomeInfo;
use App\HomeInfoDescription;
use App\Http\Requests\ProductRequest;
use App\Page;
use Exception;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Requests\PageRequest;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;

class HomeInfoController extends Controller
{

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

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

    /**
     * return data of the homeInfos.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = HomeInfo::join('home_info_descriptions AS hid', 'home_infos.id', 'hid.home_info_id')
            ->where('hid.language_id', currentLanguage()->id)
            ->select(['hid.advantage_box_1_title', 'home_infos.*']);

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

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

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

        $homeInfos = $query->cursor();

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

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

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


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

        $query = HomeInfoDescription::where('home_info_id', $homeInfo->id)
            ->join('languages', 'languages.id', 'home_info_descriptions.language_id')
            ->select(['home_info_descriptions.*', 'languages.local']);

        $homeInfoDescription= $query->get();

        foreach ($homeInfoDescription as $row) {
            $homeInfo[$row->local]= $row;
        }

        $firstBoxes = array_key_exists('first_box_points', $homeInfo->points) ? $homeInfo->points['first_box_points'] : [];
        $secondBoxes = array_key_exists('second_box_points', $homeInfo->points) ? $homeInfo->points['second_box_points'] : [];
        $thirdBoxes = array_key_exists('third_box_points', $homeInfo->points) ? $homeInfo->points['third_box_points'] : [];
        $fourthBoxes = array_key_exists('fourth_box_points', $homeInfo->points) ? $homeInfo->points['fourth_box_points'] : [];


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

    /**
     * Update the specified resource in storage.
     *
     * @param ProductRequest $request
     * @param HomeInfo $homeInfo
     * @return JsonResponse
     */
    public function update(ProductRequest $request, HomeInfo $homeInfo) :JsonResponse
    {
        // Update image if request has it
        $data = $request->all();

        $data['points'] = [];
        if ($request->first_box_points){
            $data['points']['first_box_points'] = $request->first_box_points;
        }
        if ($request->second_box_points){
            $data['points']['second_box_points'] = $request->second_box_points;
        }
        if ($request->third_box_points){
            $data['points']['third_box_points'] = $request->third_box_points;
        }
        if ($request->fourth_box_points){
            $data['points']['fourth_box_points'] = $request->fourth_box_points;
        }

        $homeInfo->update($data);

        // Delete old description
        HomeInfoDescription::where('home_info_id', $homeInfo->id)->delete();

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

        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('homeInfos.index')]);
    }

    /**
     * Handle Save form data
     *
     * @param PageRequest $request
     * @param int $home_info_id
     * @return void
     */

    private function saveData(ProductRequest $request, int $home_info_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'advantage_box_1_title'=> $requestData['advantage_box_1_title_'.$lang->local],
                'advantage_box_1_description'=> $requestData['advantage_box_1_description_'.$lang->local],
                'advantage_box_2_title'=> $requestData['advantage_box_2_title_'.$lang->local],
                'advantage_box_2_description'=> $requestData['advantage_box_2_description_'.$lang->local],
                'advantage_box_3_title'=> $requestData['advantage_box_3_title_'.$lang->local],
                'advantage_box_3_description'=> $requestData['advantage_box_3_description_'.$lang->local],
                'advantage_box_4_title'=> $requestData['advantage_box_4_title_'.$lang->local],
                'advantage_box_4_description'=> $requestData['advantage_box_4_description_'.$lang->local],
                'advantage_box_5_title'=> $requestData['advantage_box_5_title_'.$lang->local],
                'advantage_box_5_description'=> $requestData['advantage_box_5_description_'.$lang->local],
                'advantage_box_6_title'=> $requestData['advantage_box_6_title_'.$lang->local],
                'contact_box_title'=> $requestData['contact_box_title_'.$lang->local],
                'advantage_box_6_description'=> $requestData['advantage_box_6_description_'.$lang->local],
                'social_service_box_1_title'=> $requestData['social_service_box_1_title_'.$lang->local],
                'social_service_box_1_description'=> $requestData['social_service_box_1_description_'.$lang->local],
                'social_service_box_2_title'=> $requestData['social_service_box_2_title_'.$lang->local],
                'social_service_box_2_description'=> $requestData['social_service_box_2_description_'.$lang->local],
                'social_service_box_3_title'=> $requestData['social_service_box_3_title_'.$lang->local],
                'social_service_box_3_description'=> $requestData['social_service_box_3_description_'.$lang->local],
                'social_service_box_4_title'=> $requestData['social_service_box_4_title_'.$lang->local],
                'social_service_box_4_description'=> $requestData['social_service_box_4_description_'.$lang->local],
                'contact_box_description'=> $requestData['contact_box_description_'.$lang->local],
                'home_info_id'=> $home_info_id,
                'language_id'=> $lang->id,
            ];
            HomeInfoDescription::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);
        }

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

    /**
     * Remove several homeInfos 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) {
            HomeInfo::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            HomeInfo::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
    {
        $homeInfo = HomeInfo::withTrashed()->find($id);

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

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