<?php

use App\Models\Admin;
use App\Models\AdminAuth;
use App\Models\AdminToken;
use App\Models\Auth;

class Login
{
    public static $info;
    public static $login_type;
    public static $token_info;

    public static function check_admin_auth($auth_id = 0): int
    {
        if (self::$info->admin_auth_id === -1) return 0;
        $auth = Auth::where('id', $auth_id)->where('status', 1)->where('del', 2)->first();
        if (!$auth) return 100003;
        if (self::$info->admin_auth_id === 0) {
            if ($auth->check_type !== 1) return 100003;
        } else {
            if ($auth->check_type === 1) return 0;
            $admin_auth = AdminAuth::select('id')
                ->where('id', self::$info->admin_auth_id)
                ->where('auth_ids', 'like', "%\"$auth_id\"%")
                ->where('del', 2)
                ->first();
            if (!$admin_auth) return 100003;
        }
        return 0;
    }

    public static function admin_check($auth_ids = [], $or_ids = []): int
    {
        if (!request()->header('Authorization')) return 100001;
        $header_token_arr = explode('Bearer ', request()->header('Authorization'));
        if (!isset($header_token_arr[1])) return 100001;
        $header_token = $header_token_arr[1];
        if (!$header_token) return 100001;
        $admin_token_info = AdminToken::where('token', $header_token)->where('del', 2)->where('updated_at', '>', Lu::date(time() - (60 * 60 * 24 * 3)))->first();
        if (!$admin_token_info) return 100001;
        $admin_info = Admin::where('id', $admin_token_info->admin_id)->where('del', 2)->where('status', 1)->first();
        if (!$admin_info) return 100002;
        self::$info = $admin_info;
        self::$login_type = $admin_token_info->type;
        self::$token_info = $admin_token_info;
        foreach ($auth_ids as $item) {
            $auth_check_res = self::check_admin_auth($item);
            if ($auth_check_res != 0) return $auth_check_res;
        }
        $ret = 0;
        $ret_code = 0;
        foreach ($or_ids as $item) {
            $auth_check_res = self::check_admin_auth($item);
            if ($auth_check_res == 0) $ret++;
            if ($auth_check_res != 0) $ret_code = $auth_check_res;
        }
        if ($ret == 0 && $ret_code != 0) return $ret_code;
        $admin_token_info->updated_at = Lu::date();
        $admin_token_info->save();
        return 0;
    }

    public static function admin($auth_ids = [], $or_ids = [])
    {
        $check_res = self::admin_check($auth_ids, $or_ids);
        if ($check_res != 0) Yo::error_echo($check_res);
    }
}
