<?php
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
//require_once(ROOT_PATH . '/' . ADMIN_PATH . '/includes/lib_news.php');
include_once(ROOT_PATH . '/includes/cls_image.php');
$exc = new exchange($ecs->table('hs_news'), $db, 'id', 'subject');
$image = new cls_image($_CFG['bgcolor']);

/*------------------------------------------------------ */
//-- 新聞列表
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
//    admin_priv('goods_manage');

    $ur_here = '新聞列表';
    $smarty->assign('ur_here', $ur_here);
    $action_link = array('href' => 'news.php?act=add', 'text' => '新增新聞');
    $smarty->assign('action_link',  $action_link);

    $smarty->assign('lang',         $_LANG);

    $news_list = news_list();
    $smarty->assign('news_list',   	$news_list['news']);
    $smarty->assign('filter',       $news_list['filter']);
    $smarty->assign('record_count', $news_list['record_count']);
    $smarty->assign('page_count',   $news_list['page_count']);
    $smarty->assign('full_page',    1);

    /* 排序标记 */
    $sort_flag  = sort_flag($news_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    /* 获取商品类型存在规格的类型 */

    /* 显示商品列表页面 */
    assign_menu_info();
    assign_query_info();
    $smarty->display('news_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{

    $news_list = news_list();
    $smarty->assign('news_list',   	$news_list['news']);
    $smarty->assign('filter',       $news_list['filter']);
    $smarty->assign('record_count', $news_list['record_count']);
    $smarty->assign('page_count',   $news_list['page_count']);
    $smarty->assign('full_page',    0);
 
    /* 排序标记 */
    $sort_flag  = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    /* 获取商品类型存在规格的类型 */

    make_json_result($smarty->fetch('news_list.htm'), '',
        array('filter' => $news_list['filter'], 'page_count' => $news_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加新商品 编辑商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    include_once(ROOT_PATH . 'includes/fckeditor/fckeditor.php'); // 包含 html editor 类文件

    $is_add = $_REQUEST['act'] == 'add'; // 添加还是编辑的标识
//    admin_priv('goods_manage'); // 检查权限
    /* 如果是安全模式，检查目录是否存在 */
	
    if (ini_get('safe_mode') == 1 && (!file_exists('../' . IMAGE_DIR . '/'.date('Ym')) || !is_dir('../' . IMAGE_DIR . '/'.date('Ym'))))
    {
        if (@!mkdir('../' . IMAGE_DIR . '/'.date('Ym'), 0777))
        {
            $warning = sprintf($_LANG['safe_mode_warning'], '../' . IMAGE_DIR . '/'.date('Ym'));
            $smarty->assign('warning', $warning);
        }
    }

    /* 如果目录存在但不可写，提示用户 */
    elseif (file_exists('../' . IMAGE_DIR . '/'.date('Ym')) && file_mode_info('../' . IMAGE_DIR . '/'.date('Ym')) < 2)
    {
        $warning = sprintf($_LANG['not_writable_warning'], '../' . IMAGE_DIR . '/'.date('Ym'));
        $smarty->assign('warning', $warning);
    }

    if ($is_add)
    {
        $news = array(
            'id'      => 0,
            'subject'    => '',
			'content'	=> '',
            'start_time' => local_date('Y-m-d'),
            'end_time'   => local_date('Y-m-d', local_strtotime('+1 month')),
        );

        /* 图片列表 */
        $img_list = array();
    }
    else
    {
        $sql = "SELECT * FROM " . $ecs->table('hs_news') . " WHERE id = '$_REQUEST[id]'";
        $news = $db->getRow($sql);
		 
        if (empty($news) === true)
        {
            /* 默认值 */
			$news = array(
				'id'      => 0,
				'subject'    => '',
				'content'	=> '',
				'start_time' => local_date('Y-m-d'),
				'end_time'   => local_date('Y-m-d', local_strtotime('+1 month')),
			);
        }

    }


    /* 创建 html editor */
    create_html_editor('goods_desc', $goods['goods_desc']);
    $smarty->assign('goods_desc',    $goods['goods_desc']);

    /* 模板赋值 */
    $smarty->assign('ur_here', $is_add ?  $_LANG['02_goods_add'] : $_LANG['51_virtual_card_add']);
    $smarty->assign('action_link', list_link($is_add, $code));
    $smarty->assign('news', $news);
    $smarty->assign('cfg', $_CFG);
    $smarty->assign('form_act', $is_add ? 'insert' : ($_REQUEST['act'] == 'edit' ? 'update' : 'insert'));
    if ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
    {
        $smarty->assign('is_add', true);
    }

    $smarty->assign('img_list', $img_list);
    $smarty->assign('gd', gd_version());
    $smarty->assign('thumb_width', 200);
    $smarty->assign('thumb_height', 0);
//    $smarty->assign('goods_attr_html', build_attr_html($goods['goods_type'], $goods['goods_id']));

    /* 显示商品信息页面 */
    assign_menu_info();
    assign_query_info();
    $smarty->display('news_info.htm');
}

/*------------------------------------------------------ */
//-- 插入商品 更新商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
//    admin_priv('goods_manage'); // 检查权限
    /* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
    if (isset($_FILES['image']['error'])) // php 4.2 版本才支持 error
    {
        // 最大上传文件大小
        $php_maxsize = ini_get('upload_max_filesize');
        $htm_maxsize = '20M';

        // 商品图片
        if ($_FILES['image']['error'] == 0)
        {
            if (!$image->check_img_type($_FILES['image']['type']))
            {
                sys_msg('圖片格式錯誤', 1, array(), false);
            }
        }
        elseif ($_FILES['image']['error'] == 1)
        {
            sys_msg(sprintf($_LANG['goods_img_too_big'], $php_maxsize), 1, array(), false);
        }
        elseif ($_FILES['index_banner']['error'] == 2)
        {
            sys_msg(sprintf($_LANG['goods_img_too_big'], $htm_maxsize), 1, array(), false);
        }

    }
    /* 4.1版本 */
    else
    {
        // 商品图片
        if ($_FILES['image']['tmp_name'] != 'none')
        {
            if (!$image->check_img_type($_FILES['image']['type']))
            {

                sys_msg($_LANG['invalid_goods_img'], 1, array(), false);
            }
        }
    }

    /* 插入还是更新的标识 */
    $is_insert = $_REQUEST['act'] == 'insert';

    /* 处理商品图片 */
    $nimage        = '';  // 初始化商品图片
    $old_image = '';  // 初始化原始图片旧图

    // 如果上传了商品图片，相应处理
    if (($_FILES['image']['tmp_name'] != '' && $_FILES['image']['tmp_name'] != 'none'))
    {
        if ($_REQUEST['id'] > 0)
        {
            /* 删除原来的图片文件 */
            $sql = "SELECT image " .
                    " FROM " . $ecs->table('hs_news') .
                    " WHERE id = '$_REQUEST[id]'";
            $row = $db->getRow($sql);
            if ($row['image'] != '' && is_file('../' . $row['image']))
            {
                @unlink('../' . $row['image']);
            }

        }
        $original_img   = $image->upload_image($_FILES['image']); // 原始图片
        if ($original_img === false)
        {
            sys_msg($image->error_msg(), 1, array(), false);
        }
        $nimage      = $original_img;   // 商品图片

	}


    /* 處理數據 */
    $id = empty($_POST['id']) ? 0 : intval($_POST['id']);


    /* 入库 */
    if ($is_insert)
    {
            $sql = "INSERT INTO " . $ecs->table('hs_news') . 
					" (hs_id, subject, content,start_time,end_time, image, enable," .
                    " cstamp, ustamp)" .
                "VALUES ('".$_SESSION['user_id']."', '$_POST[subject]','$_POST[content]', " .
                "'$_POST[start_time]','$_POST[end_time]','$nimage',1,".
                    " '" . gmtime() . "', '". gmtime() ."')";
    }
    else
    {
        /* 如果有上传图片，删除原来的商品图 */
		if (($_FILES['image']['tmp_name'] != '' && $_FILES['image']['tmp_name'] != 'none')){
			$sql = "SELECT image " .
						" FROM " . $ecs->table('hs_news') .
						" WHERE id = '$_REQUEST[id]'";
			$row = $db->getRow($sql);
			if ($row['image'])
			{
				@unlink(ROOT_PATH . $row['image']);
			}			
		}


        $sql = "UPDATE " . $ecs->table('hs_news') . " SET " .
                "subject 	= '$_POST[subject]', " .
                "content 	= '$_POST[content]', " .
                "start_time = '$_POST[start_time]', " .
                "end_time 	= '$_POST[end_time]', " .
                "ustamp 	= '".time()."', " ;
        /* 如果有上传图片，需要更新数据库 */
        if ($nimage)
        {
            $sql .= "image = '$nimage', ";
        }
        $sql .=  "ustamp = '". gmtime() ."' ".
                "WHERE id = '$_REQUEST[id]' LIMIT 1";
    }
    $db->query($sql);
    /* 商品编号 */
    $id = $is_insert ? $db->insert_id() : $_REQUEST['id'];

    /* 记录日志 */
    if ($is_insert)
    {
        //admin_log($_POST['goods_name'], 'add', 'goods');
    }
    else
    {
        //admin_log($_POST['goods_name'], 'edit', 'goods');
    }
    
    /* 清空缓存 */
    clear_cache_files();

    if ($is_insert)
    {
        $link[0] = add_link();
    }
    $link[1] = list_link($is_insert);


    //$key_array = array_keys($link);
    for($i=0;$i<count($link);$i++)
    {
       $key_array[]=$i;
    }
    krsort($link);
    $link = array_combine($key_array, $link);


    sys_msg($is_insert ? '新增成功' : '修改成功', 0, $link);
}



/*------------------------------------------------------ */
//-- 显示图片
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'show_image')
{

//    $img_url = $_GET['img_url'];
    $img_url = '../' . $_GET['img_url'];
    $smarty->assign('img_url', $img_url);
    $smarty->display('show_image.htm');
}

/*------------------------------------------------------ */
//-- 修改商品名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_name')
{
    check_authz_json('goods_manage');

    $goods_id   = intval($_POST['id']);
    $goods_name = json_str_iconv(trim($_POST['val']));

    if ($exc->edit("goods_name = '$goods_name', last_update=" .gmtime(), $goods_id))
    {
        clear_cache_files();
        make_json_result(stripslashes($goods_name));
    }
}

/*------------------------------------------------------ */
//-- 修改商品货号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_sn')
{
    check_authz_json('goods_manage');

    $goods_id = intval($_POST['id']);
    $goods_sn = json_str_iconv(trim($_POST['val']));

    /* 检查是否重复 */
    if (!$exc->is_only('goods_sn', $goods_sn, $goods_id))
    {
        make_json_error($_LANG['goods_sn_exists']);
    }
    if ($exc->edit("goods_sn = '$goods_sn', last_update=" .gmtime(), $goods_id))
    {
        clear_cache_files();
        make_json_result(stripslashes($goods_sn));
    }
}

elseif ($_REQUEST['act'] == 'check_goods_sn')
{
    check_authz_json('goods_manage');

    $goods_id = intval($_REQUEST['goods_id']);
    $goods_sn = htmlspecialchars(json_str_iconv(trim($_REQUEST['goods_sn'])));

    /* 检查是否重复 */
    if (!$exc->is_only('goods_sn', $goods_sn, $goods_id))
    {
        make_json_error($_LANG['goods_sn_exists']);
    }
    make_json_result('');
}
elseif ($_REQUEST['act'] == 'check_products_goods_sn')
{
    check_authz_json('goods_manage');

    $goods_id = intval($_REQUEST['goods_id']);
    $goods_sn = json_str_iconv(trim($_REQUEST['goods_sn']));
    $products_sn=explode('||',$goods_sn);
    if(!is_array($products_sn))
    {
        make_json_result('');
    }
    else
    {
        foreach ($products_sn as $val)
        {
            if(empty($val))
            {
                 continue;
            }
            if(is_array($int_arry))
            {
                if(in_array($val,$int_arry))
                {
                     make_json_error($val.$_LANG['goods_sn_exists']);
                }
            }
            $int_arry[]=$val;
            if (!$exc->is_only('goods_sn', $val, '0'))
            {
                make_json_error($val.$_LANG['goods_sn_exists']);
            }
        }
    }
    /* 检查是否重复 */
    make_json_result('');
}


/*------------------------------------------------------ */
//-- 修改上架状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_enable')
{
//    check_authz_json('goods_manage');

    $id       = intval($_POST['id']);
    $enable        = intval($_POST['val']);

    if ($exc->edit("enable = '$enable', ustamp=" .gmtime(), $id))
    {
        clear_cache_files();
        make_json_result($enable);
    }
}

/*------------------------------------------------------ */
//-- 修改精品推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_best')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_best        = intval($_POST['val']);

    if ($exc->edit("is_best = '$is_best', last_update=" .gmtime(), $goods_id))
    {
        clear_cache_files();
        make_json_result($is_best);
    }
}

