<?php

namespace App\Models;

use CodeIgniter\Model;

class ModelPatients extends Model
{
    protected $table            = 'patients';
    protected $primaryKey       = 'id'; // UUID
    protected $useAutoIncrement = false; // UUID tidak auto-increment
    protected $allowedFields    = [
        'id',
        'no_rm',          // UUID
        'nik',
        'nama',
        'tanggal_lahir',
        'jenis_kelamin',
        'alamat',
        'no_hp',
        'aktif',
        'created_at'
    ];

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

    /**
     * Ambil semua data pasien
     */
    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('nik', $search)
                ->orLike('nama', $search)
                ->orLike('jenis_kelamin', $search)
                ->orLike('alamat', $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('nik', $search)
                ->orLike('nama', $search)
                ->orLike('jenis_kelamin', $search)
                ->orLike('alamat', $search)
                ->groupEnd();
        }

        return $builder->countAllResults();
    }

    public function generateNoRM($tanggal_lahir)
    {
        $tgl = date('Ymd', strtotime($tanggal_lahir));

        // Ambil jumlah pasien dengan tanggal lahir sama
        $count = $this->where('tanggal_lahir', $tanggal_lahir)->countAllResults();

        // Tambahkan 1 untuk nomor berikutnya
        $urutan = str_pad($count + 1, 4, '0', STR_PAD_LEFT);

        return $tgl . $urutan;
    }


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

    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);
    }
}
