<?php

/*
 * *************************************************
 * Copyright (C) 2021 Earworks.                    *
 * Codeigniter Project Template Modification       *
 * Please contact our email for more information : *
 * contact@earworks.co.id                          *
 * *************************************************
 */

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of Permission_model
 *
 * @author Andhy Taslin <andhy@earworks.co.id>
 * @since 1.0
 */
class Permission_model extends MY_Model {

    const STATUS_ACTIVE = 1;
    const STATUS_BANNED = 2;

    protected $table = "permissions";
    public $timestamps = true;

    public static function status_label($selected = null) {
        $lib = [
            self::STATUS_ACTIVE => lang('ACTIVE'),
            self::STATUS_BANNED => lang('BANNED'),
        ];
        return array_key_exists($selected, $lib) ? $lib[$selected] : $lib;
    }

    public function roles() {
        return $this->belongsToMany(Role_model::class, 'role_permissions', 'role_id', 'permission_id')->withTimestamps();
    }

    public static function grouped($permissions = []) {
        $permission_group = [];
        $count = count($permissions);
        if ($count > 0) {
            foreach ($permissions as $permission) {
                if (!isset($permission_group[$permission->group])) {
                    $permission_group[$permission->group] = [];
                }
                $permission_group[$permission->group][] = $permission;
            }
        }
        return $permission_group;
    }

}
