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

class Inbox extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->Model_squrity->getsqurity();
        $this->Model_squrity->cekmenu('inbox');
        $data['title'] = 'arifahpulsa';
        $data['halaman'] = 'Inbox';

        $this->template->load('includes/header', 'view_inbox', $data);
    }

    function aksi_data()
    {
        $this->Model_squrity->getsqurity();
        $this->Model_squrity->cekmenu('inbox');

        $db_arifahpulsa_api = $this->load->database('db_arifahpulsa_api', TRUE);

        $url_mst_inbox_gambar = 'http://141.11.241.178/arifahpulsa/admin/assets/upload/data-inbox/';

        $query = $db_arifahpulsa_api->query("SELECT * FROM tbl_mst_inbox 
                                          ORDER BY mst_inbox_tanggal DESC limit 100");

        echo "<table id='example1' class='table table-bordered table-striped'>";
        echo    "<thead>
                    <tr>
                        <th>No</th>
                        <th>AKSI</th>
                        <th>STATUS</th>
                        <th>KODE</th>
                        <th>JENIS</th>
                        <th>GAMBAR</th>
                        <th>JUDUL</th>
                        <th>ISI</th>
                    </tr>
                </thead
                <tbody>";

        $no = 1;
        foreach ($query->result() as $row) {
            //STATUS
            if ($row->mst_inbox_status == '0') {
                $aksi = "<div class='btn-group'>
                        <button type='button' class='btn btn-danger'>PILIH</button>
                        <button type='button' class='btn btn-danger dropdown-toggle dropdown-icon' data-toggle='dropdown'>
                        <span class='sr-only'>Toggle Dropdown</span>
                        <div style='position: relative;float: none;' class='dropdown-menu' role='menu'>
                            <a class='dropdown-item' onclick=aksi_hapus('" . $row->mst_inbox_kode . "')>HAPUS</a>
                        </div>
                        </button>
                    </div>";
                $status = "<div class='btn btn-success'>AKTIF</div>";
            } else {
                $aksi = "<div class='btn-group'>
                        <button type='button' class='btn btn-danger'>PILIH</button>
                        <button type='button' class='btn btn-danger dropdown-toggle dropdown-icon' data-toggle='dropdown'>
                        <span class='sr-only'>Toggle Dropdown</span>
                        <div style='position: relative;float: none;' class='dropdown-menu' role='menu'>
                            <a class='dropdown-item' onclick=aksi_hapus('" . $row->mst_inbox_kode . "')>HAPUS</a>
                        </div>
                        </button>
                    </div>";
                $status = "<div class='btn btn-danger'>TIDAK AKTIF</div>";
            }

            //GAMBAR
            if ($row->mst_inbox_jenis == 'Teks') {
                $mst_inbox_gambar = "Tidak ada gambar";
            } else {
                $mst_inbox_gambar = "<img src='$url_mst_inbox_gambar" . "$row->mst_inbox_gambar' class='rounded' alt='$row->mst_inbox_gambar' style='width:70;height:70px;text-align:center'>";
            }

            //ISI
            if (strlen($row->mst_inbox_isi) > 100) {
                $words = explode(' ', $row->mst_inbox_isi);
                $limitedWords = array_slice($words, 0, 15);
                $mst_inbox_isi = implode(' ', $limitedWords);
            } else {
                $mst_inbox_isi = $row->mst_inbox_isi;
            }


            echo        "<tr>";
            echo            "<td>" . $no++ . "</td>";
            echo            "<td>$aksi </td>";
            echo            "<td id='tbl_mst_inbox_status'>$status</td>";
            echo            "<td id='tbl_mst_inbox_kode'>$row->mst_inbox_kode</td>";
            echo            "<td id='tbl_mst_inbox_jenis'>$row->mst_inbox_jenis</td>";
            echo            "<td id='tbl_mst_inbox_gambar'>$mst_inbox_gambar</td>";
            echo            "<td id='tbl_mst_inbox_judul'>$row->mst_inbox_judul</td> ";
            echo            "<td id='tbl_mst_inbox_isi'>$mst_inbox_isi</td>";
            echo        "</tr>";
        }
        echo        "</tbody>";
        echo    "</table>";
        echo "<script>
              
                $(document).ready(function () {
                    var table = $('#example1').DataTable({
                        lengthChange : true, 
                        autoWidth: true,
                        paging: true,
                        buttons: ['copy', 'print'],
                    }).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)');
                
                  
                });
                
            </script>";
    }

    function aksi_user()
    {
        $this->Model_squrity->getsqurity();
        $this->Model_squrity->cekmenu('inbox');

        $db_arifahpulsa_api = $this->load->database('db_arifahpulsa_api', TRUE);

        $keyword = explode(',', $this->input->post('keyword'));
        $mst_inbox_user_kode = $keyword[0];
        $json = array();
        $query = $db_arifahpulsa_api->query("SELECT mst_user_kode,mst_user_nama_lengkap,mst_user_nomor_hp
                                from tbl_mst_user where 
                                mst_user_nama_lengkap LIKE '%$mst_inbox_user_kode%' or
                                mst_user_nomor_hp LIKE '%$mst_inbox_user_kode%' or
                                mst_user_kode LIKE '%$mst_inbox_user_kode%'
                                limit 20")->result_array();

        foreach ($query as $row) {
            $json[] = [
                'id' => $row['mst_user_kode'],
                'text' => $row['mst_user_nama_lengkap'] . ' - ' . $row['mst_user_nomor_hp']
            ];
        }
        echo json_encode($json);
    }

    function aksi_tambah()
    {
        $this->Model_squrity->getsqurity();
        $this->Model_squrity->cekmenu('inbox');

        $db_arifahpulsa_api = $this->load->database('db_arifahpulsa_api', TRUE);

        $mst_inbox_kode = "INBOX-" . rand(1000, 9999);
        $mst_inbox_user_pilih = $this->input->post("mst_inbox_user_pilih");
        $mst_inbox_user_kode = $this->input->post("mst_inbox_user_kode");
        $mst_inbox_jenis = $this->input->post("mst_inbox_jenis");
        $mst_inbox_judul = $this->input->post("mst_inbox_judul");
        $mst_inbox_isi = $this->input->post("mst_inbox_isi");
        $mst_inbox_tanggal = date('Y-m-d H:i:s');
        $mst_inbox_status = "0";

        if ($mst_inbox_jenis == "Gambar") {
            //UPLOAD GAMBAR
            $config['upload_path'] = 'assets/upload/data-inbox/';
            $config['allowed_types'] = 'jpg|png|JPG|JPEG|webp|WEBP|PNG';
            $config['remove_spaces'] = TRUE;
            $config['overwrite'] = TRUE;
            $config['max_size'] = '20000';
            $config['file_name'] = 'INBOX-' . $mst_inbox_kode;

            $this->load->library('upload', $config);
            $this->upload->initialize($config);
            $this->upload->data();
            if ($this->upload->do_upload('mst_inbox_gambar')) {
                $img_foto = $this->upload->data();
                $mst_inbox_gambar = $img_foto['file_name'];
            } else {
                $mst_inbox_gambar = "no_image.png";
            }
        } else {
            $mst_inbox_gambar = "";
        }



        //PUSH NOTIF
        if ($mst_inbox_user_pilih == "Semua") {
            $sql_jumlah = $db_arifahpulsa_api->query("SELECT * FROM tbl_mst_user")->result_array();
            $jumlah = round(count($sql_jumlah) / 1000);

            //FIREBASE
            $fcmUrl = 'https://fcm.googleapis.com/fcm/send';

            $this->load->helper("file");
            delete_files('./assets/upload/data-notif/', TRUE);

            for ($x = 0; $x <= $jumlah; $x++) {
                $a = $x + 1;
                $from = ($x * 1000);
                $to = ($a * 1000);

                $sql_user_firebase = $db_arifahpulsa_api->query("SELECT mst_user_kode,mst_user_firebase,mst_user_nama_lengkap 
                                                    FROM tbl_mst_user 
                                                    limit 1000 offset $from")->result_array();
                foreach ($sql_user_firebase as $row) {
                    $mst_user_firebase[] = $row['mst_user_firebase'];
                }
                file_put_contents('assets/upload/data-notif/' . $x . '.txt',  json_encode($mst_user_firebase, TRUE));
                unset($mst_user_firebase);

                $generated_user_firebase = json_decode(file_get_contents('assets/upload/data-notif/' . $x . '.txt'));

                $notification = array(
                    'type' => 1,
                    'title' => "Inbox",
                    'body' => $mst_inbox_judul,
                    'click_action' =>  "main_activity",
                );

                $fcmNotification = [
                    'registration_ids' => $generated_user_firebase,
                    'data' => $notification,
                    'notification' => $notification,
                    'priority' => 'high',
                    'apns-priority' => '5'
                ];

                $headers = [
                    'Authorization: key=' . $this->config->item('firebase_key'),
                    'Content-Type: application/json'
                ];

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $fcmUrl);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
                $result = curl_exec($ch);
                curl_close($ch);
            }

            $sql_user_kode = $db_arifahpulsa_api->query("SELECT GROUP_CONCAT(mst_user_kode) AS mst_user_kode  FROM tbl_mst_user");
            if ($sql_user_kode->num_rows() > 0) {
                foreach ($sql_user_kode->result_array() as $row) {
                    $mst_user_kode = $row['mst_user_kode'];
                }
            }

            //SIMPAN
            $db_arifahpulsa_api->query("insert into tbl_mst_inbox (
                                mst_inbox_kode,
								mst_inbox_user_kode, 
                                mst_inbox_jenis, 
                                mst_inbox_gambar,
								mst_inbox_judul, 
								mst_inbox_isi,
                                mst_inbox_tanggal,
                                mst_inbox_status) values (
                                '$mst_inbox_kode', 
							    '" . str_replace("'", "\'", $mst_user_kode) . "',
								'$mst_inbox_jenis', 
								'$mst_inbox_gambar', 
								'" . str_replace("'", "\'", $mst_inbox_judul) . "',
                                '" . str_replace("'", "\'", $mst_inbox_isi) . "',
                                '" . str_replace("'", "\'", $mst_inbox_tanggal) . "',
                                '" . str_replace("'", "\'", $mst_inbox_status) . "'
                                )");
            $data['tambah_status'] = '0';
            echo json_encode($data);
        } else {
            $mst_user_kode = $mst_inbox_user_kode;
            //PANGGIL USER
            $user = $db_arifahpulsa_api->query("SELECT * FROM tbl_mst_user WHERE mst_user_kode='$mst_user_kode'");
            if ($user->num_rows() > 0) {
                foreach ($user->result() as $row) {
                    $mst_user_firebase = $row->mst_user_firebase;
                }

                //KIRIM NOTIFIKASI
                $title = 'Inbox';
                $body =  strip_tags($mst_inbox_judul);
                firebase_notification($title, $body, $mst_user_firebase);
            }

            //SIMPAN
            $db_arifahpulsa_api->query("insert into tbl_mst_inbox (
                                mst_inbox_kode,
								mst_inbox_user_kode, 
                                mst_inbox_jenis, 
                                mst_inbox_gambar,
								mst_inbox_judul, 
								mst_inbox_isi,
                                mst_inbox_tanggal,
                                mst_inbox_status) values (
                                '$mst_inbox_kode', 
							    '" . str_replace("'", "\'", $mst_user_kode) . "',
								'$mst_inbox_jenis', 
								'$mst_inbox_gambar', 
								'" . str_replace("'", "\'", $mst_inbox_judul) . "',
                                '" . str_replace("'", "\'", $mst_inbox_isi) . "',
                                '" . str_replace("'", "\'", $mst_inbox_tanggal) . "',
                                '" . str_replace("'", "\'", $mst_inbox_status) . "'
                                )");
            $data['tambah_status'] = '0';
            echo json_encode($data);
        }
    }

    function aksi_hapus($mst_inbox_kode)
    {
        $this->Model_squrity->getsqurity();
        $this->Model_squrity->cekmenu('inbox');

        $db_arifahpulsa_api = $this->load->database('db_arifahpulsa_api', TRUE);

        $db_arifahpulsa_api->query("DELETE from tbl_mst_inbox where mst_inbox_kode='$mst_inbox_kode'");
    }
}
