<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\SliderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class SliderController extends Controller
{
     public function slider()
    {
        $records   =  SliderModel::orderBy('id', 'ASC')->get();
        return view('backend.slider.list', compact('records'));
    }

    public function addSlider($id = '')
    {
        $record = '';
        if ($id > 0) {
            $record = SliderModel::Where('id', $id)->first();
        }
        return view('backend.slider.add_edit', compact('record'));
    }

    public function storeUpdateSlider(Request $request)
    {
        $input     = $request->all();
        $id        = isset($input['id']) ? $input['id'] : 0;

        $dataArr = [];
        foreach ($input as $key => $val) {
            if ($key != '_token' && $key != 'id' && $key != 'slider_image')
                $dataArr[$key] = $val;
        }

        if ($request->file('slider_image') != '') {
            $image = $request->file('slider_image');
            $imageName = 'slider_' . time() . '_' . str_replace(' ', '_', $image->getClientOriginalName());
            $image->move(public_path('/uploads/slider_image/'), $imageName);
            $imageUrl = URL::to('/') . '/uploads/slider_image/' . $imageName;
            $dataArr['slider_img'] = $imageUrl;
        }
        if ($id == 0 || $id == '') {
            $request->validate([
                'slider_caption'          =>  "required",
                'slider_type'    =>  "required",               
                // 'currency_code' =>  "required|unique:countries,currency_code",
            ]);
           $insert = SliderModel::create($dataArr);
           if($insert['id'] > 0)
           {
               return redirect()->route('slider')->with('success', 'Slider Saved Successfully');
           }else{
               return redirect()->route('slider')->with('error', 'Something went wrong!');
           }
           
        } else {
            $request->validate([
                'name'          =>  "required",
                'phone_code'    =>  "required",
                'currency_name' =>  "required",
                'currency_code' =>  "required",
            ]);
            $update = SliderModel::Where('id',$id)->update($dataArr);
            return redirect()->route('slider')->with('success', 'Slider Updated Successfully');;
        }        
    }
}
