<?php

namespace Modules\Settings\Models;

use CodeIgniter\Model;

class PermissionsModel extends Model
{
    protected $table = 'permissions';
    protected $primaryKey = 'id';

    protected $allowedFields = ['parent_id', 'name', 'module_section_id', 'description', 'module'];

    protected $returnType     = 'array';
    protected $useTimestamps  = true;
    protected $useSoftDeletes = true;
    
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    public function getAll()
    {
        $builder = $this->db->table('permissions as p');
        $builder->select('p.*, pp.name as parent_name, m.name as section_name')
                ->join('permissions as pp', 'pp.id=p.parent_id', 'left')
                ->join('module_sections as m', 'm.id=p.module_section_id', 'left');
        return $result = $builder->get()->getResult();
    }
    

    public function getByName($name)
    {
        return $this->where('name', $name)->first();
    }

    public function getPermissionsBySection()
    {
        return $this->select('permissions.*, module_sections.name as section_name')
            ->join('module_sections', 'module_sections.id = permissions.module_section_id')
            ->orderBy('module_sections.sort_order', 'ASC')
            ->orderBy('permissions.id', 'ASC')
            ->findAll();
    }
    
    public function getSectionPermissions($sectionId)
    {
        return $this->where('section_id', $sectionId)->findAll();
    }

    

}