<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Slider;
use App\Models\WebsiteSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class SliderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', WebsiteSetting::class);
        if ($request->ajax()) {
            // dd($request->all());
            $draw = $request->get('draw');
            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = Slider::select('count(*) as allcount')->count();
            $totalRecordswithFilter = Slider::select('count(*) as allcount')
                ->when($searchValue , function ($q) use ($searchValue){
                    $q->where('title', 'like', '%' . $searchValue . '%')
                    ->orWhere('title_ar', 'like', '%' . $searchValue . '%');
                })
                ->count();

            $sliders = Slider::select('sliders.*')
                ->when($searchValue , function ($q) use ($searchValue){
                    $q->where('title', 'like', '%' . $searchValue . '%')
                    ->orWhere('title_ar', 'like', '%' . $searchValue . '%');
                })
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('sliders.id', 'desc')
                ->get();


            $records = [];

            foreach($sliders as $item)
            {
                $records[] = [
                    'record_select' =>view('admin.sliders.datatable.record',[ 'item' => $item ])->render(),
                    'id' => $item->id,
                    'image' => $item->image ? '<img src="'. asset('storage/'.$item->image) .'" width="100">' : __('No image uploaded'),
                    'title' => \LaravelLocalization::getCurrentLocale() == 'ar' ? ($item->title_ar ? $item->title_ar : __('No Added')) :( $item->title ? $item->title : __('No Added')),
                    'actions' => view('admin.sliders.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

            $response = [
                "draw" => intval($draw),
                "iTotalRecords" => $totalRecords,
                "iTotalDisplayRecords" => $totalRecordswithFilter,
                "aaData" => $records
            ];

            return response()->json($response);

        }

        return view('admin.sliders.index');
    }

    public function store(Request $request)
    {
        # code...
        $this->authorize('viewAny', WebsiteSetting::class);
        // dd($request->all());
        $request->validate([
            'image' => 'required|mimes:png,jpg,jpeg',
            'title' => 'nullable|string|max:255',
            'title_ar' => 'nullable|string|max:255',
            'sub_title' => 'nullable|string|max:255',
            'sub_title_ar' => 'nullable|string|max:255',
            'description' => 'nullable',
            'description_ar' => 'nullable',
            'link' => 'nullable|url',
        ]);

        $data = $request->all();
        $image = null;

        if($request->hasFile('image') && $request->file('image')->isValid()){
            $image = $request->file('image')->store('/','sliders' );
            $data['image'] ='sliders/'. $image;
        }

        Slider::create($data);

        return redirect()->route('c-panel.sliders.index')->with('success', __('Added Done !'));
    }

    public function update(Request $request, Slider $slider)
    {
        # code...
        $this->authorize('viewAny', WebsiteSetting::class);
        $request->validate([
            'image' => 'nullable|mimes:png,jpg,jpeg',
            'title' => 'nullable|string|max:255',
            'title_ar' => 'nullable|string|max:255',
            'sub_title' => 'nullable|string|max:255',
            'sub_title_ar' => 'nullable|string|max:255',
            'description' => 'nullable',
            'description_ar' => 'nullable',
            'link' => 'nullable|url',
        ]);

        $data = $request->all();
        $image = $slider->image;

        if($request->hasFile('image') && $request->file('image')->isValid()){
            if($slider->image)
                Storage::disk('public')->delete($slider->image);
                $image = $request->file('image')->store('/','sliders' );
                $data['image'] ='sliders/'. $image;
        }

        $slider->update($data);

        return redirect()->route('c-panel.sliders.index')->with('success', __('Updated Done !'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy( Slider $slider)
    {
        // $this->authorize('delete', $department);
        $this->authorize('viewAny', WebsiteSetting::class);
        if($slider->image)
            Storage::disk('public')->delete($slider->image);
        $slider->delete();
        return redirect()->route('c-panel.sliders.index')->with('success',__('Deleted Done !'));
    }

    public function bulkDelete()
    {
        // dd(json_decode(request()->record_ids));
        $this->authorize('viewAny', WebsiteSetting::class);
        if(count(json_decode(request()->record_ids)) != 0){
            foreach (json_decode(request()->record_ids) as $recordId) {
                $slider = Slider::FindOrFail($recordId);
                // $this->authorize('delete', $slider);
                $this->delete($slider);
            }//end of for each
        }else{
            return redirect()->route('c-panel.sliders.index')->with('error',__('Please Select Record Before Delete'));
        }

        return redirect()->route('c-panel.sliders.index')->with('success',__('Selected  Deleted Done !'));
    }// end of bulkDelete

    private function delete(Slider $slider)
    {
        // $this->authorize('delete', $slider);
        $this->authorize('viewAny', WebsiteSetting::class);
        if($slider->image)
            Storage::disk('public')->delete($slider->image);
        $slider->delete();
    }
}
