<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use Exception;
use App\WbSetting;
use Illuminate\View\View;
use App\WbSettingDescription;
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\WbSettingRequest; // for Validation
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class WbSettingController extends Controller
{

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

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

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

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

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

        if ($request->key) {
            $query->where('key', 'LIKE', '%'.$request->key.'%');
        }
        if ($request->value) {
            $query->where('cd.value', 'LIKE', '%'.$request->value.'%');
        }

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

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

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

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

        $wbSetting = WbSetting::create(['key'=>$request->key]);
       
        // Insert Description
        $this->saveData( $request, $wbSetting->id );

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

    /**
     * Show the form for editing the specified WbSetting.
     *
     * @param  WbSetting  $wbSetting
     * @return View
     */
    public function edit(WbSetting $wbsetting) :View
    {
        $action= route('wbsettings.update', $wbsetting->id);
        $head = 'Edit Web Site Setting';
        $query = WbSettingDescription::where('wbsetting_id', $wbsetting->id)
        ->join('languages', 'languages.id', 'wbsetting_descriptions.language_id')
        ->select(['wbsetting_descriptions.*', 'languages.local']);

        $WbSettingDescription= $query->get();

        foreach ($WbSettingDescription as $row) {
            $wbsetting[$row->local]= $row;
        }

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

    /**
     * Update the specified WbSetting in storage.
     * @param WbSettingRequest $request
     * @param WbSetting $wbSetting
     * @return RedirectResponse|Redirector
     */
    public function update(WbSettingRequest $request, WbSetting $wbsetting) :RedirectResponse
    {
        
        WbSettingDescription::where('wbsetting_id', $wbsetting->id)->delete();

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

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

    /**
     * Handle Save form data
     *
     * @param WbSettingRequest $request
     * @param int $wbsetting_id
     * @return void
     */

     private function saveData(WbSettingRequest $request, int $wbsetting_id ) :void
     {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'wbsetting_id'=> $wbsetting_id,
                'language_id'=> $lang->id,
                'value'=> $requestData['value_'.$lang->local],
                
            ];

            WbSettingDescription::create($data);
        }

     }

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

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

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

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

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

    }

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