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

class Warga extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        $this->load->model('Warga_model');
        $this->load->model('User_model');
        $this->load->model('KartuKeluarga_model');
        $this->load->library('form_validation');
    }

    public function index() {
        $filter = $this->input->get('filter'); // ambil ?filter=xxx

        $data['title']   = 'Data Warga';
        $data['filter']  = $filter;

        // Jika ada filter, ambil data sesuai filter
        if (!empty($filter)) {
            $data['warga'] = $this->Warga_model->get_all_filter($filter);
        } else {
            $data['warga'] = $this->Warga_model->get_all();
        }

        $data['statistik']                    = $this->Warga_model->get_statistik_dashboard();
        $data['statistik']['total_kk']        = $this->KartuKeluarga_model->count_all();
        $data['statistik']['total_meninggal'] = $this->Warga_model->count_meninggal();
        $data['warga_meninggal']              = $this->Warga_model->get_warga_meninggal();

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

    public function tambah() {
        $data['title']           = 'Tambah Warga';
        $data['status_hubungan'] = $this->Warga_model->get_status_hubungan_options();
        $data['status_warga']    = $this->Warga_model->get_status_warga_options();

        $this->form_validation->set_rules('nik',          'NIK',          'required|is_unique[warga.nik]');
        $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('warga/tambah', $data);
            $this->load->view('templates/footer');
        } else {
            $data_warga = [
                'nik'                 => $this->input->post('nik'),
                'no_kk'               => $this->input->post('no_kk'),
                'nama_lengkap'        => $this->input->post('nama_lengkap'),
                'tempat_lahir'        => $this->input->post('tempat_lahir'),
                'tanggal_lahir'       => $this->input->post('tanggal_lahir'),
                'jenis_kelamin'       => $this->input->post('jenis_kelamin'),
                'status_perkawinan'   => $this->input->post('status_perkawinan'),
                'pekerjaan'           => $this->input->post('pekerjaan'),
                'agama'               => $this->input->post('agama'),
                'status_hubungan'     => $this->input->post('status_hubungan'),
                'status_warga'        => $this->input->post('status_warga'),
                'keterangan_domisili' => $this->input->post('keterangan_domisili'),
                'status_meninggal'    => 0,
            ];
            $this->Warga_model->insert($data_warga);
            $this->User_model->log_activity($this->session->userdata('user_id'), 'create', 'Menambah data warga baru: ' . $this->input->post('nama_lengkap'));
            $this->session->set_flashdata('success', 'Data warga berhasil ditambahkan');
            redirect('warga');
        }
    }

    public function edit($id) {
        $data['title']           = 'Edit Warga';
        $data['warga']           = $this->Warga_model->get_by_id($id);
        $data['status_hubungan'] = $this->Warga_model->get_status_hubungan_options();
        $data['status_warga']    = $this->Warga_model->get_status_warga_options();

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

        $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('warga/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $data_warga = [
                'no_kk'               => $this->input->post('no_kk'),
                'nama_lengkap'        => $this->input->post('nama_lengkap'),
                'tempat_lahir'        => $this->input->post('tempat_lahir'),
                'tanggal_lahir'       => $this->input->post('tanggal_lahir'),
                'jenis_kelamin'       => $this->input->post('jenis_kelamin'),
                'status_perkawinan'   => $this->input->post('status_perkawinan'),
                'pekerjaan'           => $this->input->post('pekerjaan'),
                'agama'               => $this->input->post('agama'),
                'status_hubungan'     => $this->input->post('status_hubungan'),
                'status_warga'        => $this->input->post('status_warga'),
                'keterangan_domisili' => $this->input->post('keterangan_domisili'),
            ];
            $this->Warga_model->update($id, $data_warga);
            $this->User_model->log_activity($this->session->userdata('user_id'), 'update', 'Mengubah data warga: ' . $this->input->post('nama_lengkap'));
            $this->session->set_flashdata('success', 'Data warga berhasil diupdate');
            redirect('warga');
        }
    }

    public function statistik() {
        $data['title']     = 'Statistik Kependudukan';
        $data['warga']     = $this->Warga_model->get_all();
        $data['statistik'] = $this->Warga_model->get_statistik_dashboard();
        $data['statistik']['total_kk']        = $this->KartuKeluarga_model->count_all();
        $data['statistik']['total_meninggal'] = $this->Warga_model->count_meninggal();

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

    public function hapus($id) {
        $warga = $this->Warga_model->get_by_id($id);
        if ($warga) {
            $this->Warga_model->delete($id);
            $this->User_model->log_activity($this->session->userdata('user_id'), 'delete', 'Menghapus data warga: ' . $warga->nama_lengkap);
            $this->session->set_flashdata('success', 'Data warga berhasil dihapus');
        }
        redirect('warga');
    }

    // ════════════════════════════════════════════════════════════════
    // HALAMAN DAFTAR PEMILIH PEMILU
    // ════════════════════════════════════════════════════════════════
    public function pemilih() {
        $data['title']   = 'Data Pemilih Pemilu';
        $data['pemilih'] = $this->Warga_model->get_pemilih_pemilu();
        $data['stat']    = $this->Warga_model->get_statistik_pemilih();

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

    // ════════════════════════════════════════════════════════════════
    // EXPORT EXCEL DAFTAR PEMILIH
    // ════════════════════════════════════════════════════════════════
    public function export_pemilih() {
        $this->_check_admin_or_rt();

        $pemilih = $this->Warga_model->get_pemilih_pemilu();

        $autoload_paths = [
            FCPATH . 'vendor/autoload.php',
            APPPATH . 'vendor/autoload.php',
            realpath(APPPATH . '../../vendor/autoload.php'),
            dirname(APPPATH) . '/vendor/autoload.php',
        ];
        foreach ($autoload_paths as $path) {
            if ($path && file_exists($path)) { require_once $path; break; }
        }

        if (!class_exists('\PhpOffice\PhpSpreadsheet\Spreadsheet')) {
            $this->session->set_flashdata('error', 'Library PhpSpreadsheet tidak ditemukan. Jalankan: composer require phpoffice/phpspreadsheet');
            redirect('warga/pemilih');
            return;
        }

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Daftar Pemilih');

        $sheet->mergeCells('A1:L1');
        $sheet->setCellValue('A1', 'DAFTAR PEMILIH PEMILU — ' . strtoupper(date('d F Y')));
        $sheet->getStyle('A1')->applyFromArray([
            'font'      => ['bold'=>true, 'size'=>13, 'color'=>['rgb'=>'FFFFFF']],
            'fill'      => ['fillType'=>'solid', 'startColor'=>['rgb'=>'1D4ED8']],
            'alignment' => ['horizontal'=>'center', 'vertical'=>'center'],
        ]);
        $sheet->getRowDimension(1)->setRowHeight(28);

        $headers = ['No','NIK','Nama Lengkap','L/P','Tempat Lahir','Tgl Lahir','Umur','Kelompok Umur','Status Kawin','Domisili','No KK','Kepala KK'];
        foreach ($headers as $col => $h) {
            $cell = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col + 1) . '2';
            $sheet->setCellValue($cell, $h);
            $sheet->getStyle($cell)->applyFromArray([
                'font'      => ['bold'=>true, 'color'=>['rgb'=>'FFFFFF']],
                'fill'      => ['fillType'=>'solid', 'startColor'=>['rgb'=>'1E40AF']],
                'alignment' => ['horizontal'=>'center', 'vertical'=>'center'],
            ]);
        }
        $sheet->getRowDimension(2)->setRowHeight(20);

        $today = new DateTime();
        $row   = 3;
        $no    = 1;

        $kelompok_fn = function($umur) {
            if ($umur >= 17 && $umur <= 21) return 'Pemula (17-21)';
            if ($umur >= 22 && $umur <= 35) return 'Muda (22-35)';
            if ($umur >= 36 && $umur <= 55) return 'Dewasa (36-55)';
            if ($umur >= 56 && $umur <= 70) return 'Lansia (56-70)';
            return 'Tua (71+)';
        };

        $kawin_label = ['belum_kawin'=>'Belum Kawin','kawin'=>'Kawin','cerai_hidup'=>'Cerai Hidup','cerai_mati'=>'Cerai Mati'];
        $dom_label   = ['tetap'=>'Tetap','kost'=>'Kost','kontrak'=>'Kontrak','pendatang'=>'Pendatang','sementara'=>'Sementara'];

        foreach ($pemilih as $p) {
            $umur = 0;
            if (!empty($p->tanggal_lahir)) {
                $lahir = new DateTime($p->tanggal_lahir);
                $umur  = $today->diff($lahir)->y;
            }
            $cols = [
                $no++,
                $p->nik ?? '-',
                $p->nama_lengkap ?? '-',
                ($p->jenis_kelamin ?? '') === 'L' ? 'Laki-laki' : 'Perempuan',
                $p->tempat_lahir ?? '-',
                !empty($p->tanggal_lahir) ? date('d/m/Y', strtotime($p->tanggal_lahir)) : '-',
                $umur,
                $kelompok_fn($umur),
                $kawin_label[$p->status_perkawinan ?? ''] ?? ($p->status_perkawinan ?? '-'),
                $dom_label[$p->status_domisili ?? ''] ?? ($p->status_domisili ?? '-'),
                $p->no_kk ?? '-',
                $p->nama_kepala_kk ?? '-',
            ];
            foreach ($cols as $col => $val) {
                $cell = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col + 1) . $row;
                $sheet->setCellValue($cell, $val);
            }
            if ($row % 2 === 0) {
                $sheet->getStyle('A'.$row.':L'.$row)->applyFromArray([
                    'fill' => ['fillType'=>'solid', 'startColor'=>['rgb'=>'EFF6FF']],
                ]);
            }
            $row++;
        }

        foreach (range(1, 12) as $col) {
            $sheet->getColumnDimensionByColumn($col)->setAutoSize(true);
        }

        if ($row > 3) {
            $sheet->getStyle('A1:L'.($row-1))->applyFromArray([
                'borders' => ['allBorders' => ['borderStyle'=>'thin', 'color'=>['rgb'=>'DBEAFE']]],
            ]);
        }

        $sheet->freezePane('A3');

        if (ob_get_level()) ob_end_clean();
        $filename = 'daftar_pemilih_' . date('Ymd_His') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        header('Pragma: public');
        header('Expires: 0');

        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }

    // ════════════════════════════════════════════════════════════════
    // HELPER PRIVATE
    // ════════════════════════════════════════════════════════════════
    private function _check_admin_or_rt() {
        $role = $this->session->userdata('role');
        if (!in_array($role, ['admin', 'rt', 'ketua_rt', 'sekretaris'])) {
            $this->session->set_flashdata('error', 'Akses ditolak');
            redirect('warga');
        }
    }

    public function cetak_pemilih() {
        $this->_check_admin_or_rt();
        $data['pemilih'] = $this->Warga_model->get_pemilih_pemilu();
        $data['stat']    = $this->Warga_model->get_statistik_pemilih();
        $this->load->view('cetak/cetak_pemilih', $data);
    }

    public function ubah_role()
    {
        header('Content-Type: application/json');

        if ($this->session->userdata('role') !== 'admin') {
            echo json_encode(['status' => 'error', 'msg' => 'Akses ditolak']); return;
        }

        $user_id   = (int) $this->input->post('user_id');
        $role_baru = $this->security->xss_clean($this->input->post('role_baru'));
        $roles_valid = ['admin', 'ketua_rt', 'sekretaris', 'bendahara', 'warga'];

        if (!$user_id || !in_array($role_baru, $roles_valid)) {
            echo json_encode(['status' => 'error', 'msg' => 'Data tidak valid']); return;
        }

        if ($user_id == (int)$this->session->userdata('user_id')) {
            echo json_encode(['status' => 'error', 'msg' => 'Tidak dapat mengubah role akun sendiri']); return;
        }

        $user = $this->User_model->get_by_id($user_id);
        if (!$user) {
            echo json_encode(['status' => 'error', 'msg' => 'User tidak ditemukan']); return;
        }

        $role_lama = $user->role;
        $ok = $this->User_model->update($user_id, [
            'role'       => $role_baru,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        if ($ok) {
            $this->User_model->log_activity(
                $this->session->userdata('user_id'),
                'ubah_role',
                "Ubah role '{$user->username}' dari '{$role_lama}' jadi '{$role_baru}'"
            );
            echo json_encode([
                'status'    => 'ok',
                'msg'       => "Role diubah: {$role_lama} → {$role_baru}",
                'role_baru' => $role_baru,
                'role_lama' => $role_lama,
            ]);
        } else {
            echo json_encode(['status' => 'error', 'msg' => 'Gagal mengubah role']);
        }
    }

    public function buat_akun() {
        header('Content-Type: application/json');

        if ($this->session->userdata('role') !== 'admin') {
            echo json_encode(['status' => 'error', 'msg' => 'Akses ditolak']); return;
        }

        $warga_id = $this->input->post('warga_id');
        $warga = $this->Warga_model->get_by_id($warga_id);

        if (!$warga) {
            echo json_encode(['status' => 'error', 'msg' => 'Data warga tidak ditemukan']); return;
        }

        if (empty($warga->nik)) {
            echo json_encode(['status' => 'error', 'msg' => 'Warga tidak memiliki NIK, harap isi NIK terlebih dahulu']); return;
        }

        if ($this->User_model->is_username_exists($warga->nik)) {
             echo json_encode(['status' => 'error', 'msg' => 'Username (NIK) sudah terdaftar di sistem']); return;
        }

        $user_data = [
            'username' => $warga->nik,
            'password' => password_hash($warga->nik, PASSWORD_DEFAULT),
            'role' => 'warga',
            'status' => 'aktif',
            'warga_id' => $warga->id,
            'nama_lengkap' => $warga->nama_lengkap,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $user_id = $this->User_model->insert($user_data);

        if ($user_id) {
            $this->Warga_model->update($warga->id, ['user_id' => $user_id]);
            $this->User_model->log_activity(
                $this->session->userdata('user_id'),
                'buat_akun',
                "Membuat akun otomatis untuk warga: {$warga->nama_lengkap}"
            );
            echo json_encode(['status' => 'ok', 'msg' => 'Akun berhasil dibuat. Username dan Password sesuai NIK.']);
        } else {
            echo json_encode(['status' => 'error', 'msg' => 'Gagal membuat akun']);
        }
    }

    public function reset_password() {
        header('Content-Type: application/json');

        if ($this->session->userdata('role') !== 'admin') {
            echo json_encode(['status' => 'error', 'msg' => 'Akses ditolak']); return;
        }

        $user_id = $this->input->post('user_id');
        $nik = $this->input->post('nik');

        if (empty($nik)) {
            echo json_encode(['status' => 'error', 'msg' => 'Data NIK tidak valid, tidak bisa reset password']); return;
        }

        $user = $this->User_model->get_by_id($user_id);
        if (!$user) {
            echo json_encode(['status' => 'error', 'msg' => 'Akun tidak ditemukan']); return;
        }

        $ok = $this->User_model->update_password($user_id, $nik);
        if ($ok) {
            $this->User_model->log_activity(
                $this->session->userdata('user_id'),
                'reset_password',
                "Mereset password user: {$user->username} menjadi default (NIK)"
            );
            echo json_encode(['status' => 'ok', 'msg' => 'Password berhasil direset ke NIK default.']);
        } else {
            echo json_encode(['status' => 'error', 'msg' => 'Gagal mereset password']);
        }
    }

    // ================================================================
    // AJAX: Kirim Ucapan Selamat Ulang Tahun via WAHA
    // POST: warga/kirim_ucapan_ultah
    // Body JSON: { warga_id: 123 } atau kosong (kirim semua ultah hari ini)
    // ================================================================
    public function kirim_ucapan_ultah() {
        if ($this->session->userdata('role') !== 'admin') {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'Akses ditolak']));
        }

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

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

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

        // Cari warga yang ulang tahun hari ini dengan no_hp
        $warga_id = $this->input->post('warga_id');

        if ($warga_id) {
            // Kirim ke satu warga spesifik
            $list = $this->db->select('w.id, w.nama_lengkap, u.no_hp, w.tanggal_lahir')
                ->from('warga w')
                ->join('users u', 'u.id = w.user_id', 'left')
                ->where('w.id', (int)$warga_id)
                ->where('w.status_meninggal', 0)
                ->get()->result();
        } else {
            // Kirim ke semua warga yang ultah hari ini
            $list = $this->db->select('w.id, w.nama_lengkap, u.no_hp, w.tanggal_lahir')
                ->from('warga w')
                ->join('users u', 'u.id = w.user_id', 'left')
                ->where('DAY(w.tanggal_lahir)', date('j'))
                ->where('MONTH(w.tanggal_lahir)', date('n'))
                ->where('w.status_meninggal', 0)
                ->where('u.no_hp IS NOT NULL')
                ->where('u.no_hp !=', '')
                ->get()->result();
        }

        if (empty($list)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'ok', 'msg' => 'Tidak ada warga yang berulang tahun hari ini (atau tidak ada nomor HP).', 'kirim' => 0]));
        }

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

        foreach ($list as $w) {
            if (empty($w->no_hp)) {
                $gagal++;
                $errors[] = $w->nama_lengkap . ': No HP tidak tersedia';
                continue;
            }

            $umur = '';
            if (!empty($w->tanggal_lahir) && $w->tanggal_lahir != '0000-00-00') {
                $birthDate = strtotime($w->tanggal_lahir);
                if ($birthDate) {
                    $umur = date('Y') - date('Y', $birthDate);
                }
            }

            $pesan = "🎂 *Selamat Ulang Tahun!* 🎂\n\n"
                   . "Assalamu'alaikum Bpk/Ibu *{$w->nama_lengkap}*,\n\n"
                   . "Seluruh warga dan pengurus *{$nama_rt}* mengucapkan:\n\n"
                   . "🎉 *SELAMAT ULANG TAHUN* 🎉\n"
                   . ($umur ? "Semoga di usia ke-{$umur} ini selalu diberikan kesehatan, keberkahan, dan kebahagiaan. Aamiin.\n\n" : "Semoga selalu diberikan kesehatan, keberkahan, dan kebahagiaan. Aamiin.\n\n")
                   . "_Salam hangat dari Pengurus {$nama_rt}_ 🏠";

            $result = $this->waha_lib->send($w->no_hp, $pesan);
            if ($result['success']) {
                $sukses++;
            } else {
                $gagal++;
                $errors[] = $w->nama_lengkap . ': ' . $result['message'];
            }
        }

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status' => 'ok',
                'msg'    => "Selesai. Berhasil: {$sukses}, Gagal: {$gagal}.",
                'kirim'  => $sukses,
                'gagal'  => $gagal,
                'errors' => $errors,
            ]));
    }

}
