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

class Pengumuman_m extends CI_Model {
    var $table = 'data_pengumuman';
    public function __construct(){
        parent::__construct();
    }

    function get_datatables(){
        $this->_get_datatables_query();
        if($_GET['length'] != -1){
            $this->db->limit($_GET['length'], $_GET['start']);
        }
        $query = $this->db->get();
        return $query->result();
    }
    
    function count_filtered(){
        $this->_get_datatables_query();
        $query = $this->db->get();
        return $query->num_rows();
    }
    
    public function count_all(){
        $this->db->select("id_pengumuman")->from($this->table);
        $this->db->where("id_company",$_SESSION['id_company']);
        return $this->db->count_all_results();
    }
    
    private function _get_datatables_query(){
        $this->db->select("id_pengumuman, judul, content, target, target_id, id_cabang, date_created, posting")->from($this->table);
        $this->db->where("id_company",$_SESSION['id_company']);
    
        $column_search = array('judul');
        $i = 0;
    
        foreach ($column_search as $item){  // looping awal
            if($_GET['search']['value']){ // jika datatable mengirimkan pencarian dengan metode POST
    
                if($i===0){ // looping awal
                    $this->db->group_start();
                    $this->db->like($item, $_GET['search']['value']);
                }else{
                    $this->db->or_like($item, $_GET['search']['value']);
                }
    
                if(count($column_search) - 1 == $i){
                    $this->db->group_end();
                }
            }
            $i++;
        }
    
        $column_order = array('','','judul');
    
        if(isset($_GET['order'])){
            $this->db->order_by($column_order[$_GET['order']['0']['column']], $_GET['order']['0']['dir']);
        } 
        else{
            $order_by = array("id_pengumuman"=>"DESC");
            $this->db->order_by(key($order_by), $order_by[key($order_by)]);
        }
    }

    public function getDataById($id=null){
        $select = $this->db->query("SELECT id_pengumuman, 
                                            judul, 
                                            content, 
                                            target, 
                                            target_id, 
                                            id_cabang,
                                            date_created
                                    FROM $this->table
                                    WHERE MD5(id_pengumuman) = ?
                                    AND id_company = ?",[$id,$this->id_company])->row();
        return $select;
    }

    public function save($data,$id = null){
        if($id != null){
            $data['user_update'] = $this->nik_karyawan." - ".$this->nm_karyawan;
            $data['tgl_update']  = date('Y-m-d h:i:s');

            $this->db->where(array('md5(id_pengumuman)'=>$id, 'id_company'=>$this->id_company));
            $update = $this->db->update($this->table,$data);
            $this->logger->create_log('informasi_pengumuman', 'edit', $this->db->last_query());
            if($update){
                echo  __response_update(true);
                $id_pengumuman = $this->db->select("id_pengumuman")
                                        ->from($this->table)
                                        ->where("MD5(id_pengumuman)",$id)
                                        ->where("id_company",$this->id_company)
                                        ->get()
                                        ->row("id_pengumuman");
                $token_fcm = $this->_token_fcm($data['target'], $data['target_id'], $data['id_cabang']);
                $this->_send_notif("UPDATE :".$data["judul"], $data["content"], $id_pengumuman, $token_fcm );
            }else{
                return  __response_update(false);
            }
        }else{
            $data['user_input'] = $this->nik_karyawan." - ".$this->nm_karyawan;
            
            $nextId = $this->fungsi->getNextId($this->table,'id_pengumuman',$this->id_company,3);
            $id_pengumuman = array('id_pengumuman' => $nextId);
            $save = $this->db->insert($this->table, array_merge($data,$id_pengumuman));
            if($save){
                echo __response_save(true);
                $token_fcm = $this->_token_fcm($data['target'], $data['target_id'], $data['id_cabang']);
                $this->_send_notif("NEW :".$data["judul"], $data["content"], $nextId, $token_fcm);
            }else{
                return __response_save(false);
            }
        }
    }

    public function delete($id=null){
        $this->db->where(array('md5(id_pengumuman)'=>$id));
        $delete =$this->db->delete($this->table);
        $this->logger->create_log('informasi_pengumuman', 'delete', $this->db->last_query());
        return  __response_delete($delete);
    }

    private function _token_fcm($target=null, $target_id=null, $id_cabang = null){
        $target_id = explode(",",$target_id);
        if($target == '2'){
            $this->db->where_in("data_karyawan.id_cabang",$target_id);
        }else if($target == '3'){
            $this->db->where("data_karyawan.id_cabang",$id_cabang);
            $this->db->where_in("data_karyawan.id_departemen",$target_id);
        }else if($target == '4'){
            $this->db->where_in("data_karyawan.id_karyawan",$target_id);
        }

        $token_fcm = $this->db->select("users.token_fcm")
                            ->from("users")
                            ->join("data_karyawan","data_karyawan.id_karyawan = users.id_karyawan")
                            ->where_in("data_karyawan.status",["1","2","3","4"])
                            ->where("users.token_fcm !=","")
                            ->where("data_karyawan.id_company",$this->id_company)
                            ->get()
                            ->result();
        return $token_fcm;
    }

    private function _send_notif($judul = null, $content = null, $id_ref = null, $token_fcm = null){
        $this->load->library('amqp');

        $timetosend =  0; //waktu delay pesan dalam milisecond, misal delay 3s = 3000
        $queue = $this->amqp->delayedQueueName();
        $exchange = $this->amqp->delayedExchangeName();

        if(!empty($token_fcm)){
            foreach($token_fcm as $row) {
                $send['url'] = $this->config->item('url_api')."/notifikasi/send";
                $send['parameter'] = array(
                    'token_fcm' => $row->token_fcm,
                    'route'     => '/detail_pengumuman',
                    'title'     => $judul,
                    'body'      => strip_tags($content),
                    'id_ref'    => $id_ref
                );
                $this->amqp->init_delayed();
                $this->amqp->queue($queue);
                $this->amqp->exchange($exchange);
                $this->amqp->delay($timetosend);
                $this->amqp->data($send);
                $this->amqp->send();
            }
        }
    }
}