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

class Crawler_listen_blacklist_model extends CI_Model
{
    protected $_table = 'crawler_listen_blacklists';

    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Ho_Chi_Minh");
    }

    public function add($dataInsert){
        $this->db->insert($this->_table, $dataInsert);
        $insert_id = $this->db->insert_id();
        return $insert_id;
    }

    public function update($id, $dataUpdate){
        $this->db->where('id', $id);
        $this->db->update($this->_table, $dataUpdate);
        return true;
    }

    public function delete($id){
        $this->db->where('id', $id);
        $this->db->delete($this->_table);
        return true;
    }

    public function getSrcByTrackId($track_id, $src=null)
    {
        $this->db->select($this->_table . '.src');
        $this->db->from($this->_table);
        $this->db->where($this->_table . '.track_id', $track_id);
        if (! empty($src)) {
            $this->db->where($this->_table . '.src', $src);
        }
        $query = $this->db->get();
        $result = $query->result_array();
        $data = [];
        if ($result) {
            foreach ($result as $key => $val) {
                $data[] = $val['src'];
            }
        }
        return $data;
    }

    public function checkAndUpdate($track_id, $title, $src, $selected)
    {
        $this->db->select($this->_table . '.*');
        $this->db->from($this->_table);
        $this->db->where($this->_table . '.track_id', $track_id);
        $this->db->where($this->_table . '.src', $src);
        $query = $this->db->get();
        $result = $query->result_array();
        // Nếu đã tồn tại mà bỏ tích chọn thì xóa, ngược lại thì tạo mới
        if (isset($result[0])) {
            if ($selected == 0) {
                $this->db->where('id', $result[0]['id']);
                $this->db->delete($this->_table);
            }
            return true;
        } else {
            $this->db->insert($this->_table, [
                'track_id' => $track_id,
                'src' => strtolower($src),
                'title' => $title,
                'created_by' => $this->session->userdata('id'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            return true;
        }
        //
        return false;
    }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */