<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
require_once dirname(dirname(__FILE__)) . '/init.php';

$bTable = Book::table();
$bmTable = BookManagers::table();
$bfTabke = BookForum::table();
$mTable = Members::table();
$mfTable = Memberfields::table();

if (date('d') == '01')
{
    $db->query('UPDATE '.SoftContents::table().' SET month_download = 0');

	$db->query("UPDATE `{$bTable}` SET `month` = 0, `m_red` = 0, `m_black` = 0, u_m_click = 0, u_v_m_click = 0");
	$db->query("UPDATE `{$mTable}` SET extcredits5 = if (extcredits1 >= 1000 AND extcredits1 < 5000 , 1, if (extcredits1 >= 5000 AND extcredits1 < 20000, 2, if (extcredits1 >=20000 AND extcredits1 < 50000, 3, if (extcredits1 >= 50000, 4, 0))))");

    $bmwages = setting('bmwages');
    if ($bmwages)
    {
        $bookmanages = $db->select()
                          ->from($bmTable)
                          ->leftjoin($bfTabke, 'bookforum.bookid=bookmanage.bookid')
                          ->where(array('status'=>1))
                          ->find();
        if (!empty($bookmanages))
        {
            foreach ($bookmanages as $bookmanage)
            {
                $uid = $bookmanage['uid'];
                $username = $bookmanage['username'];
                $subject = '[系统消息]发放上月书管工资';
                $content = '感谢您一个月来对书会《' . filter_content($bookmanage['forumname']) . '》的繁荣做出的努力，特奖励'.$bmwages.setting('creditname').'以做鼓励！^_^';
                $did = MessageData::single()->create($subject, $content);
                Message::single()->send($did, 1, 'admin', $uid);
                $iCredits = iCredits::single($uid,$username);
                $iCredits->setUid($uid);
                $iCredits->setUserName($username);
                $iCredits->addMoney($bmwages,false,false);
                $iCredits->log($uid,$username,$bmwages,'BookBM');
            }
        }
    }

    $sbmwages = setting('sbmwages');
    if ($sbmwages)
    {
        $suppers = $db->select()->from($mTable)->where(array('groupid'=>6))->find();
        if (!empty($suppers))
        {
            foreach ($suppers as $supper)
            {
                $uid = $supper['uid'];
                $username = userName($uid);
                $subject = '[系统消息]发放上月超管工资';
                $content = '感谢您一个月来对书城繁荣做出的努力，特奖励'.$sbmwages.setting('creditname').'以做鼓励！^_^';
                $did = MessageData::single()->create($subject, $content);
                Message::single()->send($did, 1, 'admin', $uid);
                $iCredits = iCredits::single($uid, $username);
                $iCredits->setUid($uid);
                $iCredits->setUserName($username);
                $iCredits->addMoney($sbmwages, false, false);
                $iCredits->log($uid,$username, $sbmwages, 'SuperBM');
            }
        }
    }
    
    $array = array(
        1 => array('forum'=>10000,'manager'=>5000),
        2 => array('forum'=>8000,'manager'=>4000),
        3 => array('forum'=>5000,'manager'=>3000),
        4 => array('forum'=>4000,'manager'=>2000),
        5 => array('forum'=>3000,'manager'=>1000),
    );
    $sql = "SELECT * FROM `{$bfTabke}` WHERE bookid NOT IN (13089,16212) ORDER BY (monthmcount + monthposts + monthdigests * 2) DESC, monthmcount DESC LIMIT 10";
	$forums = $db->setQueryString($sql)->find();
    $i = 1;
	foreach ($forums as $forum)
	{
	    $forumid = $forum['bookid'];
	    $mcount = $forum['monthmcount'];
	    $digests = $forum['monthdigests'];
	    $posts = $forum['monthposts'];
	    $date = getPrevMonth();
	    $db->insert(BookForumMonth::table())->value(array('forumid'=>$forumid,'mcount'=>$mcount,'digests'=>$digests,'posts'=>$posts,'date'=>$date))->q();

	    if (5 >= $i)
	    {
            $credits = isset($array[$i]) ? $array[$i] : $array[5];
    	    $sql = "SELECT * FROM {$bmTable} AS BE INNER JOIN {$bfTabke} AS BM ON BM.bookid = BE.bookid WHERE BM.bookid = $forumid AND BE.status=1";
    	    $items = $db->setQueryString($sql)->find();
    	    if (!empty($items))
    	    {
    	        foreach ($items as $item)
    	        {
    	            $uid = $item['uid'];
    	            $username = Members::single()->getNameByUid($uid);
    	            $subject = '[系统消息]发放上月书会争霸前5名书会书管奖励';
        		    $message = '您管理的书会在上个月的书会争霸赛中杀入前5名，奖励'.$credits['manager'].'分，同时书会获得'.$credits['forum'].'活动积分^_^';
                    $did = MessageData::single()->create($subject,$message);
                    Message::single()->send($did,1,'admin',$uid);
                    
                    $iCredits = iCredits::single($uid,$username);
                    $iCredits->setUid($uid);
        		    $iCredits->setUserName($username);
                    $iCredits->addMoney($credits['manager'],false,false);
                    $iCredits->log($uid, $username, $credits['manager'], 'BookForumMonth');
    	        }
    
                BookForum::single()->addSelf(array('income'=>$credits['forum']),$forumid);
    	    }
	    }
        $i++;
	}
    
    $db->query("UPDATE {$bfTabke} SET monthadvance = 0, monthmcount = 0, monthdigests = 0, monthposts = 0, todayposts = 0");

    $bookforums = $db->select(array('bookid'))->from(BookForum::table())->find();
    if (!empty($bookforums))
    {
        foreach ($bookforums as $bookforum)
        {
            $bookId = $bookforum['bookid'];
            $bpTable = BookPost::table($bookId);
            $count = $db->getValue("SELECT COUNT(*) FROM {$bpTable} WHERE bookid = $bookId");
            $digestCount = $db->getValue("SELECT COUNT(*) FROM {$bpTable} WHERE bookid = $bookId AND digest = 1");
            $advanceCount = $db->getValue("SELECT COUNT(*) FROM {$bpTable} WHERE bookid = $bookId AND isadvance = 1");
            $db->update($bfTabke)->value(array('posts'=>$count,'digests'=>$digestCount,'advance'=>$advanceCount))->where('bookid='.$bookId)->q();
            updateBookForum($bookId);
        }
    }
}

function getPrevMonth()
{
    $tmp_date = date("Ym");
    $tmp_year = substr($tmp_date,0,4);
    $tmp_mon = substr($tmp_date,4,2);
    $tmp_nextmonth = mktime(0,0,0,$tmp_mon+1,1,$tmp_year);
    $tmp_forwardmonth = mktime(0,0,0,$tmp_mon-1,1,$tmp_year);
    
    return date("Ym",$tmp_forwardmonth);
}