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

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

    // -------------------------------------------------------
    // List (DataTables server-side)
    // -------------------------------------------------------

    public function index()
    {
        $data = [
            'title'        => 'Data Pegawai | ' . app_name(),
            'page_title'   => 'Data Pegawai',
            'page_subtitle'=> 'Daftar seluruh pegawai aktif dan nonaktif',
            'list_divisi'  => $this->Divisi_model->get_all(TRUE),
        ];
        $this->render('master/pegawai/list', $data);
    }

    public function ajax_list()
    {
        if (!$this->input->is_ajax_request()) show_404();

        $draw    = (int) $this->input->post('draw');
        $start   = (int) $this->input->post('start');
        $length  = (int) $this->input->post('length');
        $search  = $this->input->post('search[value]', TRUE);
        $order_col = (int) $this->input->post('order[0][column]');
        $order_dir = $this->input->post('order[0][dir]', TRUE);

        $filter = [];
        if ($this->input->post('filter_divisi')) {
            $filter['id_divisi'] = (int) $this->input->post('filter_divisi', TRUE);
        }
        if ($this->input->post('filter_status')) {
            $filter['status_pegawai'] = $this->input->post('filter_status', TRUE);
        }

        $total    = $this->Pegawai_model->datatable_total();
        $filtered = $this->Pegawai_model->datatable_total($filter);
        $rows     = $this->Pegawai_model->datatable_data($start, $length, $search, $order_col, $order_dir, $filter);

        $result = [];
        foreach ($rows as $r) {
            $badge_class = $r->status_pegawai === 'AKTIF' ? 'badge-aktif' : 'badge-nonaktif';
            $result[] = [
                'nip'           => html_escape($r->nip),
                'nama_lengkap'  => html_escape($r->nama_lengkap),
                'nama_divisi'   => html_escape($r->nama_divisi),
                'nama_jabatan'  => html_escape($r->nama_jabatan),
                'tanggal_masuk' => tgl_indonesia($r->tanggal_masuk),
                'no_telepon'    => html_escape($r->no_telepon),
                'status_pegawai'=> '<span class="badge ' . $badge_class . '">' . $r->status_pegawai . '</span>',
                'aksi'          => $this->_aksi($r->id_pegawai, $r->status_pegawai),
            ];
        }

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

    // -------------------------------------------------------
    // Detail
    // -------------------------------------------------------

    public function detail($id = NULL)
    {
        $row = $this->_get_or_404($id);
        $data = [
            'title'         => 'Detail Pegawai | ' . app_name(),
            'page_title'    => 'Detail Pegawai',
            'page_subtitle' => html_escape($row->nama_lengkap),
            'row'           => $row,
            'riwayat_list'  => $this->Pegawai_model->get_histori($id),
        ];
        $this->render('master/pegawai/detail', $data);
    }

    public function riwayat()
    {
        // Riwayat Perubahan sudah dipindahkan ke tab di halaman Detail Pegawai
        // Redirect ke halaman Data Pegawai
        $this->session->set_flashdata('info', ['title' => 'Info', 'text' => 'Riwayat Perubahan sudah dipindahkan ke tab di halaman Detail Pegawai. Pilih pegawai untuk melihat riwayatnya.']);
        redirect('master/pegawai');
    }

    public function komponen($id = NULL)
    {
        // Dialihkan ke halaman Mapping Komponen yang mandiri
        redirect('master/mapping_komponen/pegawai/' . (int) $id);
        return;

        // --- kode lama di bawah sudah tidak digunakan ---
        $row = $this->_get_or_404($id);
        $list_komponen = $this->Pegawai_model->get_komponen_mapping($id);

        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            $post_aktif = (array) $this->input->post('aktif');
            $post_override = (array) $this->input->post('override');
            $post_catatan = (array) $this->input->post('catatan');

            $items = [];
            foreach ($list_komponen as $k) {
                $id_komponen = (int) $k->id_komponen;
                $raw_override = trim((string) ($post_override[$id_komponen] ?? ''));
                $nilai_override = null;
                if ($raw_override !== '') {
                    if (strpos($raw_override, ',') !== false && strpos($raw_override, '.') !== false) {
                        $clean = str_replace('.', '', $raw_override);
                        $clean = str_replace(',', '.', $clean);
                    } elseif (strpos($raw_override, ',') !== false) {
                        $clean = str_replace(',', '.', $raw_override);
                    } else {
                        $clean = $raw_override;
                    }
                    $nilai_override = (float) $clean;
                }

                $items[] = [
                    'id_komponen'    => $id_komponen,
                    'is_active'      => isset($post_aktif[$id_komponen]) ? 1 : 0,
                    'nilai_override' => $nilai_override,
                    'catatan'        => trim((string) ($post_catatan[$id_komponen] ?? '')),
                ];
            }

            $saved = $this->Pegawai_model->save_komponen_mapping($id, $items, $this->session->userdata('id_user'));
            if (!$saved) {
                $this->session->set_flashdata('error', ['title' => 'Gagal', 'text' => 'Mapping komponen gagal disimpan.']);
                redirect('master/pegawai/komponen/' . (int) $id);
            }

            audit_log('UPDATE', 'Mapping Komponen Pegawai', 'Pegawai ID: ' . (int) $id);
            $this->session->set_flashdata('success', ['title' => 'Berhasil', 'text' => 'Mapping komponen pegawai berhasil diperbarui.']);
            redirect('master/pegawai/komponen/' . (int) $id);
        }

        $data = [
            'title'         => 'Mapping Komponen Pegawai | ' . app_name(),
            'page_title'    => 'Mapping Komponen Pegawai',
            'page_subtitle' => html_escape($row->nama_lengkap),
            'row'           => $row,
            'list_komponen' => $list_komponen,
        ];
        $this->render('master/pegawai/komponen', $data);
    }

    // -------------------------------------------------------
    // Form tambah
    // -------------------------------------------------------

    public function tambah()
    {
        $this->_form_rules();

        if ($this->form_validation->run() === FALSE) {
            $this->_form_view();
            return;
        }

        $nip = trim($this->input->post('nip', TRUE));
        if ($this->Pegawai_model->nip_exists($nip)) {
            $this->session->set_flashdata('error', ['title' => 'Gagal', 'text' => 'NIP sudah terdaftar.']);
            $this->_form_view();
            return;
        }

        $id = $this->Pegawai_model->insert($this->_collect_post());
        audit_log('TAMBAH', 'PEGAWAI', 'Tambah pegawai NIP: ' . $nip);
        $this->session->set_flashdata('success', ['title' => 'Berhasil', 'text' => 'Data pegawai berhasil ditambahkan.']);
        redirect('master/pegawai/detail/' . $id);
    }

    // -------------------------------------------------------
    // Form edit
    // -------------------------------------------------------

    public function edit($id = NULL)
    {
        $row = $this->_get_or_404($id);
        $this->_form_rules($id);

        if ($this->form_validation->run() === FALSE) {
            $this->_form_view($row);
            return;
        }

        $nip = trim($this->input->post('nip', TRUE));
        if ($this->Pegawai_model->nip_exists($nip, $id)) {
            $this->session->set_flashdata('error', ['title' => 'Gagal', 'text' => 'NIP sudah digunakan pegawai lain.']);
            $this->_form_view($row);
            return;
        }

        // Catat histori jika jabatan berubah
        $post = $this->_collect_post();
        if ((int) $post['id_jabatan'] !== (int) $row->id_jabatan) {
            $this->Pegawai_model->log_histori(
                $id, 'JABATAN',
                $row->id_jabatan . '|' . $row->nama_jabatan,
                $post['id_jabatan'],
                'Perubahan jabatan via form edit',
                $this->session->userdata('id_user')
            );
        }

        $this->Pegawai_model->update($id, $post);
        audit_log('EDIT', 'PEGAWAI', 'Edit pegawai ID: ' . $id);
        $this->session->set_flashdata('success', ['title' => 'Berhasil', 'text' => 'Data pegawai berhasil diperbarui.']);
        redirect('master/pegawai/detail/' . $id);
    }

    // -------------------------------------------------------
    // Toggle status
    // -------------------------------------------------------

    public function toggle_status($id = NULL)
    {
        $row = $this->_get_or_404($id);
        $new_status = $row->status_pegawai === 'AKTIF' ? 'NONAKTIF' : 'AKTIF';
        $this->Pegawai_model->set_status($id, $new_status);
        $this->Pegawai_model->log_histori(
            $id, 'STATUS', $row->status_pegawai, $new_status,
            'Toggle status via UI', $this->session->userdata('id_user')
        );
        audit_log('TOGGLE', 'PEGAWAI', "Status pegawai ID {$id}: {$row->status_pegawai} → {$new_status}");
        $this->session->set_flashdata('success', ['title' => 'Berhasil', 'text' => "Status pegawai diubah menjadi <strong>{$new_status}</strong>."]);
        redirect('master/pegawai');
    }

    // -------------------------------------------------------
    // Helpers private
    // -------------------------------------------------------

    private function _form_rules($exclude_id = NULL)
    {
        $this->form_validation->set_rules('nip',            'NIP',            'required|trim|max_length[20]|alpha_numeric_spaces');
        $this->form_validation->set_rules('nama_lengkap',   'Nama Lengkap',   'required|trim|max_length[150]');
        $this->form_validation->set_rules('jenis_kelamin',  'Jenis Kelamin',  'required|in_list[L,P]');
        $this->form_validation->set_rules('id_divisi',      'Divisi',         'required|is_natural_no_zero');
        $this->form_validation->set_rules('id_jabatan',     'Jabatan',        'required|is_natural_no_zero');
        $this->form_validation->set_rules('tanggal_masuk',  'Tanggal Masuk',  'required');
        $this->form_validation->set_rules('ptkp_status',    'Status PTKP',    'required');
    }

    private function _collect_post()
    {
        return [
            'nip'                        => trim($this->input->post('nip', TRUE)),
            'nik'                        => trim($this->input->post('nik', TRUE)),
            'nama_lengkap'               => trim($this->input->post('nama_lengkap', TRUE)),
            'jenis_kelamin'              => $this->input->post('jenis_kelamin', TRUE),
            'tempat_lahir'               => trim($this->input->post('tempat_lahir', TRUE)),
            'tanggal_lahir'              => $this->input->post('tanggal_lahir', TRUE) ?: NULL,
            'alamat'                     => trim($this->input->post('alamat', TRUE)),
            'no_telepon'                 => trim($this->input->post('no_telepon', TRUE)),
            'email'                      => trim($this->input->post('email', TRUE)),
            'id_divisi'                  => (int) $this->input->post('id_divisi', TRUE),
            'id_jabatan'                 => (int) $this->input->post('id_jabatan', TRUE),
            'tanggal_masuk'              => $this->input->post('tanggal_masuk', TRUE),
            'npwp'                       => trim($this->input->post('npwp', TRUE)),
            'no_bpjs_kesehatan'          => trim($this->input->post('no_bpjs_kesehatan', TRUE)),
            'no_bpjs_ketenagakerjaan'    => trim($this->input->post('no_bpjs_ketenagakerjaan', TRUE)),
            'no_rekening'                => trim($this->input->post('no_rekening', TRUE)),
            'nama_bank'                  => trim($this->input->post('nama_bank', TRUE)),
            'ptkp_status'                => $this->input->post('ptkp_status', TRUE),
        ];
    }

    private function _form_view($row = NULL)
    {
        $data = [
            'title'        => ($row ? 'Edit' : 'Tambah') . ' Pegawai | ' . app_name(),
            'page_title'   => ($row ? 'Edit' : 'Tambah') . ' Pegawai',
            'page_subtitle'=> 'Master Data Pegawai',
            'row'          => $row,
            'list_divisi'  => $this->Divisi_model->get_all(TRUE),
            'list_jabatan' => $row ? $this->Jabatan_model->get_by_divisi($row->id_divisi) : [],
            'ptkp_options' => ['TK0','TK1','TK2','TK3','K0','K1','K2','K3','K_I0','K_I1','K_I2','K_I3'],
        ];
        $this->render('master/pegawai/form', $data);
    }

    private function _aksi($id, $status)
    {
        $url_detail = site_url('master/pegawai/detail/' . $id);
        $url_edit   = site_url('master/pegawai/edit/' . $id);
           $url_map    = site_url('master/pegawai/komponen/' . $id);
        $url_toggle = site_url('master/pegawai/toggle_status/' . $id);
        $lbl_toggle = $status === 'AKTIF' ? 'Nonaktifkan' : 'Aktifkan';
        $cls_toggle = $status === 'AKTIF' ? 'btn-warning' : 'btn-success';
        return '<a href="' . $url_detail . '" class="btn btn-info btn-xs mr-1" title="Detail"><i class="fa fa-eye"></i></a>'
             . '<a href="' . $url_edit . '" class="btn btn-primary btn-xs mr-1" title="Edit"><i class="fa fa-pencil"></i></a>'
               . '<a href="' . $url_map . '" class="btn btn-secondary btn-xs mr-1" title="Mapping Komponen"><i class="fa fa-sliders"></i></a>'
             . '<a href="' . $url_toggle . '" class="btn ' . $cls_toggle . ' btn-xs btn-confirm" data-msg="' . $lbl_toggle . ' pegawai ini?" title="' . $lbl_toggle . '"><i class="fa fa-power-off"></i></a>';
    }

    private function _get_or_404($id)
    {
        $row = $this->Pegawai_model->get_by_id($id);
        if (!$row) show_404();
        return $row;
    }
}
