<?php
require_once '_admin_setting.php';

$action = $_REQUEST['action'];
$id = $_REQUEST['id'];
$username = $_POST['username'];
$npassword = md5($_POST['npassword']);
$opassword = md5($_POST['opassword']);
$success = false;

switch ($action) {
    case 'add':
		$sql = "INSERT INTO users(account, password) VALUES('{$username}', '{$npassword}')";
		$nsodb->query($sql);
		$id = $nsodb->insert_id;
        $success = true;
        break;

    case 'update':
        $sql = "SELECT * FROM users WHERE account = '{$username}' AND password = '{$opassword}'";
		$row = $nsodb->get_row($sql);
		if ($row) {
			$sql = "UPDATE users SET password = '{$npassword}' WHERE id = {$id}";
			$nsodb->query($sql);
			$success = true;
		}
        break;

    case 'delete':
        $id = $_GET['id'];
        if (! is_numeric($id))
            break;
		$sql = "DELETE FROM users WHERE id = {$id}";
        $nsodb->query($sql);
        $success = true;
        break;

    default:
        break;
}

// ------------------------------------------
// 如果是AJAX请求，返回JSON.
// ------------------------------------------
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
    $array = array('success' => $success, 'id' => $id);
    echo json_encode($array);
    exit();
}
header('Location: users.php');