<?php
require_once '_admin_setting.php';
require_once NSO_LIBS_PATH . 'phpthumb/ThumbLib.inc.php';


session_start();
// ini_set("html_errors", "0");

// -------------------------------------------------------------
// 处理传参
// -------------------------------------------------------------
$id = $_REQUEST['id'];
$parent = $_REQUEST['parent'];
$cat = $_REQUEST['cat'];
$action = $_REQUEST['action'];
$name = $_POST['name'];
$od = $_POST['od'];
if (empty($od)) $od = 0;

switch ($action) {
	case 'add':
		$sql = "INSERT INTO categories(name, parent, od) VALUES('{$name}', {$parent}, {$od})";
		$nsodb->query($sql);
		$id = $nsodb->insert_id;
		break;
	
	case 'update':
		$sql = "UPDATE categories SET name = '{$name}', od = {$od} WHERE id = {$id}";
		$nsodb->query($sql);
		break;
	
	case 'delete':
		$sql = "DELETE FROM categories WHERE id = {$id}";
		$nsodb->query($sql);
		$array = array('success' => $success, 'id' => $id);
		echo json_encode($array);
		exit();
		break;
	
	default:
		break;
}


// -------------------------------------------------------------
// Swfuploadw问题
// -------------------------------------------------------------
if (isset($_POST["PHPSESSID"])) {
    session_id($_POST["PHPSESSID"]);
}


// -------------------------------------------------------------
// 保存数据处理
// -------------------------------------------------------------
$today = getdate();

// 按年月日建立上传目录
// -------------------------------------------------------------
$yearPath = NSO_UPLOAD_PATH . $today['year'];
$monthPath = $yearPath . '/' . $today['mon'];

if (! is_dir($yearPath))  mkdir($yearPath);
if (! is_dir($monthPath)) mkdir($monthPath);
if (! is_dir("{$monthPath}/_source")) mkdir("{$monthPath}/_source");
if (! is_dir("{$monthPath}/_thumb"))  mkdir("{$monthPath}/_thumb");
if ($nsoImageSizeNeedToCreate){
    foreach ($nsoImageSizeNeedToCreate as $size){
        if (! is_dir("{$monthPath}/_{$size}")) mkdir("{$monthPath}/_{$size}");
    }
}

// 文件保存的相对路径，主要用于返回JSON
$relativePath = "../" . NSO_UPLOAD_DIR_NAME . "/{$today['year']}/{$today['mon']}/";

$randName = date('His') . '_' . rand(10, 99);
$ext = NutFunction::getExt($_FILES['Filedata']['name']);
$saveFileName = "{$randName}.{$ext}";

$savePathSource = $relativePath . '_source/' . $saveFileName;
$savePathNormal = $relativePath . $saveFileName;
$savePathThumb  = $relativePath . '_thumb/' . $saveFileName;

$size = (int) ($_FILES['Filedata']['size'] / 1024);
if (in_array($ext, $nsoUploadFileAllowType) && move_uploaded_file($_FILES['Filedata']['tmp_name'], $savePathSource)) {

    $type = 'pdf';

    // 上传的文件是规定的图片格式，则生成系统设定的缩略图
    if (in_array($ext, array('jpg', 'jpeg', 'png'))) {

        $image = PhpThumbFactory::create($savePathSource);
        $image->resize(600)->save($savePathNormal);

        list ($width, $height, $type, $attr) = getimagesize($savePathNormal);
        $size = ($width > $height) ? $height : $width;
        $image->cropFromCenter($size)->resize(49)->save($savePathThumb);

        // 按照$nsoImageSizeNeedToCreate生成规定的图片尺寸
        $image = PhpThumbFactory::create($savePathSource);
        rsort($nsoImageSizeNeedToCreate, SORT_NUMERIC); // 逆向排序，从大到小生成图片
        if ($nsoImageSizeNeedToCreate){
            foreach ($nsoImageSizeNeedToCreate as $size){
                $savePath = $relativePath . '_' . $size . '/' . $saveFileName;
                $image->resize($size)->save($savePath);
            }
        }
        $type = 'image';
    }
	
	$savePathSource = str_replace("../" . NSO_UPLOAD_DIR_NAME . "/", '', $savePathSource);
    $sql = "UPDATE categories SET image = '{$savePathSource}' WHERE id = {$id}";
	$nsodb->query($sql);
}

header("Location: categories.php?cat={$cat}");