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

class Notulen extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('authorization');
        $this->load->library('session');
        $this->load->model('Notulen_model');
        $this->load->model('Warga_model');
        check_login();
    }

    // ─────────────────────────────────────────────
    // INDEX — admin & warga boleh
    // ─────────────────────────────────────────────
    public function index() {
        $filters = [];
        if ($this->input->get('status'))  $filters['status']  = $this->input->get('status');
        if ($this->input->get('tim'))     $filters['tim']     = $this->input->get('tim');
        if ($this->input->get('dari'))    $filters['dari']    = $this->input->get('dari');
        if ($this->input->get('sampai'))  $filters['sampai']  = $this->input->get('sampai');
        if ($this->input->get('q'))       $filters['q']       = $this->input->get('q');

        $data['title']     = 'Notulen Rapat';
        $data['notulen']   = $this->Notulen_model->get_all($filters);
        $data['statistik'] = $this->Notulen_model->get_statistik();

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('notulen/index', $data);
        $this->load->view('templates/footer');
    }

    // ─────────────────────────────────────────────
    // DETAIL — admin & warga boleh
    // ─────────────────────────────────────────────
    public function detail($id) {
        $data['title']   = 'Detail Notulen';
        $data['n']       = $this->Notulen_model->get_by_id($id);
        $data['peserta'] = $this->Notulen_model->get_peserta($id);
        $data['poin']    = $this->Notulen_model->get_poin($id);

        if (!$data['n']) {
            $this->session->set_flashdata('error', 'Notulen tidak ditemukan!');
            redirect('notulen');
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('notulen/detail', $data);
        $this->load->view('templates/footer');
    }

    // ─────────────────────────────────────────────
    // TAMBAH — hanya admin
    // ─────────────────────────────────────────────
    public function tambah() {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses!');
            redirect('notulen');
        }

        $data['title'] = 'Tambah Notulen';
        $data['warga'] = $this->Warga_model->get_all();

        if ($this->input->post()) {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('judul_rapat', 'Judul Rapat', 'required|trim');
            $this->form_validation->set_rules('tanggal',     'Tanggal',     'required');
            $this->form_validation->set_rules('tim',         'Tim/Proyek',  'required');
            $this->form_validation->set_rules('moderator',   'Moderator',   'required|trim');
            $this->form_validation->set_rules('notulis',     'Notulis',     'required|trim');

            if ($this->form_validation->run()) {
                $notulen_data = [
                    'judul_rapat'   => $this->input->post('judul_rapat'),
                    'tanggal'       => $this->input->post('tanggal'),
                    'waktu_mulai'   => $this->input->post('waktu_mulai')   ?: null,
                    'waktu_selesai' => $this->input->post('waktu_selesai') ?: null,
                    'tempat'        => $this->input->post('tempat'),
                    'tim'           => $this->input->post('tim'),
                    'moderator'     => $this->input->post('moderator'),
                    'notulis'       => $this->input->post('notulis'),
                    'catatan'       => $this->input->post('catatan'),
                    'status'        => $this->input->post('status') ?: 'draft',
                    'created_by'    => $this->session->userdata('user_id'),
                ];

                if ($this->Notulen_model->insert($notulen_data)) {
                    $notulen_id = $this->db->insert_id();
                    $this->_simpan_peserta($notulen_id);
                    $this->_simpan_poin($notulen_id);
                    $this->session->set_flashdata('success', 'Notulen berhasil ditambahkan!');
                    redirect('notulen');
                } else {
                    $this->session->set_flashdata('error', 'Gagal menyimpan notulen!');
                }
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('notulen/form', $data);
        $this->load->view('templates/footer');
    }

    // ─────────────────────────────────────────────
    // EDIT — hanya admin
    // ─────────────────────────────────────────────
    public function edit($id) {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses!');
            redirect('notulen');
        }

        $data['title']   = 'Edit Notulen';
        $data['n']       = $this->Notulen_model->get_by_id($id);
        $data['warga']   = $this->Warga_model->get_all();
        $data['peserta'] = $this->Notulen_model->get_peserta($id);
        $data['poin']    = $this->Notulen_model->get_poin($id);

        if (!$data['n']) {
            $this->session->set_flashdata('error', 'Notulen tidak ditemukan!');
            redirect('notulen');
        }

        if ($this->input->post()) {
            $update_data = [
                'judul_rapat'   => $this->input->post('judul_rapat'),
                'tanggal'       => $this->input->post('tanggal'),
                'waktu_mulai'   => $this->input->post('waktu_mulai')   ?: null,
                'waktu_selesai' => $this->input->post('waktu_selesai') ?: null,
                'tempat'        => $this->input->post('tempat'),
                'tim'           => $this->input->post('tim'),
                'moderator'     => $this->input->post('moderator'),
                'notulis'       => $this->input->post('notulis'),
                'catatan'       => $this->input->post('catatan'),
                'status'        => $this->input->post('status'),
            ];

            if ($this->Notulen_model->update($id, $update_data)) {
                $this->Notulen_model->delete_peserta($id);
                $this->Notulen_model->delete_poin($id);
                $this->_simpan_peserta($id);
                $this->_simpan_poin($id);
                $this->session->set_flashdata('success', 'Notulen berhasil diupdate!');
                redirect('notulen/detail/' . $id);
            } else {
                $this->session->set_flashdata('error', 'Gagal mengupdate notulen!');
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('notulen/form', $data);
        $this->load->view('templates/footer');
    }

    // ─────────────────────────────────────────────
    // HAPUS — hanya admin
    // ─────────────────────────────────────────────
    public function hapus($id) {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses!');
            redirect('notulen');
        }

        if ($this->Notulen_model->delete($id)) {
            $this->session->set_flashdata('success', 'Notulen berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus notulen!');
        }
        redirect('notulen');
    }

    // ─────────────────────────────────────────────
    // UPDATE STATUS AJAX — hanya admin
    // ─────────────────────────────────────────────
    public function update_status($id) {
        if (is_warga()) {
            echo json_encode(['success' => false, 'message' => 'Akses ditolak']);
            return;
        }

        $status  = $this->input->post('status');
        $allowed = ['draft', 'menunggu', 'final'];

        if (!in_array($status, $allowed)) {
            echo json_encode(['success' => false, 'message' => 'Status tidak valid']);
            return;
        }

        if ($this->Notulen_model->update($id, ['status' => $status])) {
            echo json_encode(['success' => true, 'message' => 'Status berhasil diubah']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal mengubah status']);
        }
    }

    // ─────────────────────────────────────────────
    // CETAK — admin & warga boleh (menggantikan export_pdf)
    // ─────────────────────────────────────────────
    public function cetak($id) {
        $n       = $this->Notulen_model->get_by_id($id);
        $peserta = $this->Notulen_model->get_peserta($id);
        $poin    = $this->Notulen_model->get_poin($id);

        if (!$n) {
            $this->session->set_flashdata('error', 'Notulen tidak ditemukan!');
            redirect('notulen');
        }

        $data['n']       = $n;
        $data['peserta'] = $peserta;
        $data['poin']    = $poin;

        // Load HANYA view ini saja — tanpa header/sidebar/footer template
        $this->load->view('cetak/cetak_notulen', $data);
    }

    // ─────────────────────────────────────────────
    // HELPERS
    // ─────────────────────────────────────────────
    private function _simpan_peserta($notulen_id) {
        $nama      = $this->input->post('peserta_nama');
        $jabatan   = $this->input->post('peserta_jabatan');
        $kehadiran = $this->input->post('peserta_kehadiran');

        if (!empty($nama) && is_array($nama)) {
            foreach ($nama as $i => $nm) {
                if (trim($nm) !== '') {
                    $this->Notulen_model->insert_peserta([
                        'notulen_id' => $notulen_id,
                        'nama'       => trim($nm),
                        'jabatan'    => isset($jabatan[$i])   ? trim($jabatan[$i]) : '',
                        'kehadiran'  => isset($kehadiran[$i]) ? $kehadiran[$i]     : 'hadir',
                        'urutan'     => $i + 1,
                    ]);
                }
            }
        }
    }

    private function _simpan_poin($notulen_id) {
        $teks      = $this->input->post('poin_teks');
        $prioritas = $this->input->post('poin_prioritas');

        if (!empty($teks) && is_array($teks)) {
            foreach ($teks as $i => $t) {
                if (trim($t) !== '') {
                    $this->Notulen_model->insert_poin([
                        'notulen_id' => $notulen_id,
                        'teks'       => trim($t),
                        'prioritas'  => isset($prioritas[$i]) ? $prioritas[$i] : 'sedang',
                        'urutan'     => $i + 1,
                    ]);
                }
            }
        }
    }
}