<?php

namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\Lembur;
use App\Models\Absensi;
use App\Models\Gaji;
use App\Models\Penalty;
use App\Models\User;

class Admin extends BaseController
{
    protected $helpers = ['form'];
    protected $Lembur;
    protected $Absensi;
    protected $Gaji;
    protected $Penalty;
    protected $User;
    public function __construct()
    {
        
        $this->Lembur = new Lembur();
        $this->Absensi = new Absensi();
        $this->Gaji = new Gaji();
        $this->Penalty = new Penalty();
        $this->User = new User();




    }
    public function index()
    {
        $start_date = date('Y-m-27', strtotime('-1 month'));
        $end_date = date('Y-m-26');

        $total_lembur = $this->Lembur->getTotalLemburByIndividual($start_date, $end_date);
        $rekapanabsen = $this->Absensi->getTotalAbsensiByIndividual($start_date, $end_date);
        $pegawaitelat = $this->Absensi->hitungjumlahdata('pgwtrl');
        $pegawaimasuk = $this->Absensi->hitungjumlahdata('pgwmsk');
		$totallembur = $this->Lembur->totallembur();
        $data['total_lembur'] = $total_lembur;
        $data['rekapanabsen'] = $rekapanabsen;
        $data['pegawaitelat'] = $pegawaitelat;
        $data['pegawaimasuk'] = $pegawaimasuk;
        $data['totallembur'] = $totallembur;
        return view('templates/v2/header')
        .view('invoicev2/admin', $data)
        .view('templates/v2/footer');
        return $this->response->setJSON($data);
    }

     public function generateabsensi()
    {
        return view('templates/v2/header')
        .view('invoicev2/generateabsen')
        .view('templates/v2/footer');
    }



    public function revenue()
    {
       
        return view('templates/v2/header')
        .view('invoicev2/finance')
        .view('templates/v2/footer');
    }

    public function getabsensi()
    {
        $absensi = $this->Absensi->list();
        $result = [];
    
        foreach ($absensi as $item) {
            $result[] = [
               'id_absen' => $item['id_absen'],
                'nama_pegawai' => $item['nama_pegawai'],
                'tgl_absen' => $item['tgl_absen'],
                'jam_masuk' => $item['jam_masuk'],
                'jam_pulang' => $item['jam_pulang'],
                'status_pegawai' => $item['status_pegawai'],
                'tgl' => $item['tgl'],

            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }
    public function getlembur()
    {
        $lembur = $this->Lembur->findall();
        $result = [];
    
        foreach ($lembur as $item) {
            $result[] = [
               'id' => $item['id'],
                'nama_pegawai' => $item['nama'],
                'tanggal' => $item['tanggal'],
                'deskripsi' => $item['deskripsi'],
                'jumlah' => $item['jumlah'],
                'approve' => $item['approve'],
                'status' => $item['status'],
                'jml_approve' => $item['jml_approve'],
            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }
    public function getgaji()
    {
        $gaji = $this->Gaji->findall();
        $result = [];
    
        foreach ($gaji as $item) {
            $result[] = [
               'id' => $item['id'],
                'nama_pegawai' => $item['nama'],
                'periode_gajian' => $item['periode_gajian'],
                'total_gaji' => $item['total_gaji'],
            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }
    public function getkaryawan()
    {
        $karyawan = $this->User->findall();
        $result = [];
    
        foreach ($karyawan as $item) {
            $result[] = [
               'id_pegawai' => $item['id_pegawai'],
                'nama_lengkap' => $item['nama_lengkap'],
                'kode_pegawai' => $item['kode_pegawai'],
            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }

    public function getpenalty()
    {
        $penalty = $this->Penalty->select('penalty_poin.id, user.nama_lengkap as nama_pegawai, penalty_poin.tgl_absen, penalty_poin.kode_absen, penalty_poin.reason, penalty_poin.poin')
        ->join('user', 'penalty_poin.id_pegawai = user.id_pegawai')
        ->findAll();
        $result = [];
    
        foreach ($penalty as $item) {
            $result[] = [
               'id' => $item['id'],
                'nama_pegawai' => $item['nama_pegawai'],
                'tgl_absen' => $item['tgl_absen'],
                'kode_absen' => $item['kode_absen'],
                'reason' => $item['reason'],
                'poin' => $item['poin'],
            ];
        }
    
        $responseData = [
            'data' => $result
        ];
        return $this->response->setJSON($responseData);
    }

    public function getlemburbyid($id)
    {
        $lembur_data = $this->Lembur->getLemburData($id);
        if ($lembur_data) {
            return $this->response->setJSON([
                'success' => true,
                'data' => $lembur_data
            ])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Data tidak ditemukan!'
            ])->setStatusCode(404); // Not Found
        }
    }

    public function getgajibyid($id)
    {
        $gaji_data = $this->Gaji->getGajiData($id);
        if ($gaji_data) {
            return $this->response->setJSON([
                'success' => true,
                'data' => $gaji_data
            ])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Data tidak ditemukan!'
            ])->setStatusCode(404); // Not Found
        }
    }

    public function getabsensibyid($id)
    {
        $absensi_data = $this->Absensi->getAbsensiData($id);
        if ($absensi_data) {
            return $this->response->setJSON([
                'success' => true,
                'data' => $absensi_data
            ])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Data tidak ditemukan!'
            ])->setStatusCode(404); // Not Found
        }
    }

    public function getpenaltybyid($id)
    {
        $penalty_data = $this->Penalty->getPenaltyData($id);
        if ($penalty_data) {
            return $this->response->setJSON([
                'success' => true,
                'data' => $penalty_data
            ])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Data tidak ditemukan!'
            ])->setStatusCode(404); // Not Found
        }
    }

