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

/*
Copyright (C) 2014  Web3king - Alberto Bonacina

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

class Users_model extends CI_Model{
        
    function __construct(){
        // Call the Model constructor
        parent::__construct();
    } 

    function validate(){
        //Check if the username and the password is in the database
        $this->db->where('username',$this->input->post('username'));
        $this->db->where('password',md5($this->input->post('password')));
        //run the query
        $query = $this->db->get('user');
        
        //if only 1 value then the user exists with that password and I can create a session
        if($query->num_rows() > 0){
            $row = $query->row_array(); 
            $data = array('id' => $row['id'],'username' => $row['username'],'type' => $row['type']);
            return $data;
        }
    }

    function allInfoUser($id){

    }

    function getAllTemplateByType($id,$type){
        $this->db->select('*');
        $this->db->where('type', $type);
        $this->db->from('template');
        $query = $this->db->get();
        return $query;
    }

    //Mi faccio ritornare il template dell'utente bansandomi sul suo id
    // $type = 0 tutto il giorno
    // $type = 1 singolo pasto
    function getTemplateByUserID($idUser,$type){
        $this->db->select('template.id as id, template.name as name, template.code as code');
        $this->db->from('template');
        if($type == '1'){//se il tipo è 1 chiedo il template del giorno
            $this->db->join('user', 'template.id = user.templateDay');
        }else{//se il tipo è 2 chiedo il template del singolo pasto
            $this->db->join('user', 'template.id = user.templateSingle');
        }
        $this->db->where('user.id', $idUser);
        $query = $this->db->get();
        return $query->first_row('array');
    }

    //Funzione che setta il default template
    function setDefaultTemplate($type,$idTemplate,$idUser){
        if($type == '1'){//se il tipo è 1 chiedo il template del giorno
            $data = array('templateDay' => $idTemplate);
        }else{//se il tipo è 2 chiedo il template del singolo pasto
            $data = array('templateSingle' => $idTemplate);
        }

        $this->db->where('id', $idUser);
        $this->db->update('user', $data);
    }
}

?>