<?php


namespace App\Api\Http\Controllers\Api\V1\Branch;

use App\Api\Http\Resources\Branch\BranchCollection;

use App\Branch;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\QueryBuilder\QueryBuilder;

class BranchController extends Controller
{
    public function index()
    {
        $branches = QueryBuilder::for(Branch::class)
            ->where('status', 1)
            ->get();
    
        $all = [
            'id' => '',
            'name' => 'All'
        ];

        $merge = array_merge([$all], $branches->toArray());
        $data = array_map(function ($item) {
            return is_array($item) ? (object)$item : $item;
        }, $merge);
    
        return [
            'data' => new BranchCollection($data),
            'message' => 'Branches',
        ];
    }
    public function salesHeadBranch()
    { 
        $authUser = auth()->user();
        $userIds = $authUser->getAllReportingUsersIds();
        $users = User::whereIn('id',$userIds)->get();
       
        foreach ($users as $user){
            $branchId[] = $user->branch_id;
        }
    
        $branches = QueryBuilder::for(Branch::class)
            ->where('status', 1)
            ->whereIn('id',$branchId)
            ->get();
    
        $all = [
            'id' => '',
            'name' => 'All'
        ];

        $merge = array_merge([$all], $branches->toArray());
        $data = array_map(function ($item) {
            return is_array($item) ? (object)$item : $item;
        }, $merge);
    
        return [
            'data' => new BranchCollection($data),
            'message' => 'Branches',
        ];
    }
    
}
