<?php
namespace App\Models;
use CodeIgniter\Model;

class ActivityLogModel extends Model
{
    protected $table         = 'activity_log';
    protected $primaryKey    = 'id';
    protected $useTimestamps  = false;
    protected $updatedField  = '';
    protected $allowedFields  = ['company_id','type','entity_type','entity_id','entity_ref','user_id','user_name','description','meta','ip_address','user_agent','created_at','updated_at','deleted_at'];

    public function getFeedForUser(int $companyId, int $userId, array $permissions, int $limit = 50): array
    {
        $b = $this->where('company_id', $companyId)->orderBy('created_at', 'DESC');
        $isAdmin    = in_array('manage_users', $permissions);
        $isAccounts = in_array('edit_invoices', $permissions) && !in_array('edit_jobs', $permissions);

        if (!$isAdmin && $isAccounts) {
            $b->whereIn('entity_type', ['invoice','quote','payment']);
        } elseif (!$isAdmin) {
            $jobIds = array_column(db_connect()->table('job_assignees')->where('user_id', $userId)->select('job_id')->get()->getResultArray(), 'job_id');
            $b->groupStart()->where('user_id', $userId)->orWhereIn('entity_id', $jobIds ?: [0])->groupEnd();
        }
        return $b->findAll($limit);
    }
}
