<?php

namespace App\Models;

use Illuminate\Support\Facades\Auth;

class Project extends BaseModel
{

    public function getManager()
    {
        $role = ProjectRole::getByKey('manager');
        if(!$role) return null;
        $res = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['project_role_id', '=', $role->id]
        ])->first();
        if($res) return User::find($res['user_id']);
        return false;
    }

    public function getUserProjectRole()
    {
        $user = Auth::guard('mini')->user();
        $project_user = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['user_id', '=', $user->id]
        ])->first();
        if($project_user) {
            return ProjectRole::find($project_user->project_role_id);
        }
        return null;
    }

    public function isTopLevel($user)
    {
        $current_role = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['user_id', '=', $user->id]
        ])->first();
        if(empty($current_role)) return false;
        $res = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['project_role_id', '>', $current_role['project_role_id']]
        ])->first();
        return $res ? false : true;
    }

    /**
     * @param User $user
     * @param $type: current/next
     * @return ProjectUser
     */
    public function getProjectUser(User $user, $type = 'current')
    {
        $current = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['user_id', '=', $user['id']]
        ])->first();
        if($type == 'current' || !$current) return $current;
        $next = ProjectUser::where([
            ['project_id', '=', $this['id']],
            ['project_role_id', '>', $current['project_role_id']]
        ])->first();
        return $next ? $next : $current;
    }

    public function getCreateProjectRoleId(User $user, $is_draft)
    {
        $project_user = $this->getProjectUser($user, $is_draft == 1 ? 'current' : 'next');
        return $project_user ? $project_user['project_role_id'] : '';
    }

    public static function getOptions()
    {
        return self::where('id', '>', 0)->get()->toArray();
    }

    public function createDefaultUser()
    {
        $user_id = $this['user_id'];
        ProjectUser::where('project_id', $this['id'])->delete();
        ProjectUser::create([
            'project_id' => $this['id'],
            'user_id' => $user_id,
            'project_role_id' => ProjectRole::getByKey('manager', 'id')
        ]);
        $project_user = ProjectUser::where('project_role_id', ProjectRole::getByKey('admin', 'id'))->first();
        if($project_user) {
            ProjectUser::create([
                'project_id' => $this['id'],
                'user_id' => $project_user->user_id,
                'project_role_id' => $project_user->project_role_id
            ]);
        }
    }
}
