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

class Berita_m extends CI_Model {
    var $table = 'data_berita';
    public function __construct(){
        parent::__construct();
        $this->id_company = $this->session->userdata('id_company');
    }

    function get_datatables(){
        $this->_get_datatables_query();
        if($_POST['length'] != -1){
            $this->db->limit($_POST['length'], $_POST['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_berita")->from($this->table);
        $this->db->where("id_company",$this->id_company);
        return $this->db->count_all_results();
    }
    
    private function _get_datatables_query(){
        $this->db->select("id_berita,judul,content,gambar, date_created")->from($this->table);
        $this->db->where("id_company",$this->id_company);
    
        $column_search = array('judul');
        $i = 0;
    
        foreach ($column_search as $item){  // looping awal
            if($_POST['search']['value']){ // jika datatable mengirimkan pencarian dengan metode POST
    
                if($i===0){ // looping awal
                    $this->db->group_start();
                    $this->db->like($item, $_POST['search']['value']);
                }else{
                    $this->db->or_like($item, $_POST['search']['value']);
                }
    
                if(count($column_search) - 1 == $i){
                    $this->db->group_end();
                }
            }
            $i++;
        }
    
        $column_order = array('','','judul');
    
        if(isset($_POST['order'])){
            $this->db->order_by($column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
        } 
        else{
            $order_by = array("id_berita"=>"DESC");
            $this->db->order_by(key($order_by), $order_by[key($order_by)]);
        }
    }

    public function getDataById($id=null){
        $select = $this->db->query("SELECT id_berita, judul, content, gambar, date_created
                                    FROM $this->table
                                    WHERE MD5(id_berita) = '$id'
                                    AND id_company = '".$_SESSION["id_company"]."'")->row();
        return $select;
    }

    public function save($data,$id = null){
        if($id != null){
            if($data['gambar'] == ""){
                $predir_file = $this->db->select("gambar")
                                        ->from($this->table)
                                        ->where("md5(id_berita)",$id)
                                        ->where("id_company",$this->id_company)
                                        ->get()
                                        ->row("gambar");
            }

            $this->db->where(array('md5(id_berita)'=>$id, 'id_company'=>$this->id_company));
            $update = $this->db->update($this->table,$data);
            if($update){
                if($data['gambar'] == ""){
                    $this->fungsi->delete_fileupload($predir_file);
                }

                $new_params["new_params"] = ["gambar"=>$data["gambar"]];
                echo __response_update($update, $new_params);

                $id_berita = $this->db->select("id_berita")
                                    ->from($this->table)
                                    ->where("md5(id_berita)",$id)
                                    ->where("id_company",$this->id_company)
                                    ->get()
                                    ->row("id_berita");

                $this->_send_notif("UPDATE :".$data['judul'], $data['content'], $id_berita);
            }else{
                return __response_update(false);
            }

        }else{
            $nextId = $this->fungsi->getNextId($this->table,'id_berita',$this->id_company,3);
            $id_berita = array('id_berita' => $nextId);
            $save = $this->db->insert($this->table, array_merge($data,$id_berita));
            if($save){
                echo __response_save(true);
                $this->_send_notif("NEW :".$data['judul'], $data['content'], $nextId);
            }else{
                return __response_save(false);
            }
    
        }
    }

    public function delete($id=null){
        $predir_file = $this->db->select("gambar")
                                        ->from($this->table)
                                        ->where("md5(id_berita)",$id)
                                        ->where("id_company",$this->id_company)
                                        ->get()
                                        ->row("gambar");

        $this->db->where(array('md5(id_berita)'=>$id,'id_company'=>$this->id_company));
        $delete =$this->db->delete($this->table);
        if($delete){
            $this->fungsi->delete_fileupload($predir_file);
            return  __response_delete(true);
        }else{
            return  __response_delete(false);
        }
    }


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

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

        $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("data_karyawan.id_company",$this->id_company)
                                ->where("users.token_fcm !=","")
                                ->get()
                                ->result();

        foreach($token_fcm as $row) {
            $send['url'] = $this->config->item('url_api')."/notifikasi/send";
            $send['parameter'] = array(
                'token_fcm' => $row->token_fcm,
                'route'     => '/detail_berita',
                '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();
        }
    }
}