<?php
/******************************************************************************/
//                                                                            //
//                             InstantCMS v1.8                                //
//                        http://www.instantcms.ru/                           //
//                                                                            //
//                   written by InstantCMS Team, 2007-2010                    //
//                produced by InstantSoft, (www.instantsoft.ru)               //
//                                                                            //
//                        LICENSED BY GNU/GPL v2                              //
//                                                                            //
/******************************************************************************/

if(!defined('VALID_CMS')) { die('ACCESS DENIED'); }

class cms_model_rew{

    private $childs;

	function __construct(){
        $this->inDB = cmsDatabase::getInstance();
    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function install(){

        return true;

    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function addRew($item) {

        $item = cmsCore::callEvent('ADD_TorgRew', $item);
		
		$item['target_title'] =  $this->inDB->escape_string($item['target_title']);
$cat_id = dbGetFields('cms_torg_items', 'id='.$item['target_id'], 'category_id');
if ($item['parent_id']) {
  $item['points'] =0;
   $item['points2'] =0;
    $item['points3'] =0;
     $item['points4'] =0;
     $item['plusi'] =NULL;
   $item['minusi'] =NULL;
    $item['zametka'] =NULL;
    }			  
$sql = "INSERT INTO cms_torg_rew (parent_id, cat_id, user_id, target, target_id, 
                                          guestname, content, content_bbcode, pubdate,
                                          published,  target_title, target_link,
                                          ip, points, points2, points3, points4,
					  plusi, minusi, zametka)
                VALUES ({$item['parent_id']},{$cat_id['category_id']}, {$item['user_id']}, '{$item['target']}', {$item['target_id']},
                        '{$item['guestname']}', '{$item['content']}', '{$item['content_bbcode']}', NOW(),
                        {$item['published']}, '{$item['target_title']}', '{$item['target_link']}', '{$item['ip']}',
			'{$item['points']}','{$item['points2']}','{$item['points3']}','{$item['points4']}',
			'{$item['plusi']}','{$item['minusi']}','{$item['zametka']}')";

						
							
        $this->inDB->query($sql);
$points =  $item['points3'];					
$sql2 = "INSERT INTO cms_torg_ratings (item_id, points, user_id, ip, rew) VALUES ({$item['target_id']}, '{$points}', '{$item['user_id']}', '{$item['ip']}', 1)";
$this->inDB->query($sql2);

		
		
        $comment_id = $this->inDB->get_last_id('cms_torg_rew');

		
        return $comment_id;

    }

    public function updateRew($id, $comment) {

        if (!$id) { return false; }

        $sql = "UPDATE cms_torg_rew
                   SET content = '{$comment['content']}',
                       content_bbcode = '{$comment['content_bbcode']}'
                 WHERE id = '{$id}'
                 LIMIT 1";

       $this->inDB->query($sql);

       return true;

    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function getTargetAuthor($table, $target_id) {

        $sql = "SELECT u.id id, u.email email, p.title title
                FROM cms_users u, {$table} p
                WHERE p.user_id = u.id AND p.id = {$target_id} AND u.is_locked = 0 AND u.is_deleted = 0
                LIMIT 1";

        $result = $this->inDB->query($sql);

        if ($this->inDB->num_rows($result)!==1){ return false; }

        return $this->inDB->fetch_assoc($result);
        
    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function getRewAuthorId($comment_id) {

        return $this->inDB->get_field('cms_torg_rew', "id=$comment_id", 'user_id');

    }


    public function isAuthorNeedMail($author_id) {

        return $this->inDB->get_field('cms_user_profiles', "user_id=".$author_id, 'email_newmsg');
        
    }


/* ==================================================================================================== */
/* ==================================================================================================== */

    private function getRewChilds($comment_id) {

        $sql = "SELECT id FROM cms_torg_rew WHERE parent_id = $comment_id";

        $result = $this->inDB->query($sql);

        if (!$this->inDB->num_rows($result)) { return false; }

        while($child = $this->inDB->fetch_assoc($result)){
            $this->childs[] = $child;
            $this->getRewChilds($child['id']);
        }

        return true;

    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function deleteRew($comment_id) {

		$inCore     = cmsCore::getInstance();

        cmsCore::callEvent('DELETE_COMMENT', $comment_id);

        $this->childs = array();

        $this->getRewChilds($comment_id);

        $sql = "DELETE FROM cms_torg_rew WHERE id = $comment_id LIMIT 1";
        $this->inDB->query($sql);

		$inCore->deleteRatings('torg_rew', $comment_id);

        cmsActions::removeObjectLog('add_torg_rew', $comment_id);

        if ($this->childs){
            foreach($this->childs as $child){
                $sql = "DELETE FROM cms_torg_rew WHERE id = {$child['id']} LIMIT 1";
                $this->inDB->query($sql);
				$inCore->deleteRatings('torg_rew', $child['id']);
                cmsActions::removeObjectLog('add_torg_rew', $child['id']);
            }
        }

        return true;

    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function getRewCount($target, $target_id) {

        $sql = "SELECT id
                FROM cms_torg_rew
                WHERE target='$target' AND target_id=$target_id AND parent_id=0 AND published=1";

        $result = $this->inDB->query($sql);

        return $this->inDB->num_rows($result);

    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function getRews($target, $target_id, $cfg){

        $comments = array();

        if (!$cfg['edit_minutes']) { $cfg['edit_minutes'] = 0; }

        $sql = "SELECT c.*,
                       IFNULL(v.total_rating, 0) as votes,
					   IFNULL(u.nickname, 0) as nickname,
					   IFNULL(u.login, 0) as login,
					   IFNULL(u.is_deleted, 0) as is_deleted,
					   IFNULL(p.imageurl, 0) as imageurl,
                       (NOW() < DATE_ADD(c.pubdate, INTERVAL {$cfg['edit_minutes']} MINUTE)) as is_editable
                FROM cms_torg_rew c
                LEFT JOIN cms_ratings_total v ON v.item_id = c.id AND v.target = 'rew'
				LEFT JOIN cms_users u ON u.id = c.user_id
				LEFT JOIN cms_user_profiles p ON p.user_id = u.id
                WHERE c.target='$target' AND c.target_id=$target_id AND c.published=1
                ORDER BY c.pubdate ASC";

        $result = $this->inDB->query($sql);

        if (!$this->inDB->num_rows($result)) { return false; }

        while($comment = $this->inDB->fetch_assoc($result)){
			$comment['fpubdate'] = cmsCore::dateFormat($comment['pubdate'], true, true);
            $comments[] = $comment;
        }

        $comments = cmsCore::callEvent('GET_torg_rew', $comments);

        return $comments;

    }

    public function getRew($id, $cfg) {

        $comment = array();

        if (!$cfg['edit_minutes']) { $cfg['edit_minutes'] = 0; }

        $sql = "SELECT c.*,
                       IFNULL(v.total_rating, 0) as votes,
					   IFNULL(u.nickname, 0) as nickname,
					   IFNULL(u.login, 0) as login,
					   IFNULL(u.is_deleted, 0) as is_deleted,
					   IFNULL(p.imageurl, 0) as imageurl,
                       (NOW() < DATE_ADD(c.pubdate, INTERVAL {$cfg['edit_minutes']} MINUTE)) as is_editable
                FROM cms_torg_rew c
                LEFT JOIN cms_ratings_total v ON v.item_id = c.id AND v.target = 'rew'
				LEFT JOIN cms_users u ON u.id = c.user_id
				LEFT JOIN cms_user_profiles p ON p.user_id = u.id
                WHERE c.id='{$id}' AND c.published=1
                LIMIT 1";

        $result = $this->inDB->query($sql);

        if (!$this->inDB->num_rows($result)) { return false; }

        $comment = $this->inDB->fetch_assoc($result);

        $comments = cmsCore::callEvent('GET_torg_rew', $comment);

        return $comment;

    }
    
    
    public function getItem($id){
		global $_LANG;
        $comments = array();

        $sql = "SELECT c.id, c.guestname,c.pubdate as fpubdate, c.target_title,c.content, c.target_id, c.parent_id, c.target_link, c.ip, c.user_id,
	        c.points,c.points2,c.points3,c.points4,c.zametka,c.plusi,c.minusi,c.cat_id, cat.title as cat_title,
                       IFNULL(v.total_rating, 0) as votes,
					   IFNULL(u.nickname, 0) as nickname,
					   IFNULL(u.login, 0) as login,
					   IFNULL(u.is_deleted, 0) as is_deleted,
					   IFNULL(p.imageurl, 0) as imageurl,
					   IFNULL(p.gender, 0) as gender					   
                FROM cms_torg_rew c
                LEFT JOIN cms_ratings_total v ON v.item_id = c.id AND v.target = 'rew'
				LEFT JOIN cms_users u ON u.id = c.user_id
				LEFT JOIN cms_user_profiles p ON p.user_id = u.id
				LEFT JOIN cms_torg_cats cat ON cat.id = c.cat_id
                WHERE c.published=1 AND c.target_id='{$id}'
                ORDER BY c.id ASC";

        $result = $this->inDB->query($sql);

        if (!$this->inDB->num_rows($result)) { return false; }
		
        while($comment = $this->inDB->fetch_assoc($result)){
			$comment['fpubdate'] = cmsCore::dateFormat($comment['fpubdate'], true, true);
			switch ($comment['gender']){
            			case 'm': 	$comment['gender'] = $_LANG['COMMENTS_MALE'];
									break;
            			case 'f':	$comment['gender'] = $_LANG['COMMENTS_FEMALE'];
									break;
						default:	$comment['gender'] = $_LANG['COMMENTS_GENDER'];
			}
            $comments[] = $comment;
        }

        $comments = cmsCore::callEvent('GET_torg_rew', $comments);

        return $comments;

    }
    
/* ==================================================================================================== */
/* ==================================================================================================== */

    public function getRewAll($page=1, $perpage=10, $cat_id){
		global $_LANG;
	
	if ($cat_id) $catsql="AND c.cat_id=$cat_id";
	
        $comments = array();
	
        $sql = "SELECT c.id, c.guestname,c.pubdate as fpubdate, c.target_title, c.target_id, c.target_link, c.ip, c.user_id,
	        c.points,c.points2,c.points3,c.points4,c.zametka,c.plusi,c.minusi,c.cat_id, cat.title as cat_title,
                       IFNULL(v.total_rating, 0) as votes,
					   IFNULL(u.nickname, 0) as nickname,
					   IFNULL(u.login, 0) as login,
					   IFNULL(u.is_deleted, 0) as is_deleted,
					   IFNULL(p.imageurl, 0) as imageurl,
					   IFNULL(p.gender, 0) as gender					   
                FROM cms_torg_rew c
                LEFT JOIN cms_ratings_total v ON v.item_id = c.id AND v.target = 'rew'
				LEFT JOIN cms_users u ON u.id = c.user_id
				LEFT JOIN cms_user_profiles p ON p.user_id = u.id
				LEFT JOIN cms_torg_cats cat ON cat.id = c.cat_id
                WHERE c.published=1 AND c.parent_id=0 $catsql
                ORDER BY c.id DESC
				LIMIT ".(($page-1)*$perpage).", $perpage";

        $result = $this->inDB->query($sql);

        if (!$this->inDB->num_rows($result)) { return false; }
		
        while($comment = $this->inDB->fetch_assoc($result)){
			$comment['fpubdate'] = cmsCore::dateFormat($comment['fpubdate'], true, true);
			switch ($comment['gender']){
            			case 'm': 	$comment['gender'] = $_LANG['COMMENTS_MALE'];
									break;
            			case 'f':	$comment['gender'] = $_LANG['COMMENTS_FEMALE'];
									break;
						default:	$comment['gender'] = $_LANG['COMMENTS_GENDER'];
			}
            $comments[] = $comment;
        }

        $comments = cmsCore::callEvent('GET_torg_rew', $comments);

        return $comments;

    }

/* ==================================================================================================== */
/* ==================================================================================================== */

    public function buildTree($parent_id, $level, $comments, &$tree){
        $level++;
        foreach($comments as $num=>$comment){
            if ($comment['parent_id']==$parent_id){
                $comment['level'] = $level-1;
                $tree[] = $comment;
                $this->buildTree($comment['id'], $level, $comments, $tree);
            }
        }
    }

/* ==================================================================================================== */
/* ==================================================================================================== */


 
public function rew_cats(){
        $inCore = cmsCore::getInstance();
        $inDB = cmsDatabase::getInstance();
		$cfg = $inCore->loadModuleConfig($module_id);

		$sql = "SELECT cat.id as torg_cat_id, cat.title, COUNT(con.id) as content_count
				FROM cms_torg_cats cat, cms_torg_rew con
				WHERE con.cat_id = cat.id AND cat.published = 1 AND con.parent_id=0
				GROUP BY con.cat_id
				ORDER BY cat.title ASC
				";		
		
		$result = $inDB->query($sql) ;
		
		$items = array();
		
		$is_item = false;
		
		if ($inDB->num_rows($result)){	
			$is_item = true;
			
			while($item = $inDB->fetch_assoc($result)){
			
				$item['link'] = '/rew/'.$item['torg_cat_id'];
				
			
				$items[]=$item;

				}
			
			}
		
		$smarty = $inCore->initSmarty('components', 'com_torg_rew_cat.tpl');			
		$smarty->assign('items', $items);
		$smarty->assign('cfg', $cfg);
		$smarty->assign('is_item', $is_item);
		$smarty->display('com_torg_rew_cat.tpl');
				
		return true;
}


}