<?php

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

$action = trim($_GET['action']);
$userid = intval($_GET['userid']);
$devicetoken = trim($_GET['devicetoken']);
$platform = trim(strtolower($_GET['platform']));
$table = 'mocuz_member_device';

if(!$userid) {
    odz_error('userid error');
}
if(empty($devicetoken)) {
    odz_error('devicetoken error');
}
if(!in_array($platform, array('ios', 'android'))) {
    odz_error('platform error');
}

if($action == 'register') {
    DB::query("UPDATE %t SET status = 0 WHERE devicetoken = %s AND platform = %s", array($table, $devicetoken, $platform));
    $device = DB::fetch_first("SELECT * FROM %t WHERE uid = %d AND devicetoken = %s AND platform = %s", array($table, $userid, $devicetoken, $platform));
    if($device) {
        DB::update($table, array('status'=>1), array('id'=>$device['id']));
        odz_success();
    }
    $deviceid = DB::insert($table, array('uid'=>$userid, 'devicetoken'=>$devicetoken, 'platform'=>$platform));
    if(!$deviceid) {
        odz_error('register_device_failed');
    }
    odz_success();

} elseif($action == 'unregister') {
    DB::update($table, array('status'=>0), array('uid'=>$userid, 'devicetoken'=>$devicetoken, 'platform'=>$platform));
    odz_success();

} else {
    odz_error('undefined_action');
}
