<?php

/**
 * ECSHOP 夺宝奇兵管理程序
 * ============================================================================
 * 版权所有 (C) 2005-2007 北京亿商互动科技发展有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * @author:     wj
 * @version:    v2.1
 * ---------------------------------------------
 * $Author: paulgao $
 * $Date: 2007-04-19 18:11:35 +0800 (星期四, 19 四月 2007) $
 * $Id: snatch.php 8272 2007-04-19 10:11:35Z paulgao $
*/

define('IN_ECS', true);

require('includes/init.php');
$exc = new exchange($ecs->table("snatch"), $db, 'snatch_id', 'snatch_name');
$activity_exc = new exchange($ecs->table('activity'), $db, 'activity_id', 'name');

/*------------------------------------------------------ */
//-- 添加活动
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'add')
{
    /* 权限判断 */
    admin_priv('snatch_manage');

    /* 初始化信息 */
    $start_time = date("Y-m-d H:i:s");
    $end_time   = date('Y-m-d H:i:s', strtotime('+1 week'));
    $snatch     = array('min_price'=>'1.00','max_price'=>'800.00','price'=>'0', 'integral'=>'1','start_time' => $start_time,'end_time' => $end_time,'option'=>'<option value="0">'.$_LANG['make_option'].'</option>');

    $smarty->assign('snatch',       $snatch);
    $smarty->assign('ur_here',      $_LANG['snatch_add']);
    $smarty->assign('action_link',  array('text' => $_LANG['02_snatch_list'], 'href'=>'snatch.php?act=list'));
    $smarty->assign('cat_list',     cat_list());
    $smarty->assign('brand_list',   get_brand_list());
    $smarty->assign('form_action',  'insert');

    assign_query_info();
    $smarty->display('snatch_info.htm');
}

elseif ($_REQUEST['act'] =='insert')
{
    /* 权限判断 */
    admin_priv('snatch_manage');

    /* 检查商品是否存在 */
    $sql = "SELECT goods_name FROM ".$ecs->table('goods')." WHERE goods_id = '$_POST[goods_id]'";
    $goods_name = $db->GetOne($sql);
    if (empty($goods_name))
    {
        sys_msg($_LANG['no_goods'], 1);
        exit;
    }

    /* 检查活动名是否重复 */
    $activity_exc -> is_only('name',$_POST['snatch_name'], $_LANG['snatch_name_exist'] );

    /* 将时间转换成整数 */
    $_POST['start_time'] = strtotime($_POST['start_time']);
    $_POST['end_time']   = strtotime($_POST['end_time']);

    /* 处理提交数据 */
    if (empty($_POST['goods_id']))
    {
        $_POST['goods_id'] = 0;
    }
    if (empty($_POST['min_price']))
    {
        $_POST['min_price'] = 0;
    }
    if (empty($_POST['max_price']))
    {
        $_POST['max_price'] = 0;
    }
    if (empty($_POST['price']))
    {
        $_POST['price'] = 0;
    }
    if (empty($_POST['integral']))
    {
        $_POST['integral'] = 0;
    }

    /* 插入数据 */
    $record = array('action_code'=>'snatch','name' => $_POST['snatch_name'], 'start_time' => $_POST['start_time'], 'end_time' => $_POST['end_time'], 'description' => $_POST['desc']);

    $db->AutoExecute($ecs->table('activity'),$record,'INSERT');

    $record = array('activity_id' => $db->Insert_ID(), 'goods_id' => $_POST['goods_id'], 'min_price' => $_POST['min_price'],'max_price' => $_POST['max_price'], 'price' => $_POST['price'], 'integral' => $_POST['integral']);
    $db->AutoExecute($ecs->table('snatch'), $record,'INSERT');

    admin_log($_POST['snatch_name'],'add','snatch');
    $link[] = array('text' => $_LANG['back_list'], 'href'=>'snatch.php?act=list');
    $link[] = array('text' => $_LANG['continue_add'], 'href'=>'snatch.php?act=add');
    sys_msg($_LANG['add_succeed'],0,$link);
}

