<?php

namespace App\Http\Controllers\Admin;

use App\Models\Group;
use App\Helpers\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\GroupResource;

class ManageGroupCoController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:Manage Group CO List', ['only' => ['index']]);
        $this->middleware('permission:Manage Group CO Create', ['only' => ['store']]);
        $this->middleware('permission:Manage Group CO Edit', ['only' => ['store']]);
        $this->middleware('permission:Manage Group CO Delete', ['only' => ['destroy']]);
    }

    public function index(Request $request)
    {
        $page_size = $request->page_size == null?25: $request->page_size;
        $data = Group::whereHas('user',function($query) use ($request){
            if(!$request->search_text ==''){
                $query->where('name', 'LIKE', '%'.$request->search_text.'%');
            }
            $query->whereIn('branch_id',Helper::byBranch());
        })
        ->orWhereHas('CO',function($query) use ($request){
            $query->where('name', 'LIKE', '%'.$request->search_text.'%');
        })
        ->whereIn('co_id',Helper::group())
        ->where('status',1)
        ->groupBy('user_id')
        ->orderBy('id','DESC')
        ->paginate($page_size);
        return GroupResource::collection($data);
    }

    public function create(Request $request)
    {
        $group = Group::find($request->id);
        if($group){
            $res = [
                'status' => 1,
                'message'=> 'Get group success',
                'data'   => new GroupResource($group),
            ];
        }else{
            $res = [
                'status'  => 0,
                'message' => 'Get group not found',
                'data'    => [],
            ];
        }
        return response()->json($res,200);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'co_id'   => 'required',
            'user_id' => 'required ',
        ]);
        try{
            DB::beginTransaction();
            $id = [];
            foreach($request->co_id as $value){
                $qroup = Group::updateOrCreate(
                    [
                        'co_id'   => $value,
                        'user_id' => $request->user_id,
                    ],
                    [
                        'user_id' => $request->user_id,
                        'co_id'   => $value,
                    ]
                );
                $id[] = $qroup->id;
            }
            Group::where('user_id',$request->user_id)->whereNotIn('id',$id)->delete();
            $data = Group::where('user_id',Auth::user()->id)->get();
            DB::commit();
            $res = [
                'status' => 1,
                'message'=> !isset($request->id)?'Create manage group co success':'Update manage group co success',
                'data'   => GroupResource::collection($data),
            ];
        }catch(\Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Create co not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    public function destroy($user_id)
    {
        DB::beginTransaction();
        try {

            $client = Group::where('user_id',$user_id)->delete();
            $res = [
                'status' => 1,
                'message'=> 'Deleted success',
                'data'   => $client,
            ];
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Deleted not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }
}