<?php

/**
 * ECSHOP 管理中心赠品管理
 * ============================================================================
 * 版权所有 (C) 2005-2007 北京亿商互动科技发展有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * @author:     scott ye <scott.yell@gmail.com>
 * @version:    v2.1
 * ---------------------------------------------
 * $Author: scottye $
 * $Date: 2007-04-18 14:46:42 +0800 (星期三, 18 四月 2007) $
 * $Id: gift.php 8228 2007-04-18 06:46:42Z scottye $
 */

define('IN_ECS', true);

require('includes/init.php');

$exc_type = new exchange($ecs->table("gift_type"), $db, 'gift_type_id', 'gift_type_name');

/*------------------------------------------------------ */
//-- 赠品类型列表
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
    /* 模板赋值 */
    $smarty->assign('ur_here',      $_LANG['gift_type_list']);
    $smarty->assign('action_link',  array('href' => 'gift.php?act=add', 'text' => $_LANG['add_gift_type']));
    $smarty->assign('full_page',    1);

    $gift_type_list = get_gift_type_list();

    $smarty->assign('gift_type_list',   $gift_type_list['gift_type']);
    $smarty->assign('filter',           $gift_type_list['filter']);
    $smarty->assign('record_count',     $gift_type_list['record_count']);
    $smarty->assign('page_count',       $gift_type_list['page_count']);

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

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

/*------------------------------------------------------ */
//-- 排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $gift_type_list = get_gift_type_list();

    $smarty->assign('gift_type_list',   $gift_type_list['gift_type']);
    $smarty->assign('filter',           $gift_type_list['filter']);
    $smarty->assign('record_count',     $gift_type_list['record_count']);
    $smarty->assign('page_count',       $gift_type_list['page_count']);

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

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

/*------------------------------------------------------ */
//-- 删除赠品类型
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove')
{
    $id = intval($_GET['id']);

    check_authz_json('gift_manage');

    $exc_type->drop($id);

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

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

/*------------------------------------------------------ */
//-- 编辑赠品类型名称
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_type_name')
{
    check_authz_json('gift_manage');

    $id = intval($_REQUEST['id']);
    $val = empty($_REQUEST['val']) ? '' : trim($_REQUEST['val']);

    /* 检查是否重复 */
    if (!$exc_type->is_only('gift_type_name', $val, $id))
    {
        make_json_error($_LANG['name_exist']);
    }
    else
    {
        $exc_type->edit("gift_type_name='$val'", $id);
        make_json_result(stripslashes($val));
    }
}

/*------------------------------------------------------ */
//-- 编辑赠品可选数量
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_max_count')
{
    check_authz_json('gift_manage');

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

    if ($val <= 0)
    {
        make_json_error($_LANG['max_count_zero']);
    }
    else
    {
        $exc_type->edit("max_count=$val", $id);
        make_json_result($val);
    }
}

/*------------------------------------------------------ */
//-- 添加赠品类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('gift_manage');

    /* 添加还是编辑的标识 */
    $is_add = $_REQUEST['act'] == 'add';

    /* 取得赠品类型信息 */
    if ($is_add)
    {
        /* 默认值 */
        $gift_type = array(
            'gift_type_id'      => 0,
            'gift_type_name'    => '',
            'min_amount'        => '0.00',
            'max_amount'        => '0.00',
            'max_count'         => '1',
            'start_date'        => date('Y-m-d'),
            'end_date'          => date('Y-m-d', time() + date('t') * 86400),
        );
    }
    else
    {
        $sql = "SELECT * FROM " . $ecs->table('gift_type') . " WHERE gift_type_id = '$_REQUEST[gift_type_id]'";
        $gift_type = $db->getRow($sql);
        $tmp = unserialize($gift_type['param']);
        if (is_array($tmp))
        {
            $gift_type['max_amount'] = $tmp['max_amount'];
            $gift_type['min_amount'] = $tmp['min_amount'];
        }
    }

    /* 模板赋值 */
    $smarty->assign('ur_here', $is_add ? $_LANG['add_gift_type'] : $_LANG['edit_gift_type']);
    $smarty->assign('action_link',  array('href' => 'gift.php?act=list', 'text' => $_LANG['gift_type_list']));
    $smarty->assign('gift_type',    $gift_type);
    $smarty->assign('form_act',     $is_add ? 'insert' : 'update');

    /* 显示赠品类型信息页面 */
    assign_query_info();
    $smarty->display('gift_type_info.htm');
}

