<?php

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Slider;
use App\Models\Translation\SliderTranslation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SlidersController extends Controller
{

    public function index(Request $request)
    {
       $this->authorize('admin_settings_personalization');

        $navbarButtons = Slider::query()->get();

        $defaultLocal = getDefaultLocale();
        $locale = $request->get('locale', mb_strtolower($defaultLocal));

        $data = [
            'pageTitle' => trans('admin/main.sliders'),
            'sliders' => $navbarButtons,
            'name' => 'sliders',
            'selectedLocale' => $locale
        ];

        return view('admin.settings.personalization', $data);
    }

    
    public function store(Request $request)
    {
        $this->authorize('admin_settings_personalization');

        $itemId = $request->get('item_id');

        $this->validate($request, [
            'text'=>'required',
            'title' => 'required',
            'button_title' => 'required',
            'url' => 'required',
            'image' => 'required|string',
        ]);

        $data = $request->all();

        $slider = Slider::where('id', $itemId)->first();
        
        if (empty($slider)) {
            $slider = Slider::create([
                'url' => $data['url'],
                'image'=>$data['image']
            ]);
        }
        else {
            $slider->update([
                'url' => $data['url'],
                'image'=>$data['image']
            ]);
        }

        SliderTranslation::updateOrCreate([
            'slider_id' => $slider->id,
            'locale' => mb_strtolower($data['locale']),
        ], [
            'title' => $data['title'],
            'text' => $data['text'],
            'button_title'=>$data['button_title']
        ]);

        return redirect('/admin/settings/personalization/sliders');
    }
    
    public function edit(Request $request,$id){
        $this->authorize('admin_settings_personalization');

        $slider = Slider::findOrFail($id);

        $defaultLocal = getDefaultLocale();
        $locale = $request->get('locale', mb_strtolower($defaultLocal));
        storeContentLocale($locale, $slider->getTable(), $slider->id);

        $data = [
            'pageTitle' => trans('admin/main.sliders'),
            'slider' => $slider,
            'name' => 'sliders',
            'selectedLocale' => $locale,
        ];

        return view('admin.settings.personalization', $data);
    }
    
    public function delete($id)
    {
        $this->authorize('admin_settings_personalization');

        $navbarButton = Slider::findOrFail($id);

        $navbarButton->delete();

        return redirect('/admin/settings/personalization/sliders');
    }
}
