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

class Report_views_daily_model extends CI_Model
{
    protected $_table='report_views_daily';

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

    public function cmsCountAll($name = null)
    {
        $this->db->select('COUNT(*) AS totalResults');
        $this->db->from($this->_table);
        if ($name != null) {
            $this->db->where('date', date('Y-m-d', strtotime($name)));
        }
        $query = $this->db->get();
        $result = $query->result_array();
        if ($result) {
            return $result[0]['totalResults'];
        } else {
            return 0;
        }
    }

    /**
     * Hàm lấy dữ liệu phân trang
     *
     * @param $record
     * @param $start
     * @param null $name
     *
     * @return mixed
     */
    public function cmsGetPagination($record, $start, $name = null)
    {
        $this->db->select($this->_table . '.*, tracks.title AS name_song, tracks.art AS art, tracks.art_type AS art_type');
        $this->db->from($this->_table);
        $this->db->join('tracks', 'tracks.id = report_views_daily.track_id', 'left');
        if ($name != null) {
            $this->db->where('date', date('Y-m-d', strtotime($name)));
        }
        $this->db->group_by('report_views_daily.id');
        $this->db->order_by($this->_table . '.total_point', 'desc');
        $this->db->limit($record);
        $query = $this->db->get();

        return $query->result_array();
    }

    /**
     * Hàm lấy xếp hạng tháng trước để so sánh tăng/giảm hạng
     *
     * @param $date
     * @return array
     */
    public function previousRanking($date)
    {
        $this->db->select('track_id, ranking, month, year');
        $this->db->from($this->_table);

        if ($date != null) {
            $yesterday = date('Y-m-d', strtotime($date) - 86400);
            $this->db->where('date', $yesterday);
        }

        $this->db->where('ranking <=', 100);
        $query = $this->db->get();
        $data = $query->result_array();

        $result = [];
        if ($data) {
            foreach ($data as $key => $val) {
                $result[$val['track_id']] = $val['ranking'];
            }
        }

        return $result;
    }

}