<?php

namespace App\Repositories\Core\Auth;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Laratrust\Traits\LaratrustUserTrait;
use Yajra\DataTables\DataTables;

use App\Models\Core\Auth\Team;
use App\Models\Core\Auth\TeamUser;

use App\Repositories\Users;

class Teams
{
    use LaratrustUserTrait;

    public static function getTeamsByUser($user_id = false)
    {
        $user_id = $user_id ? $user_id : Users::getId();
        return TeamUser::byUser($user_id);
    }

    public static function getUsersByTeam($id)
    {
        return TeamUser::byTeam($id)->get();
    }

    public static function getUsersIdByTeam($id)
    {
        return self::getUsersByTeam($id)->pluck('user_id');
    }

    public static function getUsersByTeam2($id)
    {
        return Team::find($id)->users();
    }

    public static function getOptions()
    {
        return Team::orderBy('name', 'asc')->get()->pluck('name', 'id')->toArray();
    }

    public static function getInfo($id)
    {
        return Team::find($id);
    }

    public static function select_all()
    {
        return self::getAll()->toArray();
    }

    public static function select_by_id($id)
    {
        return Team::find($id)->toArray();
    }

    public static function getAll()
    {
        return Team::orderBy('name', 'asc')->get();
    }

    public static function getByName($name)
    {
        return Team::where('name', $name)->first();
    }

    public static function get($id)
    {
        return Team::find($id);
    }

    public static function getTable($id)
    {
        $datas = Team::with(['societe'])->withCount(['users']);
        return Datatables::of($datas)->make(true);
    }

    public static function delete($id)
    {
        Users::destroyByUniqueTeam($id);
        return Team::destroy($id);
    }

    public static function destroyBySociete($id)
    {
        $teams = Team::bySociete($id)->get();
        foreach ($teams as $team) {
            self::delete($team->id);
        }
    }

    public static function store($data)
    {
        if (isset($data['id']) && $data['id']) {
            return self::update($data);
        }
        return self::create($data);
    }

    public static function create($data)
    {
        return Team::create($data);
    }

    public static function update($data)
    {
        return Team::find($data['id'])->update($data);
    }

    public static function count()
    {
        return Team::count();
    }

    public static function toggle_active($id, $active)
    {
        return Team::find($id)->update(['active' => $active]);
    }
}
