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

class Pengumuman extends CI_Controller {  // PASTIKAN CI_Controller, BUKAN CI_Model

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if(!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        $this->load->model('Pengumuman_model');
        $this->load->library('form_validation');
        $this->load->helper(array('form', 'url'));
    }

    // Cek apakah user adalah admin/RT
    private function _check_admin_access() {
        $role = $this->session->userdata('role');
        if($role != 'admin' && $role != 'rt') {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses untuk melakukan tindakan ini');
            redirect('pengumuman');
        }
    }

    public function index() {
        $data['title'] = 'Pengumuman';
        $role = $this->session->userdata('role');
        
        // Ambil filter dari query string
        $kategori = $this->input->get('kategori');
        $bulan = $this->input->get('bulan');
        $tahun = $this->input->get('tahun');
        
        // Admin/RT lihat semua, warga hanya yang publish dan sesuai role
        if($role == 'admin' || $role == 'rt') {
            $data['pengumuman'] = $this->Pengumuman_model->get_all($kategori, $bulan, $tahun);
            $data['is_admin'] = true;
        } else {
            $data['pengumuman'] = $this->Pengumuman_model->get_for_warga($role, $kategori, $bulan, $tahun);
            $data['is_admin'] = false;
        }
        
        // Data untuk filter
        $data['kategori_filter'] = $kategori;
        $data['bulan_filter'] = $bulan;
        $data['tahun_filter'] = $tahun;
        $data['tahun_list'] = $this->Pengumuman_model->get_available_years();
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('pengumuman/index', $data);
        $this->load->view('templates/footer');
    }

    public function detail($id) {
        $data['title'] = 'Detail Pengumuman';
        $data['pengumuman'] = $this->Pengumuman_model->get_by_id($id);
        
        if(!$data['pengumuman']) {
            show_404();
        }
        
        // Jika warga, cek akses
        $role = $this->session->userdata('role');
        if($role == 'warga') {
            // Cek apakah pengumuman untuk warga atau semua
            if($data['pengumuman']->untuk_role != 'semua' && $data['pengumuman']->untuk_role != 'warga') {
                $this->session->set_flashdata('error', 'Anda tidak memiliki akses ke pengumuman ini');
                redirect('pengumuman');
            }
            // Cek status publish
            if($data['pengumuman']->status != 'publish') {
                $this->session->set_flashdata('error', 'Pengumuman tidak tersedia');
                redirect('pengumuman');
            }
        }
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('pengumuman/detail', $data);
        $this->load->view('templates/footer');
    }

    public function tambah() {
        $this->_check_admin_access();
        
        $data['title'] = 'Tambah Pengumuman';

        $this->form_validation->set_rules('judul', 'Judul', 'required|max_length[200]');
        $this->form_validation->set_rules('isi', 'Isi', 'required');
        $this->form_validation->set_rules('kategori', 'Kategori', 'required');
        $this->form_validation->set_rules('tanggal_publish', 'Tanggal Publish', 'required');

        if($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('pengumuman/tambah', $data);
            $this->load->view('templates/footer');
        } else {
            // Upload lampiran jika ada
            $lampiran = '';
            if(!empty($_FILES['lampiran']['name'])) {
                $config['upload_path'] = './uploads/pengumuman/';
                $config['allowed_types'] = 'pdf|doc|docx|jpg|jpeg|png';
                $config['max_size'] = 5120; // 5MB
                $config['file_name'] = 'lampiran_'.time().'_'.str_replace(' ', '_', $_FILES['lampiran']['name']);
                
                // Buat folder jika belum ada
                if(!is_dir($config['upload_path'])) {
                    mkdir($config['upload_path'], 0777, true);
                }
                
                $this->load->library('upload', $config);
                
                if($this->upload->do_upload('lampiran')) {
                    $lampiran = $this->upload->data('file_name');
                } else {
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect('pengumuman/tambah');
                }
            }

            $data_pengumuman = array(
                'judul' => $this->input->post('judul'),
                'isi' => $this->input->post('isi'),
                'kategori' => $this->input->post('kategori'),
                'untuk_role' => $this->input->post('untuk_role') ? $this->input->post('untuk_role') : 'semua',
                'lampiran' => $lampiran,
                'tanggal_publish' => $this->input->post('tanggal_publish'),
                'tanggal_expired' => $this->input->post('tanggal_expired') ? $this->input->post('tanggal_expired') : null,
                'status' => $this->input->post('status'),
                'dibuat_oleh' => $this->session->userdata('user_id'),
                'created_at' => date('Y-m-d H:i:s')
            );

            $this->Pengumuman_model->insert($data_pengumuman);
            $this->session->set_flashdata('success', 'Pengumuman berhasil ditambahkan');
            redirect('pengumuman');
        }
    }

