<?php
class DModelSettingTask extends Model {

	public function editDateTaskByType($data){

		$sql = "UPDATE ".DB_PREFIX."task_control SET date_last_acting = '".$this->db->escape($data['date_last_acting'])."' WHERE type = '".(int)$data['type']."'; ";
		$this->db->query($sql);

	}

	public function editAllTasks($data){

		$sql = "";
		foreach($data as $key => $value){
			$sql = "UPDATE ".DB_PREFIX."task_control SET time_execution = ".$this->db->escape($value['time_execution'])." WHERE taskcontrol_id = '".(int)$value['task_id']."'; ";
			$this->db->query($sql);
		}

	}

	public function getTask($task_id) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "task_control WHERE taskcontrol_id = '" . (int)$task_id . "'");

		return $query->row;
	}

	public function getTaskByType($type) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "task_control WHERE type = '" . (int)$type . "'");

		return $query->row;
	}

	public function getTasks($data = array()) {
    $retorno = array();

		$sql = "SELECT * FROM " . DB_PREFIX . "task_control WHERE NOT taskcontrol_id IS NULL ";

		if(isset($data['type'])){
			$sql.= "AND type = ".$this->db->escape($data['type']);
		}

		$sql .=" ORDER BY taskcontrol_id 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);

    foreach ($query->rows as $row){
      $retorno[$row['type']] = array(
        'taskcontrol_id'        => $row['taskcontrol_id'],
        'type'                  => $row['type'],
        'date_last_acting'      => $row['date_last_acting'],
        'description'           => $row['description'],
        'time_execution'        => $row['time_execution'],
        'time_default'          => $row['time_default'],
        'predefined_execution'  => $row['predefined_execution'],
        'type_group'  => $row['type_group']
      );
    }


		return $retorno;

	}

	public function getTotalTasks() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "task_control");

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


}
