<?php
namespace App\Controllers;

class ActivityController extends BaseController
{
    public function index()
    {
        if (!$this->can('view_activity')) return redirect()->to('/')->with('error','Access denied');
        $db=$db=db_connect(); $cid=$this->companyId;
        $entityType=$this->request->getGet('entity_type');
        $userId=$this->request->getGet('user_id');
        $type=$this->request->getGet('type');
        $dateFrom=$this->request->getGet('date_from');
        $dateTo=$this->request->getGet('date_to');
        $search=$this->request->getGet('search');

        $b=model('ActivityLogModel')->where('company_id',$cid)->orderBy('created_at','DESC');
        if (!$this->can('manage_users')&&$this->can('edit_invoices')&&!$this->can('edit_jobs')) $b->whereIn('entity_type',['invoice','quote','payment']);
        elseif (!$this->can('manage_users')) { $jobIds=array_column($db->table('job_assignees')->where('user_id',$this->userId)->select('job_id')->get()->getResultArray(),'job_id'); $b->groupStart()->where('user_id',$this->userId)->orWhereIn('entity_id',$jobIds?:[0])->groupEnd(); }
        if ($entityType) $b->where('entity_type',$entityType);
        if ($userId)     $b->where('user_id',$userId);
        if ($type)       $b->like('type',$type,'after');
        if ($dateFrom)   $b->where('created_at >=',$dateFrom.' 00:00:00');
        if ($dateTo)     $b->where('created_at <=',$dateTo.' 23:59:59');
        if ($search)     $b->like('description',$search);
        $activity=$b->findAll(200);

        $users=$db->table('users')->where('company_id',$cid)->where('status','active')->where('deleted_at IS NULL',null,false)->get()->getResultArray();

        return $this->view('activity/index', compact('activity','users','entityType','userId','type','dateFrom','dateTo','search'));
    }
}