    public function edit($id) {
        $this->_check_admin_access();
        
        $data['title'] = 'Edit Pengumuman';
        $data['pengumuman'] = $this->Pengumuman_model->get_by_id($id);

        if(!$data['pengumuman']) {
            show_404();
        }

        $this->form_validation->set_rules('judul', 'Judul', 'required|max_length[200]');
        $this->form_validation->set_rules('isi', 'Isi', 'required');
        $this->form_validation->set_rules('kategori', 'Kategori', 'required');

        if($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('pengumuman/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $data_pengumuman = array(
                'judul' => $this->input->post('judul'),
                'isi' => $this->input->post('isi'),
                'kategori' => $this->input->post('kategori'),
                'untuk_role' => $this->input->post('untuk_role') ? $this->input->post('untuk_role') : 'semua',
                'tanggal_publish' => $this->input->post('tanggal_publish'),
                'tanggal_expired' => $this->input->post('tanggal_expired') ? $this->input->post('tanggal_expired') : null,
                'status' => $this->input->post('status'),
                'updated_at' => date('Y-m-d H:i:s')
            );

            // Handle upload lampiran baru
            if(!empty($_FILES['lampiran']['name'])) {
                $config['upload_path'] = './uploads/pengumuman/';
                $config['allowed_types'] = 'pdf|doc|docx|jpg|jpeg|png';
                $config['max_size'] = 5120;
                $config['file_name'] = 'lampiran_'.time().'_'.str_replace(' ', '_', $_FILES['lampiran']['name']);
                
                if(!is_dir($config['upload_path'])) {
                    mkdir($config['upload_path'], 0777, true);
                }
                
                $this->load->library('upload', $config);
                
                if($this->upload->do_upload('lampiran')) {
                    // Hapus file lama jika ada
                    if($data['pengumuman']->lampiran && file_exists('./uploads/pengumuman/'.$data['pengumuman']->lampiran)) {
                        unlink('./uploads/pengumuman/'.$data['pengumuman']->lampiran);
                    }
                    $data_pengumuman['lampiran'] = $this->upload->data('file_name');
                }
            }

            $this->Pengumuman_model->update($id, $data_pengumuman);
            $this->session->set_flashdata('success', 'Pengumuman berhasil diupdate');
            redirect('pengumuman');
        }
    }

    public function hapus($id) {
        $this->_check_admin_access();
        
        $pengumuman = $this->Pengumuman_model->get_by_id($id);
        
        // Hapus file lampiran jika ada
        if($pengumuman && $pengumuman->lampiran) {
            if(file_exists('./uploads/pengumuman/'.$pengumuman->lampiran)) {
                unlink('./uploads/pengumuman/'.$pengumuman->lampiran);
            }
        }
        
        $this->Pengumuman_model->delete($id);
        $this->session->set_flashdata('success', 'Pengumuman berhasil dihapus');
        redirect('pengumuman');
    }

    public function download_lampiran($id) {
        $pengumuman = $this->Pengumuman_model->get_by_id($id);
        
        if(!$pengumuman || !$pengumuman->lampiran) {
            show_404();
        }
        
        $file_path = './uploads/pengumuman/'.$pengumuman->lampiran;
        
        if(file_exists($file_path)) {
            $this->load->helper('download');
            force_download($file_path, NULL);
        } else {
            show_404();
        }
    }

