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

class IzinCuti extends Auth_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model(['IzinCuti_model', 'Pegawai_model', 'Divisi_model', 'Payroll_model']);
    }

    public function index()
    {
        $status = strtoupper((string) $this->input->get('status'));
        $tahun = (int) ($this->input->get('tahun') ?: date('Y'));
        $bulan = (int) ($this->input->get('bulan') ?: date('n'));
        $id_divisi = $this->input->get('divisi');
        if ($bulan < 1 || $bulan > 12) {
            $bulan = (int) date('n');
        }
        
        $data = [
            'page_title'    => 'Manajemen Izin',
            'page_subtitle' => 'Kelola pengajuan izin, sakit, tidak masuk, dan cuti pegawai',
            'f_status'      => in_array($status, ['DRAFT', 'APPROVED', 'REJECTED'], TRUE) ? $status : '',
            'f_divisi'      => $id_divisi ? (int) $id_divisi : '',
            'f_tahun'       => $tahun,
            'f_bulan'       => str_pad((string) $bulan, 2, '0', STR_PAD_LEFT),
            'divisi_list'   => $this->Divisi_model->get_all(),
        ];
        $this->render('transaksi/izin_cuti/list', $data);
    }

    public function ajax_list()
    {
        $tahun = (int) ($this->input->get_post('tahun') ?: date('Y'));
        $bulan = (int) ($this->input->get_post('bulan') ?: date('m'));
        $status = strtoupper((string) $this->input->get_post('filter_status'));
        $id_divisi = $this->input->get_post('divisi') ? (int) $this->input->get_post('divisi') : NULL;
        $draw    = (int) $this->input->get_post('draw');
        $start   = (int) $this->input->get_post('start');
        $length  = (int) $this->input->get_post('length');
        $search  = trim((string) $this->input->get_post('search[value]', TRUE));
        $order_col = (int) $this->input->get_post('order[0][column]');
        $order_dir = (string) $this->input->get_post('order[0][dir]', TRUE);

        $total = $this->IzinCuti_model->datatable_total($tahun, $bulan, $id_divisi, $status);
        $filtered = $this->IzinCuti_model->datatable_filtered($tahun, $bulan, $id_divisi, $status, $search);
        $rows = $this->IzinCuti_model->datatable_data($tahun, $bulan, $start, $length, $order_col, $order_dir, $id_divisi, $status, $search);

        $data = [];
        foreach ($rows as $row) {
            $status_badge = 'badge-secondary';
            if ($row->status === 'DRAFT') $status_badge = 'badge-warning';
            elseif ($row->status === 'APPROVED') $status_badge = 'badge-success';
            elseif ($row->status === 'REJECTED') $status_badge = 'badge-danger';

            $tipe_display = (string) $row->tipe;
            if ($row->tipe === 'CUTI_TAHUNAN') $tipe_display = 'Cuti Tahunan';
            elseif ($row->tipe === 'CUTI_BERSAMA') $tipe_display = 'Cuti Bersama';
            elseif ($row->tipe === 'CUTI_KHUSUS') $tipe_display = 'Cuti Khusus';
            elseif ($row->tipe === 'TIDAK_MASUK') $tipe_display = 'Tidak Masuk';

            $aksi = '';
            if ($row->status === 'DRAFT') {
                $aksi .= '<a href="' . site_url('transaksi/izin_cuti/edit/' . $row->id_izin) . '" class="btn btn-xs btn-primary mr-1" title="Edit"><i class="fa fa-pencil"></i></a>';
                $aksi .= '<button type="button" class="btn btn-xs btn-success btn-approve mr-1" data-id="' . (int) $row->id_izin . '" title="Setujui"><i class="fa fa-check"></i></button>';
                $aksi .= '<button type="button" class="btn btn-xs btn-warning btn-reject mr-1" data-id="' . (int) $row->id_izin . '" title="Tolak"><i class="fa fa-times"></i></button>';
                $aksi .= '<button type="button" class="btn btn-xs btn-danger btn-confirm-delete" data-id="' . (int) $row->id_izin . '" title="Hapus"><i class="fa fa-trash"></i></button>';
            } else {
                $aksi .= '<a href="' . site_url('transaksi/izin_cuti/edit/' . $row->id_izin) . '" class="btn btn-xs btn-info" title="Lihat"><i class="fa fa-eye"></i></a>';
            }

            $data[] = [
                'nip'            => html_escape($row->nip),
                'nama_lengkap'   => html_escape($row->nama_lengkap),
                'nama_divisi'    => html_escape($row->nama_divisi),
                'tipe'           => $tipe_display,
                'tanggal_mulai'  => format_tanggal($row->tanggal_mulai),
                'tanggal_selesai'=> format_tanggal($row->tanggal_selesai),
                'durasi_hari'    => '<strong>' . (int) $row->durasi_hari . '</strong>',
                'status'         => '<span class="badge ' . $status_badge . '">' . html_escape($row->status) . '</span>',
                'aksi'           => $aksi,
            ];
        }

        echo json_encode([
            'draw'            => $draw,
            'recordsTotal'    => $total,
            'recordsFiltered' => $filtered,
            'data'            => $data,
        ]);
    }

    public function tambah()
    {
        $data = [
            'page_title'    => 'Tambah Pengajuan Izin',
            'page_subtitle' => 'Buat pengajuan izin, sakit, tidak masuk, atau cuti baru',
            'pegawai_list'  => $this->Pegawai_model->get_all(),
            'pegawai_label' => '',
            'row'           => NULL,
        ];
        $this->render('transaksi/izin_cuti/form', $data);
    }

    public function edit($id)
    {
        $izin = $this->IzinCuti_model->get_by_id((int) $id);
        if (!$izin) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan');
            redirect('transaksi/izin_cuti');
        }

        $data = [
            'page_title'    => 'Edit Pengajuan Izin',
            'page_subtitle' => 'Ubah data pengajuan',
            'pegawai_list'  => $this->Pegawai_model->get_all(),
            'pegawai_label' => '',
            'row'           => $izin,
        ];

        $pegawai = $this->Pegawai_model->get_by_id((int) $izin->id_pegawai);
        if ($pegawai) {
            $data['pegawai_label'] = trim((string) $pegawai->nip) . ' - ' . trim((string) $pegawai->nama_lengkap);
        }

        $this->render('transaksi/izin_cuti/form', $data);
    }

    public function ajax_pegawai_search()
    {
        $this->output->set_content_type('application/json');
        $q = trim((string) $this->input->get('q', TRUE));
        if ($q === '' || strlen($q) < 2) {
            echo json_encode([]);
            return;
        }

        $this->db->select('id_pegawai, nip, nama_lengkap, id_divisi')
                 ->from('tb_pegawai')
                 ->where('status_pegawai', 'AKTIF')
                 ->group_start()
                 ->like('nip', $q, 'both')
                 ->or_like('nama_lengkap', $q, 'both')
                 ->group_end()
                 ->order_by('nama_lengkap', 'ASC')
                 ->limit(20);
        $rows = $this->db->get()->result();

        $result = [];
        foreach ($rows as $row) {
            $result[] = [
                'id_pegawai' => (int) $row->id_pegawai,
                'nip' => $row->nip,
                'nama_lengkap' => $row->nama_lengkap,
                'label' => $row->nip . ' - ' . $row->nama_lengkap,
            ];
        }

        echo json_encode($result);
    }

    public function simpan()
    {
        if ($this->input->server('REQUEST_METHOD') !== 'POST') {
            redirect('transaksi/izin_cuti');
        }

        $id = $this->input->post('id_izin');
        $tgl_mulai = $this->input->post('tanggal_mulai');
        $tgl_selesai = $this->input->post('tanggal_selesai');
        $durasi = (strtotime($tgl_selesai) - strtotime($tgl_mulai)) / (24 * 3600) + 1;

        $payload = [
            'id_pegawai'     => $this->input->post('id_pegawai'),
            'tipe'           => $this->input->post('tipe'),
            'tanggal_mulai'  => $tgl_mulai,
            'tanggal_selesai'=> $tgl_selesai,
            'durasi_hari'    => (int) $durasi,
            'alasan'         => $this->input->post('alasan'),
            'status'         => 'DRAFT',
        ];

        if ($this->Payroll_model->has_locked_or_approved_period($tgl_mulai, $tgl_selesai)) {
            $this->session->set_flashdata('error', 'Periode payroll APPROVED/LOCKED tidak dapat diubah');
            redirect('transaksi/izin_cuti');
        }

        if ($id) {
            $this->IzinCuti_model->update($id, $payload);
            audit_log('UPDATE', 'IzinCuti', "ID: $id");
        } else {
            $this->IzinCuti_model->insert($payload);
            audit_log('INSERT', 'IzinCuti', 'Tipe: ' . $payload['tipe']);
        }

        $this->session->set_flashdata('success', 'Data tersimpan');
        redirect('transaksi/izin_cuti');
    }

    public function approve($id)
    {
        if (!$this->input->is_ajax_request()) {
            show_404();
        }

        $izin = $this->IzinCuti_model->get_by_id((int) $id);
        if (!$izin) {
            echo json_encode(['success' => FALSE, 'msg' => 'Data tidak ditemukan']);
            exit;
        }

        if ($this->Payroll_model->has_locked_or_approved_period($izin->tanggal_mulai, $izin->tanggal_selesai)) {
            echo json_encode(['success' => FALSE, 'message' => 'Periode payroll APPROVED/LOCKED tidak dapat diubah']);
            exit;
        }

        $id_user = $this->session->userdata('id_user');
        $approved = $this->IzinCuti_model->approve($id, $id_user);
        if (!$approved) {
            $db_error = $this->db->error();
            $message = !empty($db_error['message']) ? $db_error['message'] : 'Gagal mengubah status pengajuan.';
            echo json_encode(['success' => FALSE, 'message' => $message]);
            exit;
        }

        // Auto-sync ke tb_absensi
        $this->IzinCuti_model->sync_to_absensi($izin);

        audit_log('APPROVE', 'IzinCuti', "ID: $id | Sync absensi: {$izin->tanggal_mulai} s/d {$izin->tanggal_selesai}");
        echo json_encode(['success' => TRUE, 'msg' => 'Disetujui dan absensi diperbarui']);
    }

    public function reject($id)
    {
        if (!$this->input->is_ajax_request()) {
            show_404();
        }

        $catatan = $this->input->post('catatan');
        $izin = $this->IzinCuti_model->get_by_id((int) $id);
        if (!$izin) {
            echo json_encode(['success' => FALSE, 'msg' => 'Data tidak ditemukan']);
            exit;
        }

        if ($this->Payroll_model->has_locked_or_approved_period($izin->tanggal_mulai, $izin->tanggal_selesai)) {
            echo json_encode(['success' => FALSE, 'message' => 'Periode payroll APPROVED/LOCKED tidak dapat diubah']);
            exit;
        }

        $rejected = $this->IzinCuti_model->reject($id, $catatan);
        if (!$rejected) {
            $db_error = $this->db->error();
            $message = !empty($db_error['message']) ? $db_error['message'] : 'Gagal mengubah status pengajuan.';
            echo json_encode(['success' => FALSE, 'message' => $message]);
            exit;
        }
        audit_log('REJECT', 'IzinCuti', "ID: $id | Catatan: $catatan");
        echo json_encode(['success' => TRUE, 'msg' => 'Ditolak']);
    }

    public function hapus($id)
    {
        $izin = $this->IzinCuti_model->get_by_id((int) $id);
        if (!$izin || $izin->status !== 'DRAFT') {
            $this->session->set_flashdata('error', 'Hanya draft yang dapat dihapus');
            redirect('transaksi/izin_cuti');
        }

        if ($this->Payroll_model->has_locked_or_approved_period($izin->tanggal_mulai, $izin->tanggal_selesai)) {
            $this->session->set_flashdata('error', 'Data pada periode payroll APPROVED/LOCKED tidak dapat dihapus');
            redirect('transaksi/izin_cuti');
        }

        $this->IzinCuti_model->delete($id);
        audit_log('DELETE', 'IzinCuti', "ID: $id");
        $this->session->set_flashdata('success', 'Data dihapus');
        redirect('transaksi/izin_cuti');
    }
}
