<?php

namespace App\Http\Controllers\Admin;

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

class GroupsController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', Group::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 = Group::select('count(*) as allcount')->count();
            $totalRecordswithFilter = Group::select('count(*) as allcount')
                ->where('name', 'like', '%' . $searchValue . '%')
                ->count();

            $groups = Group::select('groups.*')
                ->where('name', 'like', '%' . $searchValue . '%')
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('groups.id', 'desc')
                ->get();


            $records = [];

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

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

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

        }

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


    public function store(Request $request)
    {
        $this->authorize('create', Group::class);
        $request->validate([
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'image' => 'required|mimes:png,jpg,jpeg,svg',
            'description' => 'string|nullable',
            'description_ar' => 'string|nullable',
        ]);
        $data = $request->all();

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


        Group::create($data);

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


    public function update(Request $request, Group $group)
    {
        # code...
        $this->authorize('update', $group);
        $request->validate([
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'image' => 'nullable|mimes:png,jpg,jpeg,svg',
            'description' => 'string|nullable',
            'description_ar' => 'string|nullable',
        ]);

        $data = $request->except('image');

        if($request->hasFile('image') && $request->file('image')->isValid())
        {
            if($group->image)
                Storage::disk('public')->delete($group->image);

            $image = $request->file('image')->store('groups', 'public');
            $data['image'] = $image;
        }

        $group->update($data);

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

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

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

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

    private function delete(Group $group)
    {
        $this->authorize('delete', $group);
        if($group->image)
                Storage::disk('public')->delete($group->image);
        $group->delete();
    }

}
