<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Users extends Authenticatable
{
    protected $table = "t_users";
    const ROLE_SU = 1; // unused
    const ROLE_SUPERADMIN = 7;
    const ROLE_ADMIN = 2;
    const ROLE_VENDOR = 8;
    const ROLE_CHECKER = 9;
    const ROLE_USER = 3; // unused
    const ROLE_CLIENT_ADMIN = 4;
    const ROLE_VENDOR_DRIVER = 12;
    const ROLE_CLIENT_STAFF = 5; // unused
    const ROLE_CLIENT_USER = 6; // unused
    const ROLE_SPECIAL_TRACKING = 10;
    const ROLE_FINANCE = 11;

    const STATUS_ACTIVE = 1;
    const STATUS_NOT_ACTIVE = 2;
    const STATUS_SUSPEND = 3;

    const CHK_TYPE_PICKUP = 1;
    const CHK_TYPE_DROP = 2;
    const CHK_TYPE_ALL = 3;

    const IS_TRACK_VHC_NO = 0;
    const IS_TRACK_VHC_YES = 1;
    const IS_TRACK_VHC_DEFAULT = 2;

    const IS_VDR_BCNG_NO = 0;
    const IS_VDR_BCNG_YES = 1;

    const DEFAULT_UID = 1; // swanusa account

    const DEFAULT_PHONE_CODE = 62;

    const defaultSelected = "
        u.*
        ,c.c_name AS client_group_name
        ,c.id AS client_group_id
        -- ,r.name as role_name
        ,rl.id AS role_id
        ,rl.name AS role_name
    ";

    public static function listUsers($filter = [])
    {
        $select_select = "";
        $join_join = "";
        $where_where = "";
        $other_other = "";
        $params = [];

        if (isset($filter["role"])) {
            $where_where .= " AND u.role = ?";
            $params[] = $filter["role"];
        }
        if (isset($filter["id"])) {
            $where_where .= " AND u.id = ?";
            $params[] = $filter["id"];
        }

        if (isset($filter["status"])) {
            $where_where .= " AND u.status = ?";
            $params[] = $filter["status"];
        }

        if (isset($filter["company"])) {
            $where_where .= " AND c.id = ?";
            $params[] = $filter["company"];
        }

        if (isset($filter["group_by_client_pt_id"])) {
            $other_other .= " GROUP BY c.id";
        }

        return DB::select(
            " SELECT " .
                Users::defaultSelected .
                "
                $select_select
				, ul.lastLogin
                FROM t_users AS u
                LEFT JOIN t_clients AS c ON u.client_group_id = c.id
                -- LEFT JOIN t_users_roles AS r ON u.role = r.id
                LEFT JOIN model_has_roles AS mhr ON mhr.model_id = u.id
                LEFT JOIN roles as rl ON rl.id = mhr.role_id
                $join_join
                left join (select userId, max(crt) lastLogin from t_user_log where log->'$.desc' = 'User login' group by userId) ul
					on ul.userId = u.id
                WHERE u.dlt is null
                $where_where
                $other_other
            ;",
            $params
        );
    }

    public static function listUsersByRole($role)
    {
        return DB::select(
            "SELECT
        " .
                Users::defaultSelected .
                "
        FROM t_users AS u
        LEFT JOIN t_clients AS c ON u.client_group_id = c.id
        -- LEFT JOIN t_users_roles AS r ON u.role = r.id
        LEFT JOIN model_has_roles AS mhr ON mhr.model_id = u.id
        LEFT JOIN roles as rl ON rl.id = mhr.role_id
        WHERE u.dlt is null
        AND u.role =  ? ;",
            [$role]
        );
    }

    public static function getUsers()
    {
        return DB::select("SELECT * FROM t_users WHERE dlt is null;");
    }

    public static function getUsersActiveByRole($role)
    {
        return DB::select(
            "SELECT * FROM t_users WHERE dlt is null AND status = " . Users::STATUS_ACTIVE . " AND role = ?;",
            [$role]
        );
    }

    public static function getUserById($uid)
    {
        return DB::select("SELECT * FROM t_users WHERE dlt is null AND id = ? LIMIT 1;", [$uid]);
    }

    public static function showUserById($uid)
    {
        return DB::select(
            "SELECT
        " .
                Users::defaultSelected .
                "
        FROM t_users AS u
        LEFT JOIN t_clients AS c ON u.client_group_id = c.id
        -- LEFT JOIN t_users_roles AS r ON u.role = r.id
        LEFT JOIN model_has_roles AS mhr ON mhr.model_id = u.id
        LEFT JOIN roles as rl ON rl.id = mhr.role_id
        WHERE u.dlt is null
        AND u.id = ?
        LIMIT 1;",
            [$uid]
        );
    }

    public static function getUserByEmail($email)
    {
        return DB::select("SELECT * FROM t_users WHERE dlt is null AND email = ? LIMIT 2;", [$email]);
    }

    public static function getUserByPhone($phone)
    {
        return DB::select("SELECT * FROM t_users WHERE dlt is null AND phone = ? LIMIT 2;", [$phone]);
    }

    public static function getUserByClientId($cid)
    {
        return DB::select("SELECT * FROM t_users WHERE dlt is null AND client_id = ? LIMIT 1;", [$cid]);
    }

    public static function getUserByGroupClientId($cid)
    {
        return DB::select("SELECT * FROM t_users WHERE dlt is null AND client_group_id = ? LIMIT 1;", [$cid]);
    }

    public static function likeName($name, $role = 0)
    {
        $params = ["%" . $name . "%", "%" . $name . "%"];
        $where = "";

        if ($role !== 0) {
            $where .= " AND role = ?";
            $params[] = $role;
        }

        return DB::select(
            "SELECT * FROM t_users WHERE dlt is null AND (first_name LIKE ? OR last_name LIKE ?) $where;",
            $params
        );
    }

    public static function addUser($data)
    {
        $uid = DB::table("t_users")->insertGetId($data);
        return $uid;
    }

    public static function updateUser($uid, $data)
    {
        return DB::table("t_users")
            ->where("id", $uid)
            ->update($data);
    }

    public static function updateUsersByGroupClientId($cid, $data)
    {
        return DB::table("t_users")
            ->where("client_group_id", $cid)
            ->update($data);
    }

    public static function deleteUser($uid, $data)
    {
        return DB::table("t_users")
            ->where("id", $uid)
            ->delete();
    }

    public static function arrStatus()
    {
        return [Users::STATUS_ACTIVE, Users::STATUS_NOT_ACTIVE];
    }

    public static function arrRoles()
    {
        return [
            Users::ROLE_SU,
            Users::ROLE_SUPERADMIN,
            Users::ROLE_ADMIN,
            Users::ROLE_FINANCE,
            Users::ROLE_VENDOR,
            Users::ROLE_CHECKER,
            Users::ROLE_USER,
            Users::ROLE_CLIENT_ADMIN,
            Users::ROLE_CLIENT_STAFF,
            Users::ROLE_CLIENT_USER,
            Users::ROLE_SPECIAL_TRACKING,
        ];
    }

    public static function listRoles($currentRole)
    {
        if ($currentRole == Users::ROLE_SUPERADMIN) {
            return DB::select(
                "SELECT * FROM t_users_roles WHERE dlt is null AND status = 1 AND id IN (?,?,?,?,?,?);",
                [
                    // Users::ROLE_SUPERADMIN,
                    Users::ROLE_ADMIN,
                    Users::ROLE_FINANCE,
                    Users::ROLE_VENDOR,
                    Users::ROLE_CHECKER,
                    Users::ROLE_CLIENT_ADMIN,
                    Users::ROLE_SPECIAL_TRACKING,
                ]
            );
        } elseif ($currentRole == Users::ROLE_ADMIN) {
            return DB::select(
                "SELECT * FROM t_users_roles WHERE dlt is null AND status = 1 AND id IN (?,?,?,?,?,?);",
                [
                    Users::ROLE_ADMIN,
                    Users::ROLE_FINANCE,
                    Users::ROLE_VENDOR,
                    Users::ROLE_CHECKER,
                    Users::ROLE_CLIENT_ADMIN,
                    Users::ROLE_SPECIAL_TRACKING,
                ]
            );
        } elseif ($currentRole == Users::ROLE_CLIENT_ADMIN) {
            // return DB::select("SELECT * FROM t_users_roles WHERE dlt is null AND id IN (?,?);", [
            //     Users::ROLE_CLIENT_STAFF,
            //     Users::ROLE_CLIENT_USER,
            // ]);
        }
        return [];
    }
}
