<?
class module extends controller {

    var $params = array("act");


    function loadProfile($user_id) {
        $res = $this->db->query("SELECT wkey,data FROM "._DB_TABLE_PREFIX."profiles WHERE user_id = ".$user_id, true);
        return $res;
    }



    function convertProfile($data) {
        $p = array();
        for($i=0; $i<count($data); $i++) {
            $p[$data[$i]["wkey"]] = $data[$i]["data"];
        }
        return $p;
    }



    function saveProfile($data) {
        for($i=0; $i<count($data); $i++) {
            $sql = "
                INSERT INTO "._DB_TABLE_PREFIX."profiles 
                    (user_id, wkey, data) 
                VALUES ('".$this->user_id."', '".$data[$i]["wkey"]."', '".addslashes($data[$i]["data"])."')";
            $this->db->query($sql);
        }
    }



    function run() {
        switch($this->act) {
            case "create":
                $data = getSafeStr($_REQUEST["data"]);
                $wkey = (int) $_REQUEST["wkey"];
                $this->db->query("INSERT INTO "._DB_TABLE_PREFIX."profiles (user_id, wkey, data) VALUES ('".$this->user_id."', '".$wkey."', '".$data."')");
                return array("status" => "created");
                break;

            case "update":
                $data = getSafeStr($_REQUEST["data"]);
                $wkey = (int) $_REQUEST["wkey"];
                $sql = "UPDATE "._DB_TABLE_PREFIX."profiles SET data = '".$data."' WHERE user_id = ".$this->user_id." AND wkey = ".$wkey." LIMIT 1";
                $this->db->query($sql);
                return array("status" => "updated");
                break;

            case "delete":
                $wkey = (int) $_REQUEST["wkey"];
                $this->db->query("DELETE FROM "._DB_TABLE_PREFIX."profiles WHERE user_id = ".$this->user_id." AND wkey = ".$wkey." LIMIT 1");
                return array("status" => "deleted");
                break;

            case "load_data":
                $profile = $this->loadProfile($this->user_id);
                if(!$profile) {
                    $profile = $this->loadProfile(1);
                    $this->saveProfile($profile);
                }
                if(!$profile) {
                    $profile = array();
                }
                return array("status" => "loaded", "data" => $this->convertProfile($profile));
                break;
        }

        
    }


}
?>