<?
class module extends controller {

    var $params = array("act");
    var $isNeedMysql = true;


 
    function run() {
        switch($this->act) {
            case "get_new_messages":
                $sql = "SELECT
                            m.id, 
                            m.body,
                            u.email as from_email
                        FROM
                            "._DB_TABLE_PREFIX."messages as m
                        LEFT JOIN
                            jaws_users as u
                            ON
                            u.id = m.from_user_id
                        WHERE
                            m.to_user_id = '".$this->user_id."' AND m.received = 0";
                $res = $this->db->query($sql, true);
                return array("status"   => "new_messages", 
                             "list"     => is_array($res) ? $res : array());
                break;



            case "set_received":
                $ids = explode("_", getSafeStr($_REQUEST["ids"]));
                if(is_array($ids)) {
                    $this->db->query("UPDATE 
                                         "._DB_TABLE_PREFIX."messages 
                                      SET 
                                         received = 1 
                                      WHERE to_user_id = '".$this->user_id."' AND 
                                            id IN ('".join("','", $ids)."')");
                    return array("status" => "ok", "act" => "set_received");
                } else {
                    return array("status" => "error", "act" => "set_received");
                }
                break;

            case "send":
                $to = isset($_REQUEST['to']) ? getSafeStr($_REQUEST['to']) : null;
                $res = $this->db->query("SELECT id FROM "._DB_TABLE_PREFIX."users WHERE email = '".$to."'");
                if(!$res) {
                    return array("status" => "send_error");
                }

                $to_user_id = $res["id"];
                $body = isset($_REQUEST['body']) ? getSafeStr($_REQUEST['body']) : null;
                if($to && $body) {

                    $this->db->query("INSERT INTO   
                                          "._DB_TABLE_PREFIX."messages
                                          (from_user_id, to_user_id, body, received)
                                      VALUES
                                          ('".$this->user_id."', '".$to_user_id."', '".$body."', 0)");
                }
                return array("status" => "send_ok");
                break;
        }
    }

}
?>