    public function getgajiby($id)
    {
        $gaji_ = $this->Penalty->getPenaltyData($id);
        if ($penalty_data) {
            return $this->response->setJSON([
                'success' => true,
                'data' => $penalty_data
            ])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Data tidak ditemukan!'
            ])->setStatusCode(404); // Not Found
        }
    }

    public function gettotalpenaltybyid($id)
    {
        $start_date = date('Y-m-27', strtotime('-1 month'));
        $end_date = date('Y-m-26');
        $penalty_data = $this->Penalty->getTotalPenalty($start_date,$end_date, $id);
        if ($penalty_data) {
            // Misalkan $penalty_data adalah objek dan Anda ingin mengakses total_poin
            return $this->response->setJSON(['total_poin' => $penalty_data['total_poin']])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON(['message' => 'Not Found'])->setStatusCode(404); // Not Found
        }
    }

    public function getTotalLemburbyid($id)
    {
        $lembur_data = $this->Lembur->get_total_lembur($id);
        if ($lembur_data) {
            return $this->response->setJSON([
                'success' => true,
                'data' => $lembur_data
            ])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Data tidak ditemukan!'
            ])->setStatusCode(404); // Not Found
        }
    } 
    
    public function getTotalMesinbyid($id)
    {
        $lembur_data = $this->Lembur->get_total_mesin($id);
        if ($lembur_data) {
            return $this->response->setJSON([
                'success' => true,
                'data' => $lembur_data
            ])->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Data tidak ditemukan!'
            ])->setStatusCode(404); // Not Found
        }
    }

    public function getIncomedata()
    {
        
    }

    ////////////////////////////////////////////// POST DATA /////////////////////////////////
    
    
    public function addAbsensi()
    {

        $bulan = array(
            1 => "Januari", 
            "Februari", 
            "Maret", 
            "April", 
            "Mei", 
            "Juni", 
            "Juli", 
            "Agustus", 
            "September", 
            "Oktober", 
            "November", 
            "Desember"
        );
        $hari = array(
            "Minggu", 
            "Senin", 
            "Selasa", 
            "Rabu", 
            "Kamis", 
            "Jumat", 
            "Sabtu"
        );
        $data = $this->request->getPost([
            'nama_pegawai',
            'kode_pegawai2',
            'jam_masuk',
            'jam_pulang',
            'tgl_absen',
            'keterangan_absen',
            'status',
        ]);

        $tgl_bersih = str_replace('-', '', $data['tgl_absen']); // Menghilangkan '-'
        $jam_bersih = str_replace(':', '', $data['jam_masuk']); // Menghilangkan ':'

        $kode_absen = 'absen_' . $tgl_bersih . $jam_bersih;
        $tgl_absen_post = $data['tgl_absen']; // Contoh: '2025-11-26'
    
        $timestamp = strtotime($tgl_absen_post);

        
        $hari_index = date("w", $timestamp);
        $bulan_index = date("n", $timestamp);
    
        $tgl_absen_custom = $hari[(int)$hari_index] . ', ' . 
                        date("j", $timestamp) . ' ' . 
                        $bulan[(int)$bulan_index] . ' ' . 
                        date("Y", $timestamp);        
        $dataToSave = [
            'nama_pegawai'     => $data['nama_pegawai'],
            'kode_pegawai'     => $data['kode_pegawai2'],
            'jam_masuk'        => $data['jam_masuk'],
            'jam_pulang'        => $data['jam_pulang'],
            'kode_absen'       => $kode_absen, // Data yang sudah di-generate
            'tgl_absen'        => $tgl_absen_custom,// Hanya tanggal
            'tgl'              => date('Y-m-d'),        // Tanggal dan waktu lengkap (sesuai kebutuhan Anda)
            'keterangan_absen' => $data['keterangan_absen'],
            'status_pegawai'   => $data['status'],
        ];
        
        // Contoh Backend (PHP/Controller) yang BENAR
            if ($this->Absensi->save($dataToSave)) {
                return $this->response->setJSON([
                    'success' => true, // <--- Key yang Diharapkan Frontend
                    'message' => 'Data absensi berhasil disimpan.'
                    // Hapus 'kode_absen' jika tidak digunakan di frontend
                ]);
            } else {
                return $this->response->setStatusCode(400)->setJSON([
                    'success' => false, // <--- Key yang Diharapkan Frontend
                    'message' => 'Gagal menyimpan data absensi.'
                    // Hapus 'errors' jika tidak digunakan di frontend
                ]);
            }
                }
    public function lemburupdate()
    {
        $lembur_id = $this->request->getPost('lembur_id');

        $validation =  \Config\Services::validation();
        $validation->setRules([
            'status' => 'required',
            'approve' => 'required',
            'jml_approve' => 'required'
        ]);

        if (!$this->validate($validation->getRules())) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validation->getErrors()
            ]);
        }

        $data = [
            'status' => $this->request->getPost('status'),
            'approve' => $this->request->getPost('approve'),
            'jml_approve' => $this->request->getPost('jml_approve')
        ];
        $update = $this->Lembur->updateLembur($data, $lembur_id);
        if ($update) {
            return $this->response->setJSON(['success' => true, 'message' => 'Data successfully updated']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Failed to update data']);
        }

    }

    public function absensiupdate()
    {
        $absensi_id = $this->request->getPost('absensi_id');

        $validation =  \Config\Services::validation();
        $validation->setRules([
            'status' => 'required',
            'absensi_id' => 'required',
            'nama' => 'required'
        ]);

        if (!$this->validate($validation->getRules())) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validation->getErrors()
            ]);
        }

        $data = [
            'status_pegawai' => $this->request->getPost('status'),
            'id_absen' => $this->request->getPost('absensi_id'),
            'nama_pegawai' => $this->request->getPost('nama'),
            'jam_masuk' => $this->request->getPost('jam_masuk'),
            'jam_pulang' => $this->request->getPost('jam_pulang'),
            'keterangan_absen' => $this->request->getPost('ket_absen'),
            'tgl' => $this->request->getPost('tanggal'),
        ];
        $update = $this->Absensi->updateAbsensi($data, $absensi_id);
        if ($update) {
            return $this->response->setJSON(['success' => true, 'message' => 'Data successfully updated']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Failed to update data']);
        }

    }

    public function gajiupdate()
    {
        $gaji_id = $this->request->getPost('gaji_id');

        $validation =  \Config\Services::validation();
        $validation->setRules([
            'gaji_id' => 'required',
            'nama' => 'required'
        ]);

        if (!$this->validate($validation->getRules())) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validation->getErrors()
            ]);
        }

        $data = [
            'id_pegawai' =>$this->request->getPost('karyawan_1'),
            'jumlah_kehadiran' =>$this->request->getPost('qty_1'),
            'periode_gajian' =>$this->request->getPost('waktu'),
            'gaji_pokok' =>$this->request->getPost('gapok'),
            'uang_makan' =>$this->request->getPost('qtycur_1'),
            'hari_kerja' =>$this->request->getPost('uangmakanqty_1'),
            'nominal_uang_makan' =>$this->request->getPost('qtyfinal_1'),
            'tunjangan_kesehatan' =>$this->request->getPost('hariankesehatan_1'),
            'kesehatan' =>$this->request->getPost('kesehatan_1'),
            'nominal_tunjangan_kesehatan' =>$this->request->getPost('uangkesehatan_1'),
            'tunjangan_kendaraan' =>$this->request->getPost('hariankendaraan_1'),
            'kendaraan' =>$this->request->getPost('kendaraan_1'),
            'nominal_tunjangan_kendaraan' =>$this->request->getPost('uangkendaraan_1'),
            'lembur_harian' =>$this->request->getPost('harianLembur_1'),
            'total_lembur' =>$this->request->getPost('total_lembur'),
            'nominal_lembur' =>$this->request->getPost('uangLembur_1'),
            'lembur_lainnya' =>$this->request->getPost('harianLembur_2'),
            'total_lembur_lainnya' =>$this->request->getPost('total_lembur2'),
            'nominal_lembur_lainnya' =>$this->request->getPost('uangLembur_2'),
            'double_shift' =>$this->request->getPost('hariands'),
            'total_double_shift' =>$this->request->getPost('total_ds'),
            'nominal_double_shift' =>$this->request->getPost('uangds'),
            'uang_kerajinan' =>$this->request->getPost('kerajinan'),
            'total_pendapatan_kotor' =>$this->request->getPost('nominal_kotor'),
            'telat' =>$this->request->getPost('telat'),
            'total_telat' =>$this->request->getPost('total_telat'),
            'nominal_telat' =>$this->request->getPost('nominal_telat'),
            'kasbon' =>$this->request->getPost('kasbon2'),
            'kasbon_lainnya' =>$this->request->getPost('ket_kasbon'),
            'nominal_kasbon' =>$this->request->getPost('kasbon'),
            'pinalty' =>$this->request->getPost('pinalty'),
            'nominal_pinalty' =>$this->request->getPost('nominal_pinalty'),
            'bpjs_kesehatan' =>$this->request->getPost('bpjskes'),
            'bpjs_tenaga_kerja' =>$this->request->getPost('bpjsnaker'),
            'nominal_bpjs' =>$this->request->getPost('nominal_bpjs'),
            'total_potongan' =>$this->request->getPost('nominal_potongan'),
            'total_gaji' =>$this->request->getPost('nominal_gaji'),
            'note' =>$this->request->getPost('gaji'),
            'nama' =>$this->request->getPost('nama')
        ];
        $update = $this->Gaji->updateGaji($data, $gaji_id);
        if ($update) {
            return $this->response->setJSON(['success' => true, 'message' => 'Data successfully updated']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Failed to update data']);
        }

    }

    public function getkaryawandata()
    {
        $karyawan_id = $this->request->getPost('selectedId');
        
        $karyawan_data = $this->User->getKaryawandata($karyawan_id);
        if ($karyawan_data) {
            return $this->response->setJSON($karyawan_data)->setStatusCode(200); // OK
        } else {
            return $this->response->setJSON($karyawan_data)->setStatusCode(404); // Not Found
        }
    }

    public function penaltyupdate()
    {
        $penalty_id = $this->request->getPost('penalty_id');

        $validation =  \Config\Services::validation();
        $validation->setRules([
            'poin' => 'required',
        ]);

        if (!$this->validate($validation->getRules())) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $validation->getErrors()
            ]);
        }

        $data = [
            'poin' => $this->request->getPost('poin')
        ];
        $update = $this->Penalty->updatePenalty($data, $penalty_id);
        if ($update) {
            return $this->response->setJSON(['success' => true, 'message' => 'Data successfully updated']);
        } else {
            return $this->response->setJSON(['success' => false, 'message' => 'Failed to update data']);
        }

    }

    public function creategaji()

    {



        $validation =  \Config\Services::validation();

        $validation->setRules([

            'karyawan_1' => 'required',

            'qty_1' => 'required',

        ]);



        if (!$this->validate($validation->getRules())) {

            return $this->response->setJSON([

                'success' => false,

                'message' => 'Validation error',

                'errors' => $validation->getErrors()

            ]);

        }



        $data = [

            'id_pegawai' =>$this->request->getPost('karyawan_1'),

            'jumlah_kehadiran' =>$this->request->getPost('qty_1'),

            'periode_gajian' =>$this->request->getPost('waktu'),

            'gaji_pokok' =>$this->request->getPost('gapok'),

            'uang_makan' =>$this->request->getPost('qtycur_1'),

            'hari_kerja' =>$this->request->getPost('uangmakanqty_1'),

            'nominal_uang_makan' =>$this->request->getPost('qtyfinal_1'),

            'tunjangan_kesehatan' =>$this->request->getPost('hariankesehatan_1'),

            'kesehatan' =>$this->request->getPost('kesehatan_1'),

            'nominal_tunjangan_kesehatan' =>$this->request->getPost('uangkesehatan_1'),

            'tunjangan_kendaraan' =>$this->request->getPost('hariankendaraan_1'),

            'kendaraan' =>$this->request->getPost('kendaraan_1'),

            'nominal_tunjangan_kendaraan' =>$this->request->getPost('uangkendaraan_1'),

            'lembur_harian' =>$this->request->getPost('harianLembur_1'),

            'total_lembur' =>$this->request->getPost('total_lembur'),

            'nominal_lembur' =>$this->request->getPost('uangLembur_1'),

            'lembur_lainnya' =>$this->request->getPost('harianLembur_2'),

            'total_lembur_lainnya' =>$this->request->getPost('total_lembur2'),

            'nominal_lembur_lainnya' =>$this->request->getPost('uangLembur_2'),

            'double_shift' =>$this->request->getPost('hariands'),

            'total_double_shift' =>$this->request->getPost('total_ds'),

            'nominal_double_shift' =>$this->request->getPost('uangds'),

            'uang_kerajinan' =>$this->request->getPost('kerajinan'),

            'total_pendapatan_kotor' =>$this->request->getPost('nominal_kotor'),

            'telat' =>$this->request->getPost('telat'),

            'total_telat' =>$this->request->getPost('total_telat'),

            'nominal_telat' =>$this->request->getPost('nominal_telat'),

            'kasbon' =>$this->request->getPost('kasbon2'),

            'kasbon_lainnya' =>$this->request->getPost('ket_kasbon'),

            'nominal_kasbon' =>$this->request->getPost('kasbon'),

            'pinalty' =>$this->request->getPost('pinalty'),

            'nominal_pinalty' =>$this->request->getPost('nominal_pinalty'),

            'bpjs_kesehatan' =>$this->request->getPost('bpjskes'),

            'bpjs_tenaga_kerja' =>$this->request->getPost('bpjsnaker'),

            'nominal_bpjs' =>$this->request->getPost('nominal_bpjs'),

            'total_potongan' =>$this->request->getPost('nominal_potongan'),

            'total_gaji' =>$this->request->getPost('nominal_gaji'),

            'note' =>$this->request->getPost('gaji'),

            'nama' =>$this->request->getPost('nama')

        ];

        

        $this->Gaji->insert($data); 

    

        if ($this->Gaji->insertID()) {

            return $this->response->setJSON(['success' => true, 'message' => 'Data berhasil disimpan']);

        } else {

            return $this->response->setJSON(['success' => false, 'message' => 'Gagal menyimpan data']);

        }

       

    }

    public function createpenalty()

    {



        $validation =  \Config\Services::validation();

        $validation->setRules([

            'karyawan_2' => 'required',

            'poin_pen' => 'required',

        ]);



        if (!$this->validate($validation->getRules())) {

            return $this->response->setJSON([

                'success' => false,

                'message' => 'Validation error',

                'errors' => $validation->getErrors()

            ]);

        }



        $data = [

            'id_pegawai' =>$this->request->getPost('karyawan_2'),

            'kode_pegawai' =>$this->request->getPost('kode_pegawai'),

            'reason' =>$this->request->getPost('alasan'),

            'tgl_absen' =>$this->request->getPost('waktu_pen'),

            'poin' =>$this->request->getPost('poin_pen'),
            

        ];

        

        $this->Penalty->insert($data); 

    

        if ($this->Penalty->insertID()) {

            return $this->response->setJSON(['success' => true, 'message' => 'Data berhasil disimpan']);

        } else {

            return $this->response->setJSON(['success' => false, 'message' => 'Gagal menyimpan data']);

        }

       

    }
}