<?php
class local_badiunet_userpreferences
{
    
	function add($userid,$name,$value) {
		$exist=$this->exist($userid,$name);
		$result=null;
		if($exist){
			$result=$this->update($userid,$name,$value);
		}else{
			$result=$this->save($userid,$name,$value);
		}
		return $result;
	}
	public function exist($userid,$name) {
		 global $DB, $CFG;
		 $sql="SELECT COUNT(id) AS countrecord FROM {$CFG->prefix}user_preferences WHERE userid=$userid AND name='".$name."'";
        // echo $sql;
		 $r= $DB->get_record_sql($sql);
         return $r->countrecord;
			
	 }
    
	function save($userid,$name,$value) {
         global $DB, $CFG;
        
         $dto=  new StdClass;
         $dto->userid=$userid;
		 $dto->name=$name;
         $dto->value=$value;
        return  $DB->insert_record('user_preferences', $dto);
       
    }
	
	function getId($userid,$name) {
         global $DB, $CFG;
        global $DB, $CFG;
		 $sql="SELECT id FROM {$CFG->prefix}user_preferences WHERE userid=$userid AND name='".$name."'";
         $r= $DB->get_record_sql($sql);
         return $r->id;
       
    }
	function getValue($userid,$name) {
         global $DB, $CFG;
        global $DB, $CFG;
		 $sql="SELECT value FROM {$CFG->prefix}user_preferences WHERE userid=$userid AND name='".$name."'";
         $r= $DB->get_record_sql($sql);
         return $r->value;
       
    }
	function update($userid,$name,$value) {
        global $DB, $CFG;
        $dto=  new StdClass;
        $dto->userid=$userid;
		$dto->name=$name;
        $dto->value=$value;
        $dto->id=$this->getId($userid,$name);
        return $DB->update_record('user_preferences', $dto);
    }
	
	function delete($userid,$name,$value) {
        global $DB, $CFG;
		$sql="DELETE FROM {$CFG->prefix}user_preferences WHERE userid=$userid AND name='".$name."'";
        $r=$DB->execute($sql);
        return $r;   
    }
}
?>