<?php

namespace App\Models;

use CodeIgniter\Model;

class Lembur extends Model
{
    protected $table = 'lembur';
    protected $primaryKey = 'id'; // Assuming your primary key field name is 'id'
    protected $allowedFields =  ['id', 'user_id', 'tanggal', 'deskripsi', 'jumlah', 'image', 'status', 'telat', 'jml_approve', 'approve', 'kode_pegawai', 'nama', 'id_pegawai'];

    public function getTotalLemburByIndividual($start_date, $end_date)
    {
        return $this->select('nama, SUM(jumlah) as total_lembur, SUM(jml_approve) as total_lemburapp, COUNT(CASE WHEN status = 2 THEN 1 ELSE NULL END) as mesin')
                    ->where('approve', 1)
                    ->where('tanggal >=', $start_date)
                    ->where('tanggal <=', $end_date)
                    ->groupBy('nama')
                    ->findAll();
    }

    public function get_total_lembur($selectedId)
    {
        return $this->selectSum('jml_approve')
                    ->where('tanggal >=', date('Y-m-27', strtotime('-1 month')))
                    ->where('tanggal <=', date('Y-m-26'))
                    ->where('approve', 1)
                    ->where('id_pegawai', $selectedId)
                    ->first();
    }
    public function get_total_mesin($selectedId)
    {
        // Ambil data total lembur dari tabel 'lembur' berdasarkan kode pegawai yang dipilih
        return $this->select('COUNT(CASE WHEN status = 2 THEN 1 ELSE NULL END) as status_count')
                    ->where('tanggal >=', date('Y-m-27', strtotime('-1 month')))
                    ->where('tanggal <=', date('Y-m-26'))
                    ->where('approve', 1)
                    ->where('id_pegawai', $selectedId)
                    ->first();
    }
 

    public function totalLembur()
    {
        return $this->where('approve', 1)->countAllResults();
    }
    public function getLemburData($id = null)
    {
        if ($id) {
            return $this->where('id', $id)->first(); // Mengambil satu lembur berdasarkan ID
        }

        return $this->orderBy('tanggal', 'DESC')->findAll(); // Mengambil semua lembur dan mengurutkan berdasarkan tanggal
    }

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