<?php
/**
* 优惠券后台处理操作
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
* @version $Id coupon.inc.php 2 2008-08-14 07:18 $
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');

if($dosubmit) {

    if(empty($couponids)) {
        cpmsg('未选择操作对象。','admincp.php?action='.$action.'&file='.$file.'&pcd='.$pcd.'&flag='.$flag);
    } elseif($flag == 2 && empty($operation)) {
        cpmsg('未选择操作行为。','admincp.php?action='.$action.'&file='.$file.'&pcd='.$pcd.'&flag=2');
    }
    $shopids = array();
    if(is_array($couponids)) foreach($couponids as $couponid) {
        $coupon = $db->get_one("SELECT * FROM {$dbpre}coupons WHERE couponid='$couponid'");
        if(!$coupon) continue;
        if($flag == 2 && $operation == 'check') {
            $db->update("UPDATE {$dbpre}coupons SET flag=1 WHERE couponid='$couponid'");
        } else {
            $db->update("DELETE FROM {$dbpre}coupons WHERE couponid='$couponid'");
            $db->update("DELETE FROM {$dbpre}membereffect WHERE id='$couponid' AND idtype='coupon'");
        }
        !in_array($coupon['shopid'],$shopids) && $shopids[] =  $coupon['shopid'];
    }
    if($shopids) foreach($shopids as $shopid) {
        $newtotal = $db->get_value("SELECT COUNT(*) FROM {$dbpre}coupons WHERE shopid='$shopid' AND flag=1 AND endtime>UNIX_TIMESTAMP()");
        $db->update("UPDATE {$dbpre}shops SET coupons='$newtotal' WHERE sid='$shopid'");
    }
    cpmsg('您选中的优惠券已经删除完毕！');

} else {

    $coupons = $where = array();

    $flag = empty($flag) || $flag < 0 ? 1 : $flag;
    $from = "{$dbpre}coupons c LEFT JOIN {$dbpre}shops s ON(c.shopid=s.sid)";
    $pcd = isset($pcd) ? (preg_match("/^[0-9]{2}$/",$pcd) ? $pcd : '') : '';
    $pcd && $where[] = "s.classcode BETWEEN '{$pcd}00' AND '{$pcd}9999'";
    if($flag==1) {
        $where[] = "c.endtime>UNIX_TIMESTAMP() AND flag=1";
    } elseif($flag==2) {
        $where[] = "flag=2";
    } elseif($flag==3) {
        $where[] = "flag=3";
    } elseif($flag==4) {
        $where[] = "c.endtime<UNIX_TIMESTAMP()";
    }
    $where = implode(" AND ", $where);

    $total = $db->get_value("SELECT COUNT(*) FROM $from WHERE $where");
    if($total > 0) {
        $select = "c.*,s.shopname,s.subname,s.classcode,s.areacode,s.address";
        $offset = 15;
        $limit = get_limit($page, $offset);
        $orderby = "dateline DESC";
        $query = $db->query("SELECT $select FROM $from WHERE $where ORDER BY $orderby LIMIT $limit");
        while($row = $db->fetch_array($query)) {
            $row['shopname'] .= $row['subname'] ? '('.$row['subname'].')' : '';
            $coupons[] = $row;
        }
        $multiurl = "admincp.php?action=$action&pcd=$pcd&flag=$flag";
        $multipage = multi($total, $offset, $page, $multiurl);
    }

    include cptpl('list', MOD_ROOT.'./admin/templates/');
}
?>
