<?php

namespace App\Http\Resources;

use App\Helpers\Helper;
use App\Models\Group;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;

class GroupResource extends JsonResource
{
    public function toArray($request)
    {
        $detail = Group::select(
            'groups.id',
            'groups.user_id',
            'groups.co_id',
            'users.name',
            'groups.branch_id'
        )
        ->leftjoin('users','users.id','groups.co_id')
        ->where(function($query){
            if(Auth::user()->branch_id!=1){
                $query->whereIn('groups.branch_id',Helper::byBranch());
            }
        })
        ->whereIn('groups.branch_id',Helper::byBranch())
        ->where('user_id', $this->user_id)
        ->where('groups.status',1)
        ->get();

        $datail_branch = Group::select(
            'branches.name_km',
            'groups.branch_id'
        )
        ->leftjoin('users','users.id','groups.co_id')
        ->leftjoin('branches','branches.id','groups.branch_id')
        ->where('user_id', $this->user_id)
        ->where('groups.status',1)
        ->groupby('groups.branch_id')
        ->get();

        
        return [
            'id'        => $this->id,
            'user_id'   => $this->user_id,
            'name'      => $this->user->name,
            'detail'    => $detail,
            'status'    => $this->status,
            'detail_branch'=> $datail_branch??[],
            'branch_name'  => $this->branchs->name_km??'',
        ];
    }
}