<?php

namespace App\Models\Usuarios;

class GroupModel extends \App\Models\BaseModel
{
    protected $table = "auth_groups";

    /**
     * Whether primary key uses auto increment.
     *
     * @var bool
     */
    protected $useAutoIncrement = true;

    protected $primaryKey = "id";

    protected $useTimestamps = true;
    protected $dateFormat = 'datetime';
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    const SORTABLE = [
        1 => "t1.id",
        2 => "t1.keyword",
        3 => "t1.title",
        4 => "t1.description",
        5 => "t1.rules",
        6 => "t1.created_at",
        7 => "t1.updated_at",
    ];

    protected $allowedFields = ["id", "keyword", "title", "description", "rules"];
    protected $returnType = "App\Entities\Usuarios\GroupEntity";

    public static $labelField = "title";

    protected $validationRules = [
        "description" => [
            "label" => "RolesPermisos.description",
            "rules" => "max_length[150]",
        ],
        "title" => [
            "label" => "RolesPermisos.title",
            "rules" => "required|max_length[50]",
        ],

    ];

    protected $validationMessages = [
        "description" => [
            "max_length" => "RolesPermisos.validation.description.max_length",
            "required" => "RolesPermisos.validation.description.required",
        ],
        "title" => [
            "max_length" => "RolesPermisos.validation.title.max_length",
            "required" => "RolesPermisos.validation.title.required",
        ],

    ];

    /**
     * Get resource data.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResource(string $search = "")
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id,  t1.keyword AS keyword, t1.title AS title, t1.description AS description, t1.rules AS rules, 
                t1.token AS token, t1.created_at AS created_at, t1.updated_at AS updated_at"
            );

        return empty($search)
            ? $builder
            : $builder
                ->groupStart()
                ->like("t1.id", $search)
                ->orLike("t1.keyword", $search)
                ->orLike("t1.title", $search)
                ->orLike("t1.description", $search)
                ->orLike("t1.rules", $search)
                ->orLike("t1.created_at", $search)
                ->orLike("t1.updated_at", $search)
                ->groupEnd();
    }


    public function getUsersWithRol($groupKeyWord)
    {

        return $this->db
            ->table('auth_groups_users')
            ->select('user_id')
            ->where('group', $groupKeyWord)
            ->countAllResults();
    }


    public function getUsersRoles($userId)
    {

        return $this->db
            ->table('auth_groups_users')
            ->select('group')
            ->where('user_id', $userId)
            ->get()
            ->getResult();
    }

    public function getRolPermissionList($rolId)
    {
        $rolRecord = $this->find($rolId);
        $result = [];

        foreach ($rolRecord->rules as $section => $permissions) {
            if (!is_null($permissions)) {
                foreach ($permissions as $permission) {
                    $result[$section . "." . $permission] = "Can " . $permission;
                }
                // Add menu visibility permission (automatic management)
                $result[$section . ".menu"] = "Menu shall be visualize";
            }
        }
        return $result;
    }

    public function getRolesPermissionMatrix()
    {
        $rolesRecord = $this->findAll();
        $result = [];

        foreach ($rolesRecord as $rolRecord) {
            $rolePermissions = [];
            foreach ($rolRecord->rules as $section => $permissions) {
                foreach ($permissions as $permission) {
                    $rolePermissions[] = $section . "." . $permission;
                }
                // Add menu visibility permission (automatic management)
                $rolePermissions[] = $section . ".menu";
            }
            $result[$rolRecord->keyword] = $rolePermissions;
        }
        return $result;
    }


    public function getRolesList()
    {
        $rolesRecord = $this->findAll();
        $result = [];

        foreach ($rolesRecord as $rolRecord) {
            $result[$rolRecord->keyword] = array(
                'title' => $rolRecord->title,
                'description' => $rolRecord->description
            );
        }
        return $result;
    }


}
