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

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

    // ----------------------------------------------------------------
    // MASTER SHIFT
    // ----------------------------------------------------------------

    public function index()
    {
        $data = [
            'page_title'    => 'Manajemen Shift',
            'page_subtitle' => 'Kelola jadwal shift kerja pegawai',
            'list'          => $this->Shift_model->get_all(FALSE),
        ];
        $this->render('master/shift/list', $data);
    }

    public function tambah()
    {
        $data = [
            'page_title'    => 'Tambah Shift',
            'page_subtitle' => 'Buat jadwal shift baru',
            'row'           => NULL,
        ];
        $this->render('master/shift/form', $data);
    }

    public function edit($id)
    {
        $shift = $this->Shift_model->get_by_id((int) $id);
        if (!$shift) {
            $this->session->set_flashdata('error', 'Shift tidak ditemukan');
            redirect('master/shift');
        }
        $data = [
            'page_title'    => 'Edit Shift',
            'page_subtitle' => html_escape($shift->nama_shift),
            'row'           => $shift,
        ];
        $this->render('master/shift/form', $data);
    }

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

        $id          = (int) $this->input->post('id_shift');
        $jam_masuk   = $this->input->post('jam_masuk');
        $jam_keluar  = $this->input->post('jam_keluar');

        // Deteksi lintas tengah malam otomatis
        $lintas = (strtotime($jam_keluar) < strtotime($jam_masuk)) ? 1 : 0;

        $payload = [
            'kode_shift'          => strtoupper(trim($this->input->post('kode_shift'))),
            'nama_shift'          => $this->input->post('nama_shift'),
            'jam_masuk'           => $jam_masuk,
            'jam_keluar'          => $jam_keluar,
            'toleransi_menit'     => (int) $this->input->post('toleransi_menit') ?: 15,
            'lintas_tengah_malam' => $lintas,
            'is_active'           => (int) (bool) $this->input->post('is_active'),
        ];

        if ($id) {
            $this->Shift_model->update($id, $payload);
            audit_log('UPDATE', 'Shift', "ID: $id | " . $payload['nama_shift']);
            $msg = 'Shift berhasil diperbarui';
        } else {
            $this->Shift_model->insert($payload);
            audit_log('INSERT', 'Shift', $payload['nama_shift']);
            $msg = 'Shift berhasil ditambahkan';
        }

        $this->session->set_flashdata('success', $msg);
        redirect('master/shift');
    }

    public function set_default($id)
    {
        $shift = $this->Shift_model->get_by_id((int) $id);
        if (!$shift) {
            $this->session->set_flashdata('error', 'Shift tidak ditemukan');
            redirect('master/shift');
        }

        $this->Shift_model->set_default($id);
        audit_log('UPDATE', 'Shift', "Set default: ID $id | " . $shift->nama_shift);
        $this->session->set_flashdata('success', 'Shift "' . html_escape($shift->nama_shift) . '" dijadikan shift default');
        redirect('master/shift');
    }

    // ----------------------------------------------------------------
    // JADWAL KERJA MINGGUAN (per Pegawai atau per Divisi)
    // ----------------------------------------------------------------

    public function assignment()
    {
        $tipe        = $this->input->get('tipe') ?: 'PEGAWAI';
        $id_divisi   = $this->input->get('divisi');

        $data = [
            'page_title'    => 'Jadwal Kerja',
            'page_subtitle' => 'Tetapkan jam kerja mingguan per pegawai atau per divisi',
            'f_tipe'        => $tipe,
            'f_divisi'      => $id_divisi ? (int) $id_divisi : '',
            'shift_list'    => $this->Shift_model->get_all(),
            'default_shift' => $this->Shift_model->get_default(),
            'divisi_list'   => $this->Divisi_model->get_all(),
            'list'          => $this->_get_assignment_list($tipe, $id_divisi),
        ];
        $this->render('master/shift/assignment', $data);
    }

    public function simpan_assignment()
    {
        if ($this->input->server('REQUEST_METHOD') !== 'POST') {
            redirect('master/shift/assignment');
        }

        $tipe    = $this->input->post('tipe');
        $id_ref  = (int) $this->input->post('id_referensi');
        $tgl_mulai  = $this->input->post('berlaku_mulai');
        $tgl_selesai = $this->input->post('berlaku_selesai') ?: NULL;

        if (!in_array($tipe, ['PEGAWAI', 'DIVISI'], TRUE) || $id_ref <= 0 || empty($tgl_mulai)) {
            $this->session->set_flashdata('error', 'Data target jadwal belum lengkap');
            redirect('master/shift/assignment');
        }

        $hari_shift = (array) $this->input->post('hari_shift');
        $keterangan = trim((string) $this->input->post('keterangan'));
        $total_hari_kerja = 0;

        for ($hari = 1; $hari <= 7; $hari++) {
            $raw_value = strtoupper(trim((string) ($hari_shift[$hari] ?? 'OFF')));
            $is_hari_kerja = ($raw_value !== 'OFF');
            $id_shift = $is_hari_kerja ? (int) $raw_value : NULL;

            if ($is_hari_kerja) {
                $shift = $this->Shift_model->get_by_id($id_shift);
                if (!$shift) {
                    $this->session->set_flashdata('error', 'Shift untuk jadwal mingguan tidak valid');
                    redirect('master/shift/assignment');
                }
                $total_hari_kerja++;
            }

            $payload = [
                'tipe'            => $tipe,
                'id_referensi'    => $id_ref,
                'hari_ke'         => $hari,
                'is_hari_kerja'   => $is_hari_kerja ? 1 : 0,
                'id_shift'        => $id_shift,
                'berlaku_mulai'   => $tgl_mulai,
                'berlaku_selesai' => $tgl_selesai,
                'keterangan'      => $keterangan,
            ];

            $this->Shift_model->upsert_assignment_day($payload);
        }

        if ($total_hari_kerja === 0) {
            $this->session->set_flashdata('warning', 'Jadwal tersimpan, tetapi semua hari ditandai OFF/libur.');
        } else {
            $this->session->set_flashdata('success', 'Jadwal kerja mingguan berhasil disimpan');
        }

        audit_log('UPSERT', 'ShiftAssignment', "Tipe: $tipe | Ref: $id_ref | Hari kerja: $total_hari_kerja");
        redirect('master/shift/assignment');
    }

    public function hapus_assignment($id)
    {
        $asgn = $this->Shift_model->get_assignment_by_id((int) $id);
        if (!$asgn) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan');
            redirect('master/shift/assignment');
        }

        $this->Shift_model->delete_assignment($id);
        audit_log('DELETE', 'ShiftAssignment', "ID: $id");
        $this->session->set_flashdata('success', 'Assignment dihapus');
        redirect('master/shift/assignment');
    }

    public function hapus_group()
    {
        $tipe         = $this->input->get('tipe');
        $id_referensi = (int) $this->input->get('id_referensi');
        $berlaku_mulai = $this->input->get('berlaku_mulai');

        if (!in_array($tipe, ['PEGAWAI', 'DIVISI'], TRUE) || $id_referensi <= 0 || empty($berlaku_mulai)) {
            $this->session->set_flashdata('error', 'Parameter tidak valid');
            redirect('master/shift/assignment');
        }

        $this->db->where('tipe', $tipe)
                 ->where('id_referensi', $id_referensi)
                 ->where('berlaku_mulai', $berlaku_mulai)
                 ->delete('tb_assignment_shift');

        audit_log('DELETE', 'ShiftAssignment', "Group $tipe/$id_referensi/$berlaku_mulai");
        $this->session->set_flashdata('success', 'Jadwal mingguan berhasil dihapus');
        redirect('master/shift/assignment?tipe=' . $tipe);
    }

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

        $tipe         = $this->input->post('tipe');
        $id_referensi = (int) $this->input->post('id_referensi');
        $berlaku_mulai = $this->input->post('berlaku_mulai');

        if (!in_array($tipe, ['PEGAWAI', 'DIVISI'], TRUE) || $id_referensi <= 0 || empty($berlaku_mulai)) {
            echo json_encode(['success' => false, 'message' => 'Parameter tidak valid']);
            return;
        }

        $this->db->where('tipe', $tipe)
                 ->where('id_referensi', $id_referensi)
                 ->where('berlaku_mulai', $berlaku_mulai)
                 ->delete('tb_assignment_shift');

        audit_log('DELETE', 'ShiftAssignment', "Group $tipe/$id_referensi/$berlaku_mulai");
        echo json_encode(['success' => true, 'message' => 'Jadwal berhasil dihapus']);
    }

    // Endpoint AJAX: ambil daftar pegawai per divisi untuk dropdown assignment
    public function get_pegawai_by_divisi()
    {
        if (!$this->input->is_ajax_request()) {
            show_404();
        }
        $id_divisi = (int) $this->input->get('id_divisi');
        $list = $this->db
            ->select('id_pegawai, nip, nama_lengkap')
            ->where('id_divisi', $id_divisi)
            ->where('status_pegawai', 'AKTIF')
            ->order_by('nama_lengkap')
            ->get('tb_pegawai')->result();

        echo json_encode($list);
    }

    // ----------------------------------------------------------------
    // Helper
    // ----------------------------------------------------------------

    private function _get_assignment_list($tipe, $id_divisi = NULL)
    {
        if ($tipe === 'PEGAWAI') {
            $this->db->select('a.*, s.nama_shift, s.jam_masuk, s.jam_keluar,
                               p.nip, p.nama_lengkap, p.id_divisi AS id_divisi_pegawai, d.nama_divisi')
                     ->from('tb_assignment_shift a')
                     ->join('tb_shift s', 's.id_shift = a.id_shift', 'left')
                     ->join('tb_pegawai p', 'p.id_pegawai = a.id_referensi', 'left')
                     ->join('tb_divisi d', 'd.id_divisi = p.id_divisi', 'left')
                     ->where('a.tipe', 'PEGAWAI');
            if ($id_divisi) {
                $this->db->where('p.id_divisi', (int) $id_divisi);
            }
            $rows = $this->db->order_by('d.nama_divisi, p.nama_lengkap, a.berlaku_mulai DESC, a.hari_ke ASC')
                            ->get()->result();
        } else {
            $rows = $this->db->select('a.*, s.nama_shift, s.jam_masuk, s.jam_keluar, d.nama_divisi')
                            ->from('tb_assignment_shift a')
                            ->join('tb_shift s', 's.id_shift = a.id_shift', 'left')
                            ->join('tb_divisi d', 'd.id_divisi = a.id_referensi', 'left')
                            ->where('a.tipe', 'DIVISI')
                            ->order_by('d.nama_divisi, a.berlaku_mulai DESC, a.hari_ke ASC')
                            ->get()->result();
        }

        // Group rows by (id_referensi, berlaku_mulai) => satu baris per jadwal mingguan
        $grouped = [];
        foreach ($rows as $row) {
            $key = $row->id_referensi . '_' . $row->berlaku_mulai;
            if (!isset($grouped[$key])) {
                $grouped[$key] = (object) [
                    'tipe'           => $row->tipe,
                    'id_referensi'   => $row->id_referensi,
                    'berlaku_mulai'  => $row->berlaku_mulai,
                    'berlaku_selesai'=> $row->berlaku_selesai,
                    'keterangan'     => $row->keterangan,
                    'nama_divisi'    => $row->nama_divisi ?? '-',
                    'nip'            => $row->nip ?? '',
                    'nama_lengkap'   => $row->nama_lengkap ?? '',
                    'id_divisi'      => ($tipe === 'PEGAWAI') ? ($row->id_divisi_pegawai ?? 0) : $row->id_referensi,
                    'days'           => [],
                ];
            }
            $grouped[$key]->days[(int) $row->hari_ke] = (object) [
                'hari_ke'       => (int) $row->hari_ke,
                'is_hari_kerja' => (int) $row->is_hari_kerja,
                'id_shift'      => $row->id_shift,
                'nama_shift'    => $row->nama_shift ?? '',
                'jam_masuk'     => $row->jam_masuk ?? '',
                'jam_keluar'    => $row->jam_keluar ?? '',
            ];
        }

        return array_values($grouped);
    }
}
