<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Department;
use Illuminate\Http\Request;

class DepartmentsController extends Controller
{
    //

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

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


            $records = [];

            foreach($departments as $item)
            {
                $records[] = [
                    'record_select' =>view('admin.departments.datatable.record',[ 'item' => $item ])->render(),
                    'id' => $item->id,
                    'name' => $item->name,
                    'actions' => view('admin.departments.datatable.buttons',[ 'item' => $item ])->render() ,
                ];
            }

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

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

        }

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

    public function store(Request $request)
    {
        $this->authorize('create', Department::class);
        $request->validate([
            'name' => 'required|string|max:255',
        ]);


        Department::create([
            'name' => $request->name,
        ]);

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


    public function update(Request $request, Department $department)
    {
        # code...
        $this->authorize('update', $department);
        $request->validate([
            'name' => 'required|string|max:255',
        ]);

        $department->update([
            'name' => $request->name,
        ]);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Department $department)
    {
        $this->authorize('delete', $department);
        $department->delete();
        return redirect()->route('c-panel.departments.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) {
                $department = Department::FindOrFail($recordId);
                $this->authorize('delete', $department);
                $this->delete($department);
            }//end of for each
        }else{
            return redirect()->route('c-panel.departments.index')->with('error',__('Please Select Record Before Delete'));
        }

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

    private function delete(Department $department)
    {
        $this->authorize('delete', $department);
        $department->delete();
    }
}
