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

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

    // -------------------------------------------------------
    // Index — daftar semua pegawai aktif
    // -------------------------------------------------------

    public function index()
    {
        $id_divisi = $this->input->get('divisi');

        $this->db->select('p.id_pegawai, p.nip, p.nama_lengkap, p.gaji_pokok, d.nama_divisi, j.nama_jabatan,
                   COUNT(DISTINCT k.id_komponen) as total_komponen_aktif', false)
                 ->from('tb_pegawai p')
                 ->join('tb_divisi d',  'd.id_divisi  = p.id_divisi',  'left')
                 ->join('tb_jabatan j', 'j.id_jabatan = p.id_jabatan', 'left')
                 ->join('tb_pegawai_komponen pk', 'pk.id_pegawai = p.id_pegawai AND pk.is_active = 1', 'left')
                 ->join('tb_komponen_gaji k', "k.id_komponen = pk.id_komponen AND k.is_active = 1 AND k.kode_komponen NOT IN ('LEMBUR', 'GAPOK')", 'left')
                 ->where('p.status_pegawai', 'AKTIF');

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

        $list = $this->db->group_by('p.id_pegawai')
                         ->order_by('d.nama_divisi, p.nama_lengkap', 'ASC')
                         ->get()->result();

        $data = [
            'title'        => 'Mapping Gaji | ' . app_name(),
            'page_title'   => 'Mapping Gaji',
            'page_subtitle'=> 'Atur komponen gaji untuk setiap pegawai, termasuk gaji pokok',
            'list'         => $list,
            'divisi_list'  => $this->Divisi_model->get_all(),
            'f_divisi'     => $id_divisi ? (int) $id_divisi : '',
        ];
        $this->render('master/mapping_komponen/list', $data);
    }

    // -------------------------------------------------------
    // Form mapping per pegawai
    // -------------------------------------------------------

    public function pegawai($id_pegawai = NULL)
    {
        $pegawai = $this->Pegawai_model->get_by_id((int) $id_pegawai);
        if (!$pegawai) {
            $this->session->set_flashdata('error', 'Pegawai tidak ditemukan.');
            redirect('master/mapping_komponen');
        }

        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            return $this->_simpan($pegawai);
        }

        $data = [
            'title'         => 'Mapping Gaji: ' . $pegawai->nama_lengkap . ' | ' . app_name(),
            'page_title'    => 'Mapping Gaji',
            'page_subtitle' => html_escape($pegawai->nama_lengkap),
            'pegawai'       => $pegawai,
            'list_komponen' => $this->Pegawai_model->get_komponen_mapping_full((int) $id_pegawai),
        ];
        $this->render('master/mapping_komponen/form', $data);
    }

    // -------------------------------------------------------
    // Private: simpan mapping
    // -------------------------------------------------------

    private function _simpan($pegawai)
    {
        $id_pegawai    = (int) $pegawai->id_pegawai;
        $list_komponen = $this->Pegawai_model->get_komponen_mapping_full($id_pegawai);

        $post_aktif   = (array) $this->input->post('aktif');
        $post_override = (array) $this->input->post('override');
        $post_catatan = (array) $this->input->post('catatan');

        // Gaji pokok dikirim via field khusus gapok_nominal
        $gapok_nominal_raw = trim((string) $this->input->post('gapok_nominal', TRUE));
        $gapok_nilai       = null;

        if ($gapok_nominal_raw !== '') {
            if (strpos($gapok_nominal_raw, ',') !== false && strpos($gapok_nominal_raw, '.') !== false) {
                $clean = str_replace('.', '', $gapok_nominal_raw);
                $clean = str_replace(',', '.', $clean);
            } elseif (strpos($gapok_nominal_raw, ',') !== false) {
                $clean = str_replace(',', '.', $gapok_nominal_raw);
            } else {
                $clean = $gapok_nominal_raw;
            }
            $val = (float) preg_replace('/[^0-9.]/', '', $clean);
            if ($val > 0) {
                $gapok_nilai = $val;
            }
        }

        $items = [];
        foreach ($list_komponen as $k) {
            $id_komponen = (int) $k->id_komponen;

            $raw_override = trim((string) ($post_override[$id_komponen] ?? ''));
            $nilai_override = null;
            if (($k->cara_hitung ?? 'FLAT') === 'FLAT' && $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;
                }
                $clean = preg_replace('/[^0-9.\-]/', '', $clean);
                if ($clean !== '' && is_numeric($clean)) {
                    $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_pegawai, $items, $this->session->userdata('id_user'));
        if (!$saved) {
            $this->session->set_flashdata('error', ['title' => 'Gagal', 'text' => 'Mapping komponen gagal disimpan.']);
            redirect('master/mapping_komponen/pegawai/' . $id_pegawai);
        }

        // Sinkronisasi gaji_pokok ke tb_pegawai jika GAPOK override berubah
        if ($gapok_nilai !== null && (float) $gapok_nilai !== (float) $pegawai->gaji_pokok) {
            $this->Pegawai_model->log_histori(
                $id_pegawai, 'GAJI',
                $pegawai->gaji_pokok,
                $gapok_nilai,
                'Diubah via Mapping Komponen',
                $this->session->userdata('id_user')
            );
            $this->db->where('id_pegawai', $id_pegawai)->update('tb_pegawai', ['gaji_pokok' => $gapok_nilai]);
        }

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