/*------------------------------------------------------ */
//-- 提交赠品类型
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('gift_manage');

    /* 插入还是更新的标识 */
    $is_insert = $_REQUEST['act'] == 'insert';
    $param = array('max_amount' => $_POST['max_amount'], 'min_amount' => $_POST['min_amount']);

    /* 检查名称是否重复 */
    if (!type_is_only($_POST['gift_type_id'], $_POST['gift_type_name']))
    {
        sys_msg($_LANG['name_exist'], 1);
    }

    $start_date = $_POST['startYear'] . '-' . $_POST['startMonth'] . '-' . $_POST['startDay'];
    $end_date = $_POST['endYear'] . '-' . $_POST['endMonth'] . '-' . $_POST['endDay'];

    /* 入库 */
    if ($is_insert)
    {
        $sql = "INSERT INTO " . $ecs->table('gift_type') . " ( ".
                    "gift_type_name, send_type, param, max_count, start_date, end_date " .
                ") VALUES (".
                    "'$_POST[gift_type_name]', '" . GIFT_BY_ORDER . "', '". serialize($param)."',".
                    "'$_POST[max_count]', '$start_date',".
                    "'$end_date') ";
    }
    else
    {
        $sql = "UPDATE " . $ecs->table('gift_type') . " SET " .
                    "gift_type_name = '$_POST[gift_type_name]', " .
                    "param = '".serialize($param)."', " .
                    "max_count = '$_POST[max_count]', " .
                    "start_date = '$start_date',".
                    "end_date ='$end_date'".
                "WHERE gift_type_id = '$_REQUEST[gift_type_id]' LIMIT 1";
    }
    $db->query($sql);

    /* 记录日志 */
    if ($is_insert)
    {
        admin_log($_POST['gift_type_name'], 'add', 'gift_type');
    }
    else
    {
        admin_log($_POST['gift_type_name'], 'edit', 'gift_type');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示页面 */
    if ($is_insert)
    {
        $link[] = array('text' => $_LANG['continue_add_gift_type'], 'href' => 'gift.php?act=add');
    }
    $link[] = array('text' => $_LANG['back_gift_type_list'], 'href' => 'gift.php?act=list');
    sys_msg($is_insert ? $_LANG['add_gift_type_ok'] : $_LANG['edit_gift_type_ok'], 0, $link);
}

/*------------------------------------------------------ */
//-- 批量删除赠品类型
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch')
{
    /* 检查权限 */
    admin_priv('gift_manage');

    if (isset($_POST['checkboxes']))
    {
        /* 取得要操作的赠品类型编号 */
        foreach ($_POST['checkboxes'] AS $key => $id)
        {
            $sql = "DELETE FROM " . $ecs->table('gift_type') . " WHERE gift_type_id='$id'";
            $result = $db->query($sql);
        }

        clear_cache_files(); /* 清除缓存 */
        admin_log('', 'batch_remove', 'gift_type'); /* 记录日志 */

        /* 提示信息 */
        $link[] = array('text' => $_LANG['back_type_list'], 'href'=>'gift.php?act=list');
        sys_msg($_LANG['batch_drop_ok'], 0, $link);
    }
    else
    {
        /* 提示信息 */
        $link[] = array('text' => $_LANG['back_type_list'], 'href'=>'gift.php?act=list');
        sys_msg($_LANG['no_select_gifttype'], 0, $link);
    }
}

