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

class Veiculos_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }


    function get($table, $fields, $where = '', $perpage = 0, $start = 0, $one = false, $array = 'array') {

        $this->db->select($fields);
        $this->db->from($table);
        $this->db->limit($perpage, $start);
//        $this->db->order_by('idUsuarios','desc');

        if ($where) {
            $this->db->where($where);
        }

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

        $result = !$one ? $query->result() : $query->row();
        return $result;
    }

    function getCheListComItens() {
        $linhas = $this->db->get('tbl_005_checklist')->result();
        foreach ($linhas as $linha) {
            $itens = new stdClass;
            $this->db->where('CHECKLIST_ID', $linha->ID_CHECKLIST);
            $itens->ITENS_CHECKLIST = $this->db->get('tbl_007_itens_checklist')->result();
            foreach (get_object_vars($itens) as $item => $valor) {
                $linha->$item = $valor;
            }
        }
        return $linhas;
    }

    function getById($id) {
        $this->db->where('idUsuarios', $id);
        $this->db->limit(1);
        return $this->db->get('usuarios')->row();
    }

    function add($table, $data) {
        $this->db->insert($table, $data);
        if ($this->db->affected_rows() == '1') {
            return TRUE;
        }

        return FALSE;
    }

    function edit($table, $data, $fieldID, $ID) {
        $this->db->where($fieldID, $ID);
        $this->db->update($table, $data);

        if ($this->db->affected_rows() >= 0) {
            return TRUE;
        }

        return FALSE;
    }

    function delete($table, $fieldID, $ID) {
        $this->db->where($fieldID, $ID);
        $this->db->delete($table);
        if ($this->db->affected_rows() == '1') {
            return TRUE;
        }

        return FALSE;
    }

    function count($table) {
        return $this->db->count_all($table);
    }

    public function autoCompleteVeiculo($q) {
        $this->db->select('*');
        $this->db->limit(15);
        $this->db->like('prefixo', $q);
//        $this->db->where('situacaoMorador', 1);
        $query = $this->db->get('tbl_008_veiculos');

        if ($query->num_rows() > 0) {
            foreach ($query->result_array() as $row) {
                $row_set[] = array(
                    'label' => $row['PREFIXO'] ,
                    'placa' => $row['PLACA'],
                    'garagem' => $row['GARAGEM'],
                    'idVeiculo' => $row['ID_VEICULOS'],
                    'tipoVeiculo' => $row['TIPO'],
//                    'email_morador' => $row['email_morador'],
//                    'nr_celular' => $row['nr_celular']
                );
            }
            echo json_encode($row_set);
        }
    }
}