<?php

namespace App\Models;

use CodeIgniter\Model;

class ModelPractitioner extends Model
{
    protected $table            = 'practitioners';
    protected $primaryKey       = 'id'; // UUID
    protected $useAutoIncrement = false; // UUID tidak auto-increment
    protected $allowedFields    = [
        'id',
        'nama',
        'sip',
        'spesialisasi',
        'no_hp',
        'aktif',
        'created_at'
    ];

    protected $useTimestamps = false; // created_at manual, updated_at tidak digunakan

    /**
     * Ambil semua data praktisi
     */
    public function getAllData()
    {
        return $this->orderBy('created_at', 'DESC')->findAll();
    }

    /**
     * Data untuk DataTables
     */
    public function getDatatables($search = '', $limit = 10, $offset = 0)
    {
        $builder = $this->table($this->table);

        if (!empty($search)) {
            $builder->groupStart()
                ->like('nama', $search)
                ->orLike('sip', $search)
                ->orLike('spesialisasi', $search)
                ->orLike('no_hp', $search)
                ->groupEnd();
        }

        $builder->orderBy('created_at', 'DESC');

        if ($limit != -1) {
            $builder->limit($limit, $offset);
        }

        return $builder->get()->getResult();
    }

    public function countFiltered($search = '')
    {
        $builder = $this->table($this->table);

        if (!empty($search)) {
            $builder->groupStart()
                ->like('nama', $search)
                ->orLike('sip', $search)
                ->orLike('spesialisasi', $search)
                ->orLike('no_hp', $search)
                ->groupEnd();
        }

        return $builder->countAllResults();
    }

    public function countAll()
    {
        return $this->countAllResults();
    }

    public function tambahData($data)
    {
        return $this->insert($data);
    }

    public function updateData($id, $data)
    {
        return $this->update($id, $data);
    }

    public function deleteData($id)
    {
        return $this->delete($id);
    }
}