/*------------------------------------------------------ */
//-- 某赠品类型的赠品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'gift_list')
{
    /* 检查权限 */
    admin_priv('gift_manage');

    /* 查询赠品类型信息 */
    $sql = "SELECT gift_type_id, gift_type_name FROM " . $ecs->table('gift_type') . " WHERE gift_type_id = '$_REQUEST[gift_type_id]'";
    $gift_type = $db->getRow($sql);

    /* 查询该类型的赠品列表 */
    $gift_list = get_gift_goods($_REQUEST['gift_type_id']);

    /* 查询其他类型的赠品列表 */
    $sql = "SELECT goods_id FROM " . $ecs->table('gift') . " WHERE gift_type_id <> '$_REQUEST[gift_type_id]'";
    $other_gift_list = $db->getCol($sql);
    $smarty->assign('other_gifts', join(',', $other_gift_list));

    /* 模板赋值 */
    $smarty->assign('ur_here', sprintf($_LANG['type_gift_list'], $gift_type['gift_type_name']));
    $smarty->assign('action_link', array('href' => 'gift.php?act=list', 'text' => $_LANG['gift_type_list']));
    $smarty->assign('cat_list', cat_list());
    $smarty->assign('brand_list', get_brand_list());
    $smarty->assign('gift_type', $gift_type);
    $smarty->assign('gift_list', $gift_list);

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

/*------------------------------------------------------ */
//-- 查询商品列表
/*------------------------------------------------------ */

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

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

    $arr = get_goods_list($filters);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value'  => $val['goods_id'],
                        'text'  => $val['goods_name'],
                        'data'  => $val['shop_price']);
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 添加赠品
/*------------------------------------------------------ */

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

    check_authz_json('gift_manage');

    $gifts      = $json->decode($_GET['add_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $type_id    = $arguments[0];
    $price      = $arguments[1];

    foreach ($gifts AS $val)
    {
        $sql = "INSERT INTO " .$ecs->table('gift'). " (gift_type_id, goods_id, goods_price) ".
                "VALUES ('$type_id', '$val', '$price')";

        if ($db->query($sql) === false)
        {
            $msg = ($db->errno() == 1062) ? $_LANG['gift_already_in_type'] : $db->error();

            make_json_error($msg.'dd');
        }
        else
        {
            change_is_gift($val, '1') or make_json_error($db->error());
        }
    }

    $arr = get_gift_goods($type_id);
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['goods_id'],
                        'text'      => $val['goods_name'] . ' --- [' .$val['goods_price']. ']',
                        'data'      => '');
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 删除一个赠品
/*------------------------------------------------------ */

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

    check_authz_json('gift_manage');

    $gifts      = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $type_id    = $arguments[0];

    $sql = "DELETE FROM " .$ecs->table('gift'). " WHERE gift_type_id='$type_id' AND " . db_create_in($gifts, 'goods_id');
    $db->query($sql, 'SILENT') or make_json_error($db->error());

    $arr = get_gift_goods($type_id);
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['goods_id'],
                        'text'      => $val['goods_name'],
                        'data'      => '');
    }

    make_json_result($opt);
}

/**
 * 获得赠品类型列表
 * @return   array
 */
function get_gift_type_list()
{
    /* 生成过滤条件 */
    $filter = array();
    $filter['gift_type_name'] = empty($_REQUEST['gift_type_name']) ? '' : trim($_REQUEST['gift_type_name']);
    $filter['sort_by']        = empty($_REQUEST['sort_by']) ? 'end_date' : trim($_REQUEST['sort_by']);
    $filter['sort_order']     = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

    $where = !empty($filter['gift_type_name']) ? " WHERE gift_type_name LIKE '%" . mysql_like_quote($filter['gift_type_name']) . "%' " : '';
    
    /* 记录总数 */
    $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('gift_type') . $where;
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);

    $filter = page_and_size($filter);

    /* 查询 */
    $arr = array();
    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('gift_type') . $where .
            " ORDER BY " . $filter['sort_by'] . " " . $filter['sort_order'];
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $param = unserialize($row['param']);
        $row['amount_range'] = $param['max_amount'] == 0 ?
            sprintf($GLOBALS['_LANG']['upward_of'], $param['min_amount']) :
            $param['min_amount'] . ' - ' . $param['max_amount'];
        $arr[] = $row;
    }
    $filter['gift_type_name'] = stripslashes($filter['gift_type_name']);

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

/**
 * 获得指定类型的所有赠品
 *
 * @access  public
 * @param   integer $type_id
 * @return  void
 */
function get_gift_goods($type_id)
{
    /* 查询该类型的赠品列表 */
    $sql = "SELECT go.goods_id, go.goods_name, gi.goods_price " .
            "FROM " .$GLOBALS['ecs']->table('gift') . " AS gi, " .
                $GLOBALS['ecs']->table('goods') . " AS go " .
            "WHERE gi.gift_type_id = '$type_id' " .
            "AND gi.goods_id = go.goods_id";
    $gift_list = $GLOBALS['db']->getAll($sql);

    return $gift_list;
}

/**
 * 更新 is_gift
 * @param   int     $goods_id   商品编号
 * @return  bool
 */
function change_is_gift($goods_id, $is_gift)
{
    $goods['is_gift'] = $is_gift;
    return $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('goods'), $goods, 'UPDATE', "goods_id = '$goods_id'");
}

function type_is_only($type_id, $name)
{
    $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('gift_type') .
            " WHERE gift_type_name = '$name' " .
            " AND gift_type_id <> '$type_id' ";
    return $GLOBALS['db']->getOne($sql) <= 0;
}

?>