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

class Permission_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function get_all() {
        return $this->db->get('kns1_permissions')->result();
    }

    public function get_by_id($id) {
        return $this->db->get_where('kns1_permissions', ['id' => $id])->row();
    }

    public function create($data) {
        return $this->db->insert('kns1_permissions', $data);
    }

    public function update($id, $data) {
        $this->db->where('id', $id)->update('kns1_permissions', $data);
        return $this->db->affected_rows();
    }
    
    public function delete($id) {
        return $this->db->delete('kns1_permissions', ['id' => $id]);
    }

    public function assign_to_role($role_id, $permission_id) {
        $data = [
            'role_id'       => $role_id,
            'permission_id' => $permission_id,
        ];
        return $this->db->insert('kns1_role_permissions', $data);
    }

    public function delete_by_role($role_id) {
        return $this->db->delete('kns1_role_permissions', ['role_id' => $role_id]);
    }

    public function get_permissions_by_role($role_id) {
        $this->db->select('permission_id');
        $this->db->where('role_id', $role_id);
        $query = $this->db->get('kns1_role_permissions');
        return array_column($query->result_array(), 'permission_id');
    }
}
