<?php
require_once '_admin_setting.php';

$postData = NutFunction::extractArrayByKeyPrefix($_POST, 'post-');
$catData = NutFunction::extractArrayByKeyPrefix($_POST, 'category-');
$fileData = NutFunction::extractArrayByKeyPrefix($_POST, 'swfupload-');

$action = $_REQUEST['action'];
$success = false;

switch ($action) {
    case 'add':
        $data['post'] = $postData;
        $data['rel_category'] = $catData;
        if (empty($data['rel_category']['cat_id']))
            $data['rel_category']['cat_id'] = $nsoDefaultPostCatId;
        $data['rel_file'] = reconganizeFilesData($fileData); // 整理关联文件的数据
        $postId = Posts::add($data);
        $success = true;
        break;

    case 'update':
        $postId = $_POST['id'];
        $data['post'] = $postData;
        $data['rel_category'] = $catData;
        if (empty($data['rel_category']['cat_id']))
            $data['rel_category']['cat_id'] = $nsoDefaultPostCatId;
        $data['rel_file'] = reconganizeFilesData($fileData);
        Posts::update($postId, $data);
        $success = true;
        break;

    case 'delete':
        $id = $_GET['id'];
        if (! is_numeric($id))
            break;
        $sql = "UPDATE posts SET `status` = 'deleted', `date_update` = NOW() WHERE id = '{$id}'";
		$sql = "DELETE FROM posts WHERE id = '{$id}'";
        $nsodb->query($sql);
        $success = true;
        break;

    case 'deleteAll':
        $ids = $_POST['ids'];
        $ids = implode(',', $ids);
        if (empty($ids))
            break;
        $sql = "UPDATE posts SET `status` = 'deleted', `date_update` = NOW() WHERE id IN ({$ids})";
		$sql = "DELETE FROM posts WHERE id IN ({$ids})";
        $nsodb->query($sql);
        $success = true;
        break;

    default:
        break;
}

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