/*------------------------------------------------------ */
//-- 修改新品推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_new')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_new         = intval($_POST['val']);

    if ($exc->edit("is_new = '$is_new', last_update=" .gmtime(), $goods_id))
    {
        clear_cache_files();
        make_json_result($is_new);
    }
}

/*------------------------------------------------------ */
//-- 修改热销推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_hot')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_hot         = intval($_POST['val']);

    if ($exc->edit("is_hot = '$is_hot', last_update=" .gmtime(), $goods_id))
    {
        clear_cache_files();
        make_json_result($is_hot);
    }
}

/*------------------------------------------------------ */
//-- 修改商品排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_sort_order')
{
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $sort_order     = intval($_POST['val']);

    if ($exc->edit("sort_order = '$sort_order', last_update=" .gmtime(), $goods_id))
    {
        clear_cache_files();
        make_json_result($sort_order);
    }
}

elseif ($_REQUEST['act'] == 'remove')
{
//    check_authz_json('remove_back');

    // 取得参数
    $id = intval($_REQUEST['id']);
    if ($id <= 0)
    {
        make_json_error('invalid params');
    }

    /* 取得商品信息 */
    $sql = "SELECT * " .
            "FROM " . $ecs->table('hs_news') .
            " WHERE id = '$id'";
    $news = $db->getRow($sql);
    if (empty($news))
    {
        make_json_error('文章不存在');
    }

    /* 删除商品图片和轮播图片 */
    if (!empty($news['image']))
    {
        @unlink('../' . $news['image']);
    }
    $exc->drop($id);

    clear_cache_files();
    $url = 'news.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");

    exit;
}

/*------------------------------------------------------ */
//-- 切换商品类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_attr')
{
    check_authz_json('goods_manage');

    $goods_id   = empty($_GET['goods_id']) ? 0 : intval($_GET['goods_id']);
    $goods_type = empty($_GET['goods_type']) ? 0 : intval($_GET['goods_type']);

    $content    = build_attr_html($goods_type, $goods_id);

    make_json_result($content);
}

/*------------------------------------------------------ */
//-- 删除图片
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_image')
{
//    check_authz_json('goods_manage');

    $img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);

    /* 删除图片文件 */
    $sql = "SELECT img_url, thumb_url, img_original " .
            " FROM " . $GLOBALS['ecs']->table('hs_gallery') .
            " WHERE img_id = '$img_id'";
    $row = $GLOBALS['db']->getRow($sql);

    if ($row['img_url'] != '' && is_file('../' . $row['img_url']))
    {
        @unlink('../' . $row['img_url']);
    }
    if ($row['thumb_url'] != '' && is_file('../' . $row['thumb_url']))
    {
        @unlink('../' . $row['thumb_url']);
    }
    if ($row['img_original'] != '' && is_file('../' . $row['img_original']))
    {
        @unlink('../' . $row['img_original']);
    }

    /* 删除数据 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('hs_gallery') . " WHERE img_id = '$img_id' LIMIT 1";
    $GLOBALS['db']->query($sql);

    clear_cache_files();
    make_json_result($img_id);
}

function list_link()
{
    $href = 'news.php?act=list';

    $text = '新聞清單';

    return array('href' => $href, 'text' => $text);
}

/**
 * 添加链接
 * @param   string  $extension_code 虚拟商品扩展代码，实体商品为空
 * @return  array('href' => $href, 'text' => $text)
 */
function add_link()
{
    $href = 'news.php?act=add';

    $text = $GLOBALS['_LANG']['exchange_add'];

    return array('href' => $href, 'text' => $text);
}

function news_list()
{
    $result = get_filter();

    if ($result === false)
    {
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $where .= " AND (goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }

        /* 记录总数 */
        $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('hs_news'). " AS g WHERE hs_id=".$_SESSION['user_id']. $where;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        $sql = "SELECT * " .
                    " FROM " . $GLOBALS['ecs']->table('hs_news') . " AS g WHERE hs_id=".$_SESSION['user_id']. $where .
                    " ORDER BY $filter[sort_by] $filter[sort_order] ".
                    " LIMIT " . $filter['start'] . ",$filter[page_size]";

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql, $param_str);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $row = $GLOBALS['db']->getAll($sql);

    return array('news' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

?>