/*------------------------------------------------------ */
//-- 活动列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'list')
{
    $smarty->assign('ur_here',      $_LANG['02_snatch_list']);
    $smarty->assign('action_link',  array('text' => $_LANG['snatch_add'], 'href'=>'snatch.php?act=add'));

    $snatchs = get_snatchlist();

    $smarty->assign('snatch_list',  $snatchs['snatchs']);
    $smarty->assign('filter',       $snatchs['filter']);
    $smarty->assign('record_count', $snatchs['record_count']);
    $smarty->assign('page_count',   $snatchs['page_count']);

    $sort_flag  = sort_flag($snatchs['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    $smarty->assign('full_page',    1);
    assign_query_info();
    $smarty->display('snatch_list.htm');
}

/*------------------------------------------------------ */
//-- 查询、翻页、排序
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'query')
{
    $snatchs = get_snatchlist();

    $smarty->assign('snatch_list',  $snatchs['snatchs']);
    $smarty->assign('filter',       $snatchs['filter']);
    $smarty->assign('record_count', $snatchs['record_count']);
    $smarty->assign('page_count',   $snatchs['page_count']);

    $sort_flag  = sort_flag($snatchs['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

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

/*------------------------------------------------------ */
//-- 编辑活动名称
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_snatch_name')
{
    check_authz_json('snatch_manage');

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

    /* 检查名称是否重复 */
    if (!$activity_exc->is_only('name', $val, $id, "action_code<>'snatch'"))
    {
        make_json_error($_LANG['snatch_name_exist']);
    }
    else
    {
        $activity_exc->edit("name='$val'", $id);

        make_json_result(stripslashes($val));
    }
}

/*------------------------------------------------------ */
//-- 编辑价格下限
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_min_price')
{
    check_authz_json('snatch_manage');

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

    $exc->edit("min_price='$val'", $id);

    make_json_result(number_format($val, 2));
}

/*------------------------------------------------------ */
//-- 编辑消耗的积分
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_inegral')
{
    check_authz_json('snatch_manage');

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

    $exc->edit("integral='$val'", $id);

    make_json_result($val);
}

/*------------------------------------------------------ */
//-- 编辑起始时间
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_start_time')
{
    check_authz_json('snatch_manage');

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

    /* 检查格式 */
    if (!is_time($val))
    {
        make_json_error($_LANG['js_languages']['invalid_starttime']);
    }

    /* 将时间转成整数 */
    $time= strtotime($val);

    $activity_exc->edit("start_time='$time'", $id);

    make_json_result(date("Y-m-d H:i:s", $time));
}

/*------------------------------------------------------ */
//-- 编辑结束时间
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_end_time')
{
    check_authz_json('snatch_manage');

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

    /* 检查格式 */
    if (!is_time($val))
    {
        make_json_error($_LANG['js_languages']['invalid_starttime']);
    }

    /* 将时间转成整数 */
    $time= strtotime($val);

    $activity_exc->edit("end_time='$time'", $id);

    make_json_result(date("Y-m-d H:i:s", $time));
}

/*------------------------------------------------------ */
//-- 删除指定的活动
/*------------------------------------------------------ */

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

    $id = intval($_GET['id']);

    $aid = $exc->get_name($id, 'activity_id');

    $exc->drop($id);
    $activity_exc->drop($aid);

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

    header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 编辑活动
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit')
{
    /* 权限判断 */
    admin_priv('snatch_manage');

    $snatch        = get_snatch_info($_REQUEST['id']);
    $snatch['option'] = '<option value="'.$snatch['goods_id'].'">'.$snatch['goods_name'].'</option>';
    $smarty->assign('snatch',       $snatch);
    $smarty->assign('ur_here',      $_LANG['snatch_edit']);
    $smarty->assign('action_link',  array('text' => $_LANG['02_snatch_list'], 'href'=>'snatch.php?act=list'));
    $smarty->assign('form_action',   'update');

    assign_query_info();
    $smarty->display('snatch_info.htm');

}
elseif ($_REQUEST['act'] =='update')
{
    /* 权限判断 */
    admin_priv('snatch_manage');

    /* 检查重名 */
    if (!$activity_exc->is_only('name', $_POST['snatch_name'], $_POST['id'], "action_code<>'snatch'"))
    {
        sys_msg($_LANG['snatch_name_exist'], 1);
    }

    /* 将时间转换成整数 */
    $_POST['start_time'] = strtotime($_POST['start_time']);
    $_POST['end_time']   = strtotime($_POST['end_time']);

    /* 处理提交数据 */
    if (empty($_POST['goods_id']))
    {
        $_POST['goods_id'] = 0;
    }
    if (empty($_POST['min_price']))
    {
        $_POST['min_price'] = 0;
    }
    if (empty($_POST['max_price']))
    {
        $_POST['max_price'] = 0;
    }
    if (empty($_POST['price']))
    {
        $_POST['price'] = 0;
    }
    if (empty($_POST['integral']))
    {
        $_POST['integral'] = 0;
    }

    /* 更新数据 */
    $record = array('name' => $_POST['snatch_name'], 'start_time' => $_POST['start_time'], 'end_time' => $_POST['end_time'], 'description' => $_POST['desc']);
    $db->AutoExecute($ecs->table('activity'),$record,'UPDATE', "activity_id = '$_POST[activity_id]'");

    $record = array('goods_id' => $_POST['goods_id'], 'min_price' => $_POST['min_price'], 'max_price' => $_POST['max_price'], 'price' => $_POST['price'], 'integral' => $_POST['integral']);
    $db->AutoExecute($ecs->table('snatch'), $record,'UPDATE', "snatch_id = '$_POST[id]'");

    admin_log($_POST['snatch_name'],'edit','snatch');
    $link[] = array('text' => $_LANG['back_list'], 'href'=>'snatch.php?act=list');
    sys_msg($_LANG['edit_succeed'],0,$link);
 }

/*------------------------------------------------------ */
//-- 查看活动详情
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'view')
{
    /* 权限判断 */
    admin_priv('snatch_manage');

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

    $bid_list = get_snatch_detail();

    $smarty->assign('bid_list',     $bid_list['bid']);
    $smarty->assign('filter',       $bid_list['filter']);
    $smarty->assign('record_count', $bid_list['record_count']);
    $smarty->assign('page_count',   $bid_list['page_count']);

    $sort_flag  = sort_flag($bid_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    /* 赋值 */
    $smarty->assign('info',         get_snatch_info($id));
    $smarty->assign('full_page',    1);
    $smarty->assign('result',       get_snatch_result($id));
    $smarty->assign('ur_here',      $_LANG['view_detail'] );
    $smarty->assign('action_link',  array('text' => $_LANG['02_snatch_list'], 'href'=>'snatch.php?act=list'));
    $smarty->display('snatch_view.htm');
}

/*------------------------------------------------------ */
//-- 排序、翻页活动详情
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'query_bid')
{
    $bid_list = get_snatch_detail();

    $smarty->assign('bid_list',     $bid_list['bid']);
    $smarty->assign('filter',       $bid_list['filter']);
    $smarty->assign('record_count', $bid_list['record_count']);
    $smarty->assign('page_count',   $bid_list['page_count']);

    $sort_flag  = sort_flag($bid_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

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

/*------------------------------------------------------ */
//-- 搜索商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'search_goods')
{
    include_once('../includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);

    make_json_result($arr);
}

/**
 * 获取活动列表
 *
 * @access  public
 *
 * @return void
 */
function get_snatchlist()
{
    /* 查询条件 */
    $filter['keywords']   = empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
    $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 's.snatch_id' : trim($_REQUEST['sort_by']);
    $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

    $where = (!empty($filter['keywords'])) ? " AND name like '%". mysql_like_quote($filter['keywords']) ."%'" : '';

    $sql = "SELECT count(*) FROM ".$GLOBALS['ecs']->table('snatch')." AS s,".
            $GLOBALS['ecs']->table('activity')." AS a WHERE s.activity_id = a.activity_id $where";
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);

    $filter = page_and_size($filter);

    /* 获活动数据 */
    $sql = "SELECT a.activity_id, s.snatch_id, a.name AS snatch_name, g.goods_name, ".
                "a.start_time, a.end_time, s.min_price, s.integral ".
            "FROM ".$GLOBALS['ecs']->table('snatch')." AS s, ".$GLOBALS['ecs']->table('goods')." AS g, ".$GLOBALS['ecs']->table('activity')." AS a ".
            "WHERE s.goods_id = g.goods_id AND s.activity_id = a.activity_id $where ".
            "ORDER by $filter[sort_by] $filter[sort_order] LIMIT ". $filter['start'] .", " . $filter['page_size'];
    $row = $GLOBALS['db']->getAll($sql);

    foreach ($row AS $key => $val)
    {
        $row[$key]['start_time'] = date($GLOBALS['_CFG']['time_format'], $val['start_time']);
        $row[$key]['end_time']   = date($GLOBALS['_CFG']['time_format'], $val['end_time']);
    }
    $filter['keywords'] = stripslashes($filter['keywords']);
    $arr = array('snatchs' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}

/**
 * 获取指定id snatch 的信息
 *
 * @access  public
 * @param   int         $id         snatch_id
 *
 * @return array       array(snatch_id, snatch_name, goods_id,start_time, end_time, min_price, integral)
 */
function get_snatch_info($id)
{
    global $ecs, $db,$_CFG;

    $sql = "SELECT T1.snatch_id,T1.activity_id,  T2.name AS snatch_name, T1.goods_id , T3.goods_name, T2.start_time, T2.end_time, T1.min_price, T1.max_price, T1.price , T1.integral, T2.description AS 'desc'  FROM " .$ecs->table('snatch')." AS T1, ".$ecs->table('activity')." AS T2 ,".$ecs->table('goods')." AS T3  WHERE T1.activity_id = T2.activity_id AND T1.goods_id = T3.goods_id AND snatch_id='$id'";
    $snatch = $db->GetRow($sql);

    /* 将时间转成可阅读格式 */
    $snatch['start_time'] = date("Y-m-d H:i:s", $snatch['start_time']);
    $snatch['end_time']   = date("Y-m-d H:i:s", $snatch['end_time']);

    return $snatch;
}

/**
 * 返回活动详细列表
 *
 * @access  public
 *
 * @return array
 */
function get_snatch_detail()
{
    $filter['snatch_id']  = empty($_REQUEST['snatch_id']) ? 0 : intval($_REQUEST['snatch_id']);
    $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'bid_time' : trim($_REQUEST['sort_by']);
    $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

    $where = empty($filter['snatch_id']) ? '' : " WHERE snatch_id='$filter[snatch_id]'";

    /* 获得记录总数以及总页数 */
    $sql = "SELECT count(*) FROM ".$GLOBALS['ecs']->table('snatch_log'). $where;
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);

    $filter = page_and_size($filter);

    /* 获得活动数据 */
    $sql = "SELECT s.log_id, u.user_name, s.bid_price, s.bid_time ".
            " FROM ".$GLOBALS['ecs']->table('snatch_log')." AS s ".
            " LEFT JOIN ".$GLOBALS['ecs']->table('users')." AS u ON s.user_id = u.user_id  ". $where.
            " ORDER by ".$filter['sort_by']." ".$filter['sort_order'].
            " LIMIT ". $filter['start'] .", " . $filter['page_size'];
    $row = $GLOBALS['db']->getAll($sql);

    foreach ($row AS $key => $val)
    {
        $row[$key]['bid_time'] = date($GLOBALS['_CFG']['time_format'], $val['bid_time']);
    }

    $arr = array('bid' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}

?>