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

/**
 * @property CI_Db $db
 * @property CI_Session $session
 * @property CI_Form_validation $form_validation
 * @property CI_Input $input
 * @property CI_Berita_model $berita_model
 * @property CI_Upload $upload
 */

class Berita extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('berita_model');
        is_logged_in();
    }

    public function index()
    {
        $data['title'] = 'Berita';
        $data['berita'] = $this->berita_model->get_data('tb_berita')->result();
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();

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

    public function tambah()
    {
        $data['title'] = 'Tambah Berita';
        $data['berita'] = $this->berita_model->get_data('tb_berita')->result();
        $data['admin'] = $this->db->get_where('admin', ['email' => $this->session->userdata('email')])->row_array();

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

    public function tambah_aksi()
    {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->tambah();
        } else {
            // Konfigurasi upload
            $config['upload_path']   = './assets/img/berita/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['max_size']      = 2048; // 2MB

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('gambar')) {
                // Jika upload gagal
                $this->session->set_flashdata('pesan', '<div class="alert alert-danger">Gagal mengunggah gambar!</div>');
                redirect('berita/tambah');
            } else {
                $gambar = $this->upload->data('file_name');
                $tanggal_input = $this->input->post('tanggal');
                $tanggal_formatted = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $tanggal_input)));
                $data = array(
                    'gambar'    => $gambar,
                    'judul'     => $this->input->post('judul'),
                    'deskripsi' => $this->input->post('deskripsi'),
                    'tanggal'   => $tanggal_formatted
                );

                $this->berita_model->insert_data($data, 'tb_berita');

                $this->load->library('Notif');
                $notif = new Notif();

                $title = 'Nufaku - Berita Terkini';
                $body = $this->input->post('judul');

                $host = $_SERVER['HTTP_HOST'];

                if (strpos($host, 'localhost') !== false || strpos($host, '127.0.0.1') !== false) {
                    $host = '192.168.0.80:8080'; // Ganti dengan IP kamu
                }

                $gambar_url = 'http://' . $host . '/admin-nufa/assets/img/berita/' . $gambar;

                $dataPayload = [
                    'type' => 'berita',
                    'judul' => $this->input->post('judul'),
                    'gambar' => $gambar_url,
                    'tanggal' => $tanggal_formatted,
                    'deskripsi' => $this->input->post('deskripsi'),
                    'from_notif' => 'true'
                ];


                $tokens = $this->db->get('fcm_tokens')->result();

                foreach ($tokens as $row) {
                    $token = $row->token;
                    if (!empty($token)) {
                        $response = $notif->send($token, $title, $body, $dataPayload);
                        log_message('debug', 'RESPON FCM: ' . print_r($response, true));
                    }
                }

                $this->session->set_flashdata('pesan', '<div class="alert alert-success alert-dismissible fade show" role="alert">
            Data berhasil ditambahkan!
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span></button></div>');
                redirect('berita');
            }
        }
    }


    public function edit($id_berita)
    {
        $this->form_validation->set_rules('judul', 'Judul', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('deskripsi', 'Deskripsi', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('tanggal', 'Tanggal', 'required', array(
            'required' => '%s harus diisi!!'
        ));

        if ($this->form_validation->run() == FALSE) {
            $this->index();
        } else {
            $judul     = $this->input->post('judul');
            $deskripsi = $this->input->post('deskripsi');
            $tanggal_input = $this->input->post('tanggal');
            $tanggal_formatted = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $tanggal_input)));
            // Ambil gambar lama, bahkan jika tidak upload gambar baru
            $berita_lama = $this->berita_model->get_data_by_id($id_berita);
            $gambar_lama = $berita_lama ? $berita_lama->gambar : '';
            $upload_gambar = $_FILES['gambar']['name'];

            if ($upload_gambar) {
                $config['upload_path']   = 'assets/img/berita/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                $config['max_size']      = 2048;
                $config['encrypt_name']  = TRUE;

                $this->load->library('upload', $config);

                if ($this->upload->do_upload('gambar')) {
                    // Ambil gambar lama
                    $berita_lama = $this->berita_model->get_data_by_id($id_berita); // kamu harus buat fungsi ini kalau belum ada
                    $gambar_lama = $berita_lama->gambar;

                    // Hapus gambar lama jika bukan default
                    if ($gambar_lama && file_exists(FCPATH . 'assets/img/berita/' . $gambar_lama)) {
                        unlink(FCPATH . 'assets/img/berita/' . $gambar_lama);
                    }

                    // Simpan nama gambar baru
                    $gambar_baru = $this->upload->data('file_name');
                } else {
                    $this->session->set_flashdata('pesan', '<div class="alert alert-danger">' . $this->upload->display_errors() . '</div>');
                    redirect('berita');
                }
            }

            // Data array
            $data = array(
                'id_berita' => $id_berita,
                'judul'     => $judul,
                'deskripsi' => $deskripsi,
                'tanggal'   => $tanggal_formatted,
            );

            // Jika upload gambar baru, tambahkan ke data
            if (!empty($gambar_baru)) {
                $data['gambar'] = $gambar_baru;
            }

            $this->berita_model->update_data($data, 'tb_berita');

            $this->load->library('Notif');
            $notif = new Notif();

            $title = 'Nufaku - Pembaruan Berita';
            $body = $this->input->post('judul');

            $gambar = !empty($gambar_baru) ? $gambar_baru : $gambar_lama;

            // Dapatkan host
            $host = $_SERVER['HTTP_HOST'];

            // Jika localhost, ganti ke IP lokal kamu (ganti dengan IP sesuai hasil ipconfig)
            $host = $_SERVER['HTTP_HOST']; // bisa jadi 'localhost:8080'

            if (strpos($host, 'localhost') !== false || strpos($host, '127.0.0.1') !== false) {
                $host = '192.168.0.80:8080'; // Ganti dengan IP kamu
            }

            // Buat URL gambar yang bisa diakses Android
            $gambar_url = 'http://' . $host . '/admin-nufa/assets/img/berita/' . $gambar;

            // Payload untuk notifikasi
            $dataPayload = [
                'type' => 'berita',
                'judul' => $judul,
                'gambar' => $gambar_url,
                'tanggal' => $tanggal_formatted,
                'deskripsi' => $deskripsi,
                'from_notif' => 'true'
            ];

            log_message('debug', 'URL GAMBAR: ' . $gambar_url);

            $tokens = $this->db->get('fcm_tokens')->result();

            foreach ($tokens as $row) {
                $token = $row->token;
                if (!empty($token)) {
                    $response = $notif->send($token, $title, $body, $dataPayload);
                    log_message('debug', 'RESPON FCM: ' . print_r($response, true));
                }
            }

            $this->session->set_flashdata('pesan', '<div class="alert alert-success alert-dismissible fade show" role="alert">
                Data berhasil diubah! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span>
                </button></div>');
            redirect('berita');
        }
    }

    public function view($id_berita)
    {
        // Load model jika belum diload
        $this->load->model('berita_model');

        // Ambil data wali santri berdasarkan id_santri dari model
        $data['berita'] = $this->berita_model->get_berita_by_id($id_berita);

        // Periksa apakah data ditemukan
        if ($data['berita']) {
            // Kirim data ke view untuk ditampilkan dalam modal
            $this->load->view('berita', $data);
        } else {
            // Jika data tidak ditemukan, redirect ke halaman utama dengan pesan error
            $this->session->set_flashdata('pesan', 'Berita tidak ditemukan');
            redirect('berita');  // Ubah sesuai route halaman utama Anda
        }
    }

    public function _rules()
    {
        $this->form_validation->set_rules('judul', 'Judul', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('deskripsi', 'Deskripsi', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        $this->form_validation->set_rules('tanggal', 'Tanggal', 'required', array(
            'required' => '%s harus diisi!!'
        ));
        // Validasi manual untuk file
        if (empty($_FILES['gambar']['name'])) {
            $this->form_validation->set_rules('gambar', 'Gambar', 'required', array(
                'required' => '%s harus diisi!!'
            ));
        }
    }

    public function delete($id)
    {
        $where = array('id_berita' => $id);

        $this->berita_model->delete($where, 'tb_berita');
        $this->session->set_flashdata('pesan', '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                Data berhasil dihapus! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span>
                </button></div>');
        redirect('berita');
    }
}
