<?php 
final class DModelMercadolivreMeliNoticies extends Model {

	public function getApiNoticies(){

		if(!$this->config->get('mercadolivre_status')){
			throw new Exception('Configuração de verificação de notícias desabilitada!');
		}

    $noticies = $this->mercadolivre->getSellerNoticies()->results;

    if (!$noticies) {
      return false;
    }

    $this->load->helper('Ftr_sql');

    foreach ($noticies as $noticie){

      $result = $this->getNoticiesById($noticie->id);

      if(!$result){
        $data = array(
          'noticies_id' => $noticie->id,
          'label' => $noticie->label,
          'description' => $noticie->description,
          'actions' => json_encode($noticie->actions),
          'date_created' => date("Y-m-d")
        );

        $sqlInsert = Ftr_sql::generateInsert('oc_mercadolivre_noticies',
          ['noticies_id', 'label', 'description', 'actions', 'date_created']);

        $this->db->executeSql($sqlInsert, $data);
      }

    }

	}

	public function getNoticiesById($noticies_id){

	  $sql = "select * from oc_mercadolivre_noticies where noticies_id = ".$noticies_id;

	  $query = $this->db->query($sql);

	  return ($query->rows) ? $query->rows : false ;

  }


  public function getNoticies($data = array()){

    $sql = "SELECT * FROM oc_mercadolivre_noticies";

    $filtro = array();
    if(!empty($data['data_atual'])){
      $filtro[] = " date_created BETWEEN CURDATE() - INTERVAL 60 DAY AND CURDATE()";
    }

    if($filtro){
      $sql .= ' WHERE '.implode(' AND ', $filtro);
    }

    $sql .= " ORDER BY date_created DESC";

    if (isset($data['start']) || isset($data['limit'])) {
      if ($data['start'] < 0) {
        $data['start'] = 0;
      }

      if ($data['limit'] < 1) {
        $data['limit'] = 20;
      }

      $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
    }

    $query = $this->db->query($sql);

    return ($query->rows) ? $query->rows : false ;

  }

  public function getTotalNoticies($data = array()){

    $sql = "select count(mercadolivre_noticies_id) as total from oc_mercadolivre_noticies order by date_created desc";

    $query = $this->db->query($sql);

    return ($query->rows) ? $query->row['total'] : false ;

  }

}