<?php
final class DModelSpecific4861MaterialApoio extends Model
{

  public function getMaterial($material_id) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "material WHERE material_id = '" . (int)$material_id . "'");

    return $query->row;
  }


  public function getFilters($data){

    $filter = array();

    if(!empty($data['status'])){
      $filter[] = " status = ".$data['status'];
    }

    return (implode(' and ', $filter)) ? ' where '.implode(' and ', $filter) : '';

  }

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

    $sql = 'SELECT * FROM oc_material';

    $sql.= $this->getFilters($data);

    $sort_data = array(
      'titulo',
    );

    if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
      $sql .= " ORDER BY " . $data['sort'];
    } else {
      $sql .= " ORDER BY date_added";
    }

    if (isset($data['order']) && ($data['order'] == 'DESC')) {
      $sql .= " DESC";
    } else {
      $sql .= " ASC";
    }

    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;

  }

  public function getTotalMaterials($data){

    $sql = 'SELECT count(material_id) as total FROM oc_material';

    $sql.= $this->getFilters($data);

    $sort_data = array(
      'titulo',
    );

    if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
      $sql .= " ORDER BY " . $data['sort'];
    } else {
      $sql .= " ORDER BY date_added";
    }

    if (isset($data['order']) && ($data['order'] == 'DESC')) {
      $sql .= " DESC";
    } else {
      $sql .= " ASC";
    }


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

    return $query->row['total'];

  }

  public function addMaterial($data) {
    $this->db->query("INSERT INTO " . DB_PREFIX . "material SET titulo = '" . $this->db->escape($data['titulo']) . "', status = '" . (int)$data['status'] . "', image = '".$this->db->escape($data['image'])."', date_added = current_timestamp, arquivo = '".$this->db->escape($data['arquivo'])."' ");
  }

  public function editMaterial($material_id, $data) {
    $this->db->query("UPDATE " . DB_PREFIX . "material SET titulo = '" . $this->db->escape($data['titulo']) . "', status = '" . (int)$data['status'] . "', image = '".$this->db->escape($data['image'])."', arquivo = '".$this->db->escape($data['arquivo'])."'  WHERE material_id = '" . (int)$material_id . "'");
  }

  public function deleteMaterial($material_id) {
    $this->db->query("DELETE FROM " . DB_PREFIX . "material WHERE material_id = '" . (int)$material_id . "'");
  }


}