<?php
/**
 * 处理催更票
 * 运行时间：1 2 * * *
 */
require_once dirname(dirname(dirname(__FILE__))) . '/init.php';

$date = date("Y-m-d" , strtotime("-1 day"));
$sql = "SELECT bid FROM ".Bookurge::table()." WHERE `date` = '$date' GROUP BY bid";
$result = $db->setQueryString($sql)->find();
if (empty($result))
{
    exit(0);
}
foreach ($result as $book)
{
    $bookId = $book['bid'];
    $size = $db->getValue("SELECT SUM(`size`) AS `size` FROM `".Chapter::table()."` WHERE bookid = $bookId AND `date` = '$date'");
    if (empty($size) || $size < 2000)
    {
        returnMoney($bookId, $date);
        continue;
    }
    $array = array(200);
    if ($size >= 3000)
    {
        $array[] = 300;
    }
    if ($size >= 4000)
    {
        $array[] = 400;
    }
    if ($size >= 5000)
    {
        $array[] = 500;
    }
    
    $in = implode(',', $array);
    $sql = "SELECT SUM(price) AS price, author_id FROM ".Bookurge::table()." WHERE bid = $bookId AND `date` = '$date' AND `price` IN ($in) AND `status` = 0";
    $item = $db->setQueryString($sql)->find(true);
    
    if (!empty($item['price']))
    {
        $authorName = userName($item['author_id']);
        $iCredits = iCredits::single($item['author_id'], $authorName);
        $iCredits->setUid($item['author_id']);
        $iCredits->setUserName($authorName);
        $iCredits->addMoney($item['price'], false, false);
        $iCredits->log($item['author_id'], $authorName, 'BookUrge');
        
        $books = fetchBookInfo($bookId);
        $subject = '[系统消息]您获得了催更票奖励';
        $message =  '您的小说《'.$books['bookname'].'》'.$date.'日更新'.$size.'字，总共获得'.$item['price'].'催更奖励';
        Members::sendMessage($subject,$message, 1, 'admin', $item['author_id']);
    }
    
    returnMoney($bookId, $date, $in);
}

/**
 * 将不符合条件的催更票扣除20%手续费后返还
 * @return void
 */
function returnMoney($bookId, $date, $condition = '')
{
    $condition = empty($condition) ? '' : ' AND `price` NOT IN ('.$condition.')';
    $sql = "SELECT SUM(price) AS price, uid FROM ".Bookurge::table()." WHERE bid = $bookId AND `date` = '$date' AND status = 0 {$condition} GROUP BY uid";
    $returns = $GLOBALS['db']->setQueryString($sql)->find();
    if (!empty($returns))
    {
        foreach ($returns as $return)
        {
            $userName = userName($return['uid']);
            $iCredits = iCredits::single($return['uid'], $userName);
            $iCredits->setUid($return['uid']);
            $iCredits->setUserName($userName);
            $iCredits->addMoney((0.8 * $return['price']), false, false);
            $iCredits->log($return['uid'], $userName, 'BookUrgeReturn');
        }
    }
    
    $GLOBALS['db']->update(Bookurge::table())->value(array('status' => 1))->where('bid = '.$bookId." AND date = '{$date}'")->q();
}