<?php

namespace App\Models;

use CodeIgniter\Model;

class ActivityLogModel extends Model
{
    protected $table      = 'activity_logs';
    protected $primaryKey = 'id';
    protected $returnType = 'array';

    protected $allowedFields = ['user_id', 'username', 'action', 'description', 'ip_address'];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = null;

    public function log(string $action, string $description, string $ipAddress): void
    {
        $this->insert([
            'user_id'     => session('user_id'),
            'username'    => session('username'),
            'action'      => $action,
            'description' => $description,
            'ip_address'  => $ipAddress,
        ]);
    }

    public function getDataTable(int $start, int $length, string $search): array
    {
        $builder = $this->db->table($this->table);

        $total = (clone $builder)->countAllResults();

        if ($search !== '') {
            $builder->groupStart()
                ->like('username', $search)
                ->orLike('action', $search)
                ->orLike('description', $search)
                ->groupEnd();
        }

        $filtered = (clone $builder)->countAllResults(false);

        $rows = $builder->orderBy('id', 'DESC')
            ->limit($length, $start)
            ->get()->getResultArray();

        return ['total' => $total, 'filtered' => $filtered, 'data' => $rows];
    }
}
