<?php
defined('BASEPATH') || exit('No direct script access allowed');

class Saldo_cuti extends MY_Controller
{
    /**
     * Reset cuti berdasarkan join date
     * Karyawan dengan status tetap, kontrak, atau (tetap dan kontrak)
     *
     * @return void
     */
    public function reset_cuti_1()
    {
        $data_karyawan = $this->db->query("
                SELECT
                    dk.id_karyawan,
                    dk.nama_lengkap,
                    dk.join_date,
                    timestampdiff(MONTH, dk.join_date, NOW()) as ttl_bulan,
                    dk.status,
                    dk.jatah_cuti,
                    dk.carry_forward,
                    cp.reset_saldo,
                    cp.carry_forward_maks_saldo,
                    cp.carry_forward_maks_bulan,
                    dk.id_company
                FROM
                    cuti_p as cp
                    join data_karyawan as dk on dk.id_company = cp.id_company
                WHERE
                    cp.reset_jenis = 'join_date'
                    AND DATE_FORMAT(CURRENT_DATE, '%m-%d') = DATE_FORMAT(dk.join_date, '%m-%d')
                    AND dk.join_date not in ('0000-00-00', '1970-01-01')
                    AND find_in_set(dk.status, cp.jenis_karyawan)
                    AND timestampdiff(MONTH, dk.join_date, NOW()) >= cp.join_date_bulan
                ORDER BY
                    dk.id_company ASC")->result();
        return $this->reset_saldo($data_karyawan, 'reset_saldo_by_join_date');
    }

    /**
     * Reset cuti berdasarkan bulan
     * Karyawan dengan status tetap, kontrak, atau (tetap dan kontrak)
     * Cron dijalankan setiap awal bulan
     *
     * @return void
     */
    public function reset_cuti_2()
    {
        $data_karyawan = $this->db->query("
                SELECT
                    dk.id_karyawan,
                    dk.nama_lengkap,
                    dk.join_date,
                    timestampdiff(MONTH, dk.join_date, NOW()) as ttl_bulan,
                    dk.status,
                    dk.jatah_cuti,
                    dk.carry_forward,
                    cp.reset_saldo,
                    cp.carry_forward_maks_saldo,
                    cp.carry_forward_maks_bulan,
                    dk.id_company
                FROM
                    cuti_p as cp
                    join data_karyawan as dk on dk.id_company = cp.id_company
                WHERE
                    cp.reset_jenis = 'bulan'
                    AND cp.periode_cuti = MONTH(NOW())
                    AND dk.join_date not in ('0000-00-00', '1970-01-01')
                    AND find_in_set(dk.status, cp.jenis_karyawan)
                    AND timestampdiff(MONTH, dk.join_date, NOW()) >= cp.join_date_bulan
                ORDER BY
                    dk.id_company ASC")->result();
        return $this->reset_saldo($data_karyawan, 'reset_saldo_by_month');
    }

    /**
     * menjalankan perintah reset saldo
     *
     * @param array $data_karyawan
     * @param string $jenis_reset (fungsi mana yang dijalankan)
     * @return void
     */
    public function reset_saldo($data_karyawan = [], $jenis_reset = '')
    {
        // get id_karyawan
        $id_karyawan = array();
        // carry forward
        $is_carry_forward = false;
        // $insert_history_saldo_cf_hangus = array();
        $insert_history_saldo_cf_reset = array();
        // jatah cuti
        $insert_history_saldo_hangus = array();
        $insert_history_saldo_reset = array();
        $id_company = '';
        $nextId = 0;

        foreach ($data_karyawan as $row) {
            if ($id_company != $row->id_company) {
                $nextId = $this->fungsi->getNextId('cuti_history', 'id_cuti_history', $row->id_company, 3);
            }
            $id_company = $row->id_company;

            // tambah saldo carry forward jika bulan dan saldo lebih dari 0
            if ($row->jatah_cuti <= 0) {
                $jatah_cuti = ($row->jatah_cuti + $row->reset_saldo);
                $carry_forward = 0;
            } else {
                $jatah_cuti = $row->reset_saldo;
                if ($row->jatah_cuti >= $row->carry_forward_maks_saldo) {
                    $carry_forward = $row->carry_forward_maks_saldo;
                } else {
                    $carry_forward = $row->jatah_cuti;
                }
            }
            if ($row->carry_forward_maks_bulan > 0 && $row->carry_forward_maks_saldo > 0) {
                $id_karyawan[] = [
                    'id_karyawan'   => $row->id_karyawan,
                    'jatah_cuti'    => $jatah_cuti,
                    'carry_forward' => $carry_forward
                ];
                $is_carry_forward = true;
            } else {
                $id_karyawan[] = [
                    'id_karyawan'   => $row->id_karyawan,
                    'jatah_cuti'    => $jatah_cuti,
                    'carry_forward' => 0
                ];
            }

            if ($row->jatah_cuti > 0) {
                $insert_history_saldo_hangus[] = [
                    'id_cuti_history' => $nextId,
                    'id_karyawan'     => $row->id_karyawan,
                    'tgl_trx'         => date('Y-m-d'),
                    'keterangan'      => 'Expired Balance',
                    'tambah'          => 0,
                    'kurang'          => $row->jatah_cuti,
                    'saldo'           => 0,
                    'user_input'      => 'By System',
                    'id_company'      => $row->id_company
                ];
                $last_id = substr($nextId, -3);
                $nextId = $row->id_company . date('Ym') . sprintf("%03d", ($last_id + 1));
            }

            $insert_history_saldo_reset[] = [
                'id_cuti_history' => $nextId,
                'id_karyawan'     => $row->id_karyawan,
                'tgl_trx'         => date('Y-m-d'),
                'keterangan'      => 'Reset Balance',
                'tambah'          => $jatah_cuti,
                'kurang'          => 0,
                'saldo'           => $jatah_cuti,
                'user_input'      => 'By System',
                'id_company'      => $row->id_company
            ];
            $last_id = substr($nextId, -3);
            $nextId = $row->id_company . date('Ym') . sprintf("%03d", ($last_id + 1));

            // jika punya saldo carry forward
            // insert history saldo carry forward hangus
            // if ($row->carry_forward > 0) {
            //     $insert_history_saldo_cf_hangus[] = [
            //         'id_cuti_history' => $nextId,
            //         'id_karyawan'     => $row->id_karyawan,
            //         'tgl_trx'         => date('Y-m-d'),
            //         'keterangan'      => 'Saldo carry forward hangus',
            //         'tambah'          => 0,
            //         'kurang'          => $row->carry_forward,
            //         'saldo'           => 0,
            //         'user_input'      => 'By System',
            //         'id_company'      => $row->id_company
            //     ];
            //     $last_id = substr($nextId, -3);
            //     $nextId = $row->id_company . date('Ym') . sprintf("%03d", ($last_id + 1));
            // }

            // jika carry forward diaktifkan
            // insert history penambahan saldo carry forward
            if ($is_carry_forward) {
                if ($carry_forward > 0) {
                    $insert_history_saldo_cf_reset[] = [
                        'id_cuti_history' => $nextId,
                        'id_karyawan'     => $row->id_karyawan,
                        'tgl_trx'         => date('Y-m-d'),
                        'keterangan'      => 'Carry forward',
                        'tambah'          => $carry_forward,
                        'kurang'          => 0,
                        'saldo'           => ($carry_forward + $jatah_cuti),
                        'user_input'      => 'By System',
                        'id_company'      => $row->id_company
                    ];
                    $last_id = substr($nextId, -3);
                    $nextId = $row->id_company . date('Ym') . sprintf("%03d", ($last_id + 1));
                }
            }
        }

        $this->db->trans_start();
        // insert history cuti saldo hangus
        $this->db->insert_batch('cuti_history', $insert_history_saldo_hangus);
        // insert history cuti reset saldo
        $this->db->insert_batch('cuti_history', $insert_history_saldo_reset);
        // insert history cuti saldo carry forward hangus
        // $this->db->insert_batch('cuti_history', $insert_history_saldo_cf_hangus);
        // insert history cuti reset carry forward saldo
        $this->db->insert_batch('cuti_history', $insert_history_saldo_cf_reset);
        // update saldo data_karyawan
        $this->db->update_batch('data_karyawan', $id_karyawan, 'id_karyawan');
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            echo '[' . date('Y-m-d H:i:s') . '] [error] ' . $jenis_reset . ' GAGAL dijalankan' . PHP_EOL;
        } else {
            $this->db->trans_commit();
            echo '[' . date('Y-m-d H:i:s') . '] [success] ' . $jenis_reset . ' BERHASIL dijalankan' . PHP_EOL;
        }
    }

    /**
     * Reset saldo cuti carry forward ketika sudah maksimal bulan berdasarkan join_date
     * Karyawan dengan status tetap, kontrak, atau (tetap dan kontrak)
     * Saldo carry forward > 0
     *
     * @return void
     */
    public function reset_cuti_carry_forward_1()
    {
        $data_karyawan = $this->db->query("
                SELECT
                    dk.id_karyawan,
                    dk.nama_lengkap,
                    dk.join_date,
                    STR_TO_DATE(CONCAT(YEAR(CURRENT_DATE), '-', DATE_FORMAT(DATE_ADD(dk.join_date, INTERVAL cp.carry_forward_maks_bulan MONTH), '%m-%d')), '%Y-%m-%d') as maks_carry_forward,
                    timestampdiff(MONTH, dk.join_date, NOW()) as ttl_bulan,
                    dk.status,
                    dk.jatah_cuti,
                    dk.carry_forward,
                    cp.reset_saldo,
                    cp.carry_forward_maks_saldo,
                    cp.carry_forward_maks_bulan,
                    dk.id_company
                FROM
                    cuti_p as cp
                    join data_karyawan as dk on dk.id_company = cp.id_company
                WHERE
                    cp.reset_jenis = 'join_date'
                    AND CURRENT_DATE = STR_TO_DATE(CONCAT(YEAR(CURRENT_DATE), '-', DATE_FORMAT(DATE_ADD(dk.join_date, INTERVAL cp.carry_forward_maks_bulan MONTH), '%m-%d')), '%Y-%m-%d')
                    AND dk.join_date not in ('0000-00-00', '1970-01-01')
                    AND find_in_set(dk.status, cp.jenis_karyawan)
                    AND timestampdiff(MONTH, dk.join_date, NOW()) >= cp.join_date_bulan
                    AND dk.carry_forward > 0
                ORDER BY
                    dk.id_company ASC")->result();
        return $this->reset_carry_forward($data_karyawan, 'reset_cuti_carry_forward_by_join_date');
    }

    /**
     * Reset saldo cuti carry forward ketika sudah maksimal bulan berdasarkan bulan
     * Karyawan dengan status tetap, kontrak, atau (tetap dan kontrak)
     * Saldo carry forward > 0
     *
     * @return void
     */
    public function reset_cuti_carry_forward_2()
    {
        $data_karyawan = $this->db->query("
                SELECT
                    dk.id_karyawan,
                    dk.nama_lengkap,
                    dk.join_date,
                    DATE_ADD(STR_TO_DATE(CONCAT(YEAR(CURRENT_DATE), '-' , cp.periode_cuti, '-01'), '%Y-%m-%d'), INTERVAL cp.carry_forward_maks_bulan MONTH) as maks_carry_forward,
                    timestampdiff(MONTH, dk.join_date, NOW()) as ttl_bulan,
                    dk.status,
                    dk.jatah_cuti,
                    dk.carry_forward,
                    cp.reset_saldo,
                    cp.carry_forward_maks_saldo,
                    cp.carry_forward_maks_bulan,
                    dk.id_company
                FROM
                    cuti_p as cp
                    join data_karyawan as dk on dk.id_company = cp.id_company
                WHERE
                    cp.reset_jenis = 'bulan'
                    AND cp.periode_cuti = MONTH(NOW())
                    AND dk.join_date not in ('0000-00-00', '1970-01-01')
                    AND find_in_set(dk.status, cp.jenis_karyawan)
                    AND timestampdiff(MONTH, dk.join_date, NOW()) >= cp.join_date_bulan
                    AND dk.carry_forward > 0
                ORDER BY
                    dk.id_company ASC")->result();
        return $this->reset_carry_forward($data_karyawan, 'reset_cuti_carry_forward_by_month');
    }

    public function reset_carry_forward($data_karyawan = [], $jenis_reset = '')
    {
        // get id_karyawan
        $id_karyawan = array();
        $insert_history_saldo_hangus = array();
        $id_company = '';
        $nextId = 0;
        foreach ($data_karyawan as $row) {
            if ($id_company != $row->id_company) {
                $nextId = $this->fungsi->getNextId('cuti_history', 'id_cuti_history', $row->id_company, 3);
            }
            $id_company = $row->id_company;
            $id_karyawan[] = [
                'id_karyawan'   => $row->id_karyawan,
                'carry_forward' => 0
            ];

            if ($row->carry_forward) {
                $insert_history_saldo_hangus[] = [
                    'id_cuti_history' => $nextId,
                    'id_karyawan'     => $row->id_karyawan,
                    'tgl_trx'         => date('Y-m-d'),
                    'keterangan'      => 'Carry forward balance expired',
                    'tambah'          => 0,
                    'kurang'          => $row->carry_forward,
                    'saldo'           => 0,
                    'user_input'      => 'By System',
                    'id_company'      => $row->id_company
                ];
            }

            $last_id = substr($nextId, -3);
            $nextId = $row->id_company . date('Ym') . sprintf("%03d", ($last_id + 1));
        }

        $this->db->trans_start();
        // insert history cuti saldo carry forward hangus
        $this->db->insert_batch('cuti_history', $insert_history_saldo_hangus);
        // update saldo carry forward data_karyawan
        $this->db->update_batch('data_karyawan', $id_karyawan, 'id_karyawan');
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            echo '[' . date('Y-m-d H:i:s') . '] [error] ' . $jenis_reset . ' GAGAL dijalankan' . PHP_EOL;
        } else {
            $this->db->trans_commit();
            echo '[' . date('Y-m-d H:i:s') . '] [success] ' . $jenis_reset . ' BERHASIL dijalankan' . PHP_EOL;
        }
    }
}
