<?php

namespace App\Models;

use CodeIgniter\Model;

class Absensi extends Model
{
    protected $table = 'db_absensi';
    protected $primaryKey = 'id_absen';
    protected $allowedFields =  ['id_absen', 'kode_absen', 'nama_pegawai', 'kode_pegawai', 'tgl_absen', 'jam_masuk', 'jam_pulang', 'status_pegawai', 'keterangan_absen', 'maps_absen', 'tgl'];

    public function getTotalAbsensiByIndividual($start_date, $end_date)
    {
        return $this->select('nama_pegawai,COUNT(jam_pulang) as kehadiran,COUNT(CASE WHEN status_pegawai = 2 THEN 1 ELSE NULL END) as telat')
                    ->where('tgl >=', $start_date)
                    ->where('tgl <=', $end_date)
                    ->groupBy('nama_pegawai')
                    ->findAll();
    }

    public function list()
    {
        return $this->select('*')
                    ->orderby('id_absen', 'DESC')
                    ->findAll();

       
    }
    public function hitungJumlahData($typehitung)
    {
        $today = date('Y-m-d'); 
        if ($typehitung == 'jmlpgw') {
            return $this->countAllResults();
        } elseif ($typehitung == 'pgwtrl') {
            return $this->db->table('db_absensi')
                ->where(['status_pegawai' => 2, 'tgl' => $today])
                ->countAllResults(); 
        } elseif ($typehitung == 'pgwmsk') {
            return $this->db->table('db_absensi')
                ->where(['status_pegawai' => 1, 'tgl' => $today])
                ->countAllResults(); 
        }

        return 0; 
    }

    public function getAbsensiData($id = null)
    {
        if ($id) {
            return $this->where('id_absen', $id)->first(); // Mengambil satu lembur berdasarkan ID
        }

        return $this->orderBy('tgl_absen', 'DESC')->findAll(); // Mengambil semua lembur dan mengurutkan berdasarkan tanggal
    }
    public function updateAbsensi($data, $id_absen)
    {
        return $this->update($id_absen, $data);
    }
}
