<?php
/**
* @author moufer<moufer@163.com>
* @copyright www.modoer.com
* @version $Id 2 2008-08-24 17:08 $
*/
!defined('IN_MUDDER') && exit('Access Denied');

function query_coupon($callid,$params) {
    global $db, $dbpre, $_config;

    $params = parseGlobal($params);
    if(empty($params)) return array();
    extract($params, EXTR_OVERWRITE);

    $cachename = sprintf("%d_%s", $callid,cacheIdentifier($params));
    $cachefile = MUDDER_ROOT.$_config['datacall_dir'].'cache_'.$cachename.'.php';

    if(file_exists($cachefile) && check_cache($cachefile, $cachetime)) {
        return read_cache($cachefile);
    }

    $from = "{$dbpre}coupons c";
    $panelcode = isset($panelcode) ? (preg_match("/^[0-9]{2}$/",$panelcode) ? $panelcode : '') : '';
    if($panelcode) {
        $from .= " LEFT JOIN {$dbpre}shops s ON(c.shopid=s.sid)";
        $panelcode && $where[] = "s.classcode BETWEEN '{$panelcode}00' AND '{$panelcode}9999'";
    }
    $where[] = "c.endtime>UNIX_TIMESTAMP() AND c.flag=1";
    $where = implode(" AND ", $where);
    $order = strip_order($order);
    $orderby = $order ? "ORDER BY $order" : '';
    $limit = ($row=intval($row)) ? "LIMIT 0,$row" : 'LIMIT 0,10';

    $query = $db->query("SELECT c.* FROM $from WHERE $where $orderby $limit");
    if($db->num_rows($query) <= 0) return array();
    while($row = $db->fetch_array($query)) {
        $result[] = $row;
    }
    $db->free_result($query);

    if($cachetime > 0) {
        write_cache($cachename, arrayeval($result), '', 'return', $_config['datacall_dir']);
    }

    return $result;
}
?>