    // ================================================================
    // AJAX: Sebar Pengumuman via WAHA WhatsApp
    // POST: pengumuman/sebar_wa
    // Body form: pengumuman_id=123  (atau kirim semua yang aktif hari ini)
    // ================================================================
    public function sebar_wa() {
        header('Content-Type: application/json');
        $this->_check_admin_access();

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'msg' => 'Invalid request.']);
            return;
        }

        $this->load->library('waha_lib');

        if (!$this->waha_lib->is_enabled()) {
            echo json_encode(['status' => 'error', 'msg' => 'WAHA belum diaktifkan. Atur di menu Pengaturan → tab WhatsApp.']);
            return;
        }

        $pengumuman_id = (int)$this->input->post('pengumuman_id');
        if (!$pengumuman_id) {
            echo json_encode(['status' => 'error', 'msg' => 'ID pengumuman tidak valid.']);
            return;
        }

        $pengumuman = $this->Pengumuman_model->get_by_id($pengumuman_id);
        if (!$pengumuman) {
            echo json_encode(['status' => 'error', 'msg' => 'Pengumuman tidak ditemukan.']);
            return;
        }

        $this->load->model('Pengaturan_model');
        $p = $this->Pengaturan_model->get();
        $nama_rt = trim(($p->nama_rt ?? 'RT') . ' ' . ($p->nama_rw ?? ''));

        // Ambil semua warga yang punya nomor HP
        $target_role = $pengumuman->untuk_role ?? 'semua';

        $this->db->select('u.no_hp, u.nama_lengkap')
                 ->from('users u')
                 ->join('warga w', 'w.user_id = u.id', 'left')
                 ->where('u.no_hp IS NOT NULL')
                 ->where('u.no_hp !=', '')
                 ->where('u.status', 'aktif')
                 ->where('(w.status_meninggal IS NULL OR w.status_meninggal = 0)');

        if ($target_role !== 'semua') {
            $this->db->where('u.role', $target_role);
        }

        $warga_list = $this->db->get()->result();

        if (empty($warga_list)) {
            echo json_encode(['status' => 'ok', 'msg' => 'Tidak ada warga dengan nomor HP terdaftar.', 'kirim' => 0]);
            return;
        }

        $tgl_publish = !empty($pengumuman->tanggal_publish)
            ? date('d/m/Y', strtotime($pengumuman->tanggal_publish))
            : date('d/m/Y');

        $pesan_template = "📢 *PENGUMUMAN {$nama_rt}*\n"
                        . "━━━━━━━━━━━━━━━━━━━\n"
                        . "*{$pengumuman->judul}*\n\n"
                        . strip_tags(html_entity_decode($pengumuman->isi)) . "\n\n"
                        . "📅 _{$tgl_publish}_\n"
                        . "_Pengurus {$nama_rt}_";

        // Potong isi jika terlalu panjang
        if (mb_strlen($pesan_template) > 1000) {
            $isi_pendek = mb_substr(strip_tags(html_entity_decode($pengumuman->isi)), 0, 400) . '...';
            $pesan_template = "📢 *PENGUMUMAN {$nama_rt}*\n"
                            . "━━━━━━━━━━━━━━━━━━━\n"
                            . "*{$pengumuman->judul}*\n\n"
                            . $isi_pendek . "\n\n"
                            . "📅 _{$tgl_publish}_\n"
                            . "_Pengurus {$nama_rt}_";
        }

        $sukses = 0;
        $gagal  = 0;
        $errors = [];

        foreach ($warga_list as $w) {
            $result = $this->waha_lib->send($w->no_hp, $pesan_template);
            if ($result['success']) {
                $sukses++;
            } else {
                $gagal++;
                $errors[] = ($w->nama_lengkap ?? $w->no_hp) . ': ' . $result['message'];
                // Stop jika error fatal (bukan nomor invalid)
                if ($sukses === 0 && $gagal >= 2) break;
            }
            // Jeda kecil antar pengiriman agar tidak flood
            usleep(300000); // 0.3 detik
        }

        echo json_encode([
            'status' => 'ok',
            'msg'    => "Selesai. Terkirim: {$sukses}, Gagal: {$gagal} dari " . count($warga_list) . " warga.",
            'kirim'  => $sukses,
            'gagal'  => $gagal,
            'errors' => array_slice($errors, 0, 5), // max 5 error ditampilkan
        ]);
    }
}
