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

class IzinCuti_model extends CI_Model
{
    const TABLE = 'tb_izin_cuti';

    public function datatable_total($tahun, $bulan, $id_divisi = null, $status = '')
    {
        $this->_build_datatable_query($tahun, $bulan, $id_divisi, $status, '');
        return (int) $this->db->count_all_results();
    }

    public function datatable_filtered($tahun, $bulan, $id_divisi = null, $status = '', $search = '')
    {
        $this->_build_datatable_query($tahun, $bulan, $id_divisi, $status, $search);
        return (int) $this->db->count_all_results();
    }

    public function datatable_data($tahun, $bulan, $start, $length, $order_col = 4, $order_dir = 'desc', $id_divisi = null, $status = '', $search = '')
    {
        $columns = [
            1 => 'p.nip',
            2 => 'p.nama_lengkap',
            3 => 'd.nama_divisi',
            4 => 'tic.tipe',
            5 => 'tic.tanggal_mulai',
            6 => 'tic.tanggal_selesai',
            7 => 'tic.durasi_hari',
            8 => 'tic.status',
        ];

        $this->_build_datatable_query($tahun, $bulan, $id_divisi, $status, $search);

        $sort_field = isset($columns[(int) $order_col]) ? $columns[(int) $order_col] : 'tic.tanggal_mulai';
        $sort_dir = strtolower((string) $order_dir) === 'asc' ? 'ASC' : 'DESC';
        $this->db->order_by($sort_field, $sort_dir);
        $this->db->order_by('tic.tanggal_mulai', 'DESC');

        $length = (int) $length;
        $start = max(0, (int) $start);
        if ($length > 0) {
            $this->db->limit($length, $start);
        }

        return $this->db
            ->select('tic.*, p.nip, p.nama_lengkap, d.nama_divisi')
            ->get()->result();
    }

    private function _build_datatable_query($tahun, $bulan, $id_divisi = null, $status = '', $search = '')
    {
        $tahun = (int) $tahun;
        $bulan = (int) $bulan;
        if ($bulan < 1 || $bulan > 12) {
            $bulan = (int) date('n');
        }

        $tanggal_mulai_bulan = sprintf('%04d-%02d-01', $tahun, $bulan);
        $tanggal_selesai_bulan = date('Y-m-t', strtotime($tanggal_mulai_bulan));

        $this->db->from(self::TABLE . ' tic')
                 ->join('tb_pegawai p', 'p.id_pegawai = tic.id_pegawai', 'left')
                 ->join('tb_divisi d', 'd.id_divisi = p.id_divisi', 'left')
                 ->where('tic.tanggal_mulai <=', $tanggal_selesai_bulan)
                 ->where('tic.tanggal_selesai >=', $tanggal_mulai_bulan);

        if (!empty($id_divisi)) {
            $this->db->where('p.id_divisi', (int) $id_divisi);
        }

        if (in_array((string) $status, ['DRAFT', 'APPROVED', 'REJECTED'], true)) {
            $this->db->where('tic.status', (string) $status);
        }

        $search = trim((string) $search);
        if ($search !== '') {
            $this->db->group_start()
                     ->like('p.nip', $search)
                     ->or_like('p.nama_lengkap', $search)
                     ->or_like('d.nama_divisi', $search)
                     ->or_like('tic.tipe', $search)
                     ->or_like('tic.status', $search)
                     ->group_end();
        }
    }

    public function get_all($id_pegawai = NULL, $tahun = NULL, $status = NULL)
    {
        $this->db->from(self::TABLE);
        if ($id_pegawai) {
            $this->db->where('id_pegawai', (int) $id_pegawai);
        }
        if ($tahun) {
            $this->db->where('YEAR(tanggal_mulai)', (int) $tahun);
        }
        if ($status) {
            $this->db->where('status', $status);
        }
        return $this->db->order_by('tanggal_mulai', 'DESC')
                        ->get()->result();
    }

    public function get_by_id($id)
    {
        return $this->db->where('id_izin', (int) $id)
                        ->get(self::TABLE)->row();
    }

    public function insert($data)
    {
        return $this->db->insert(self::TABLE, $data);
    }

    public function update($id, $data)
    {
        return $this->db->where('id_izin', (int) $id)
                        ->update(self::TABLE, $data);
    }

    public function delete($id)
    {
        return $this->db->where('id_izin', (int) $id)
                        ->delete(self::TABLE);
    }

    public function approve($id, $id_user)
    {
        return $this->db->where('id_izin', (int) $id)
                        ->update(self::TABLE, [
                            'status'      => 'APPROVED',
                            'approved_by' => $id_user,
                            'approved_at' => date('Y-m-d H:i:s'),
                        ]);
    }

    /**
     * Sync semua tanggal dari izin/cuti yang di-APPROVE ke tb_absensi.
     * Panggil setelah approve() berhasil.
     */
    public function sync_to_absensi($izin)
    {
        $this->load->model('Absensi_model');

        // Map tipe izin ke status absensi
        $status_map = [
            'IZIN'          => 'IZIN',
            'SAKIT'         => 'SAKIT',
            'TIDAK_MASUK'   => 'ALPHA',
            'CUTI_TAHUNAN'  => 'CUTI',
            'CUTI_BERSAMA'  => 'CUTI',
            'CUTI_KHUSUS'   => 'CUTI',
        ];
        $status_absensi = $status_map[$izin->tipe] ?? 'IZIN';
        $keterangan     = 'Auto-sync dari izin/cuti #' . $izin->id_izin . ' (' . $izin->tipe . ')';

        $current = strtotime($izin->tanggal_mulai);
        $end     = strtotime($izin->tanggal_selesai);

        while ($current <= $end) {
            $tanggal = date('Y-m-d', $current);
            $this->Absensi_model->update_status_by_tanggal(
                $izin->id_pegawai, $tanggal, $status_absensi, $keterangan
            );
            $current = strtotime('+1 day', $current);
        }
    }

    public function reject($id, $catatan = '')
    {
        return $this->db->where('id_izin', (int) $id)
                        ->update(self::TABLE, [
                            'status'  => 'REJECTED',
                            'catatan' => $catatan,
                        ]);
    }

    public function get_pending()
    {
        return $this->db->where('status', 'DRAFT')
                        ->order_by('created_at', 'ASC')
                        ->limit(20)
                        ->get(self::TABLE)->result();
    }

    public function get_summary_pegawai($id_pegawai, $tahun)
    {
        return $this->db->select('tipe, COUNT(*) as total_hari')
                        ->where('id_pegawai', (int) $id_pegawai)
                        ->where('YEAR(tanggal_mulai)', (int) $tahun)
                        ->where('status', 'APPROVED')
                        ->group_by('tipe')
                        ->get(self::TABLE)->result();
    }
}
