<?php
/**
 * 处理催更票
 * 运行时间：1 2 * * *
 */
require_once 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)
    {
        exit(0);
    }
    $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)";
    $item = $db->setQueryString($sql)->find(true);
    
    //iCredits::single($item['author_id'], $item['author'])->addMoney($item['price']);
    $iCredits = iCredits::single($item['author_id'],$item['author']);
    $iCredits->setUid($item['author_id']);
    $iCredits->setUserName($item['author']);
    $iCredits->addMoney($item['price'],false,false);
    $iCredits->log($item['author_id'],$item['author'],'BookUrge');
    
    $books = fetchBookInfo($bookId);
    $subject = '[系统消息]您获得了催更票奖励';
    $message =  '您的小说《'.$books['bookname'].'》'.$date.'日更新'.$size.'字，总共获得'.$item['price'].'催更奖励';
    $did = MessageData::single()->create($subject,$message);
    Message::single()->send($did, 1, 'admin', $item['author_id']);
    
    # 将不符合条件的催更票扣除20%手续费后返还
    $sql = "SELECT uid,username,price FROM " .Bookurge::table(). " WHERE bid = $bookId AND `date` = '$date' AND `price` NOT IN ($in)";
    $returns = $db->setQueryString($sql)->find(true);
    if (!empty($returns))
    {
        foreach ($returns as $return)
        {
            //iCredits::single($return['uid'], $return['username'])->addMoney((0.8 * $return['price']));
            $iCredits = iCredits::single($return['uid'],$return['username']);
            $iCredits->setUid($return['uid']);
            $iCredits->setUserName($return['username']);
            $iCredits->addMoney((0.8 * $return['price']),false,false);
            $iCredits->log($return['uid'],$return['username'],'BookUrgeReturn');
        }
    }
}