<?php namespace Admin\Controller;
use Think\Controller;

class CommentController extends Controller {
	public function getLastComments() {
		$comments = M('comments');
		//return $comments->where('userid='.$_SESSION['userid'])->order('commtime desc')->limit(0,10)->select();
		return $comments->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'comments c')->where('a.id=c.archive and c.userid=' . $_SESSION['userid'])->field('c.*,a.title')->order('commtime desc')->limit(0, 10)->select();
	}
	public function getComments($id = 0) {
		$comments = M('comments');
		if (0 == $id) {
			return $comments->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'comments c')->where('a.id=c.archive and c.userid=' . $_SESSION['userid'])->field('c.*,a.title')->order('commtime desc')->select();
		} else {
			return $comments->table(C('DB_PREFIX') . 'archives a,' . C('DB_PREFIX') . 'comments c')->where('a.id=c.archive and c.id=' . $id)->field('c.*,a.title')->find();
		}

	}
	public function editComment() {
		$comment        = M('comments');
		$data['author'] = $_POST['author'];
		$data['email']  = $_POST['email'];
		//$data['ip']=$_POST['ip'];
		$data['comment'] = $_POST['comment'];
		$data['url']     = $_POST['url'];

		if (($i = $comment->where('id=' . $_GET['id'])->save($data)) != 0) {
			echo json_encode($this->getComments($_GET['id']));
			//echo "成功".$i;

			//$this->success('添加成功');
		} else {
			echo $comment->getlastsql();
		}
	}
	public function replyComment() {
		$comment          = M('comments');
		$data['author']   = $_POST['author'];
		$data['email']    = $_POST['email'];
		$data['ip']       = $_POST['ip'];
		$data['comment']  = $_POST['comment'];
		$data['url']      = $_POST['url'];
		$data['commtime'] = date('Y-m-d H:i:s', time());
		$data['reply']    = $_POST['reply'];
		$data['ip']       = get_client_ip();
		$data['userid']   = $_POST['userid'];
		$data['archive']  = $_POST['archive'];
		if (($lastid = $comment->data($data)->add()) != 0) {
			//$this->show($lastid);
			echo json_encode($this->getComments($lastid));
			//$this->show($comment->getlastsql());
			//$this->success('添加成功');
		} else {
			$this->show($comment->getlastsql());
			$this->error('添加失败');
		}
	}
	public function delComment() {

		$comment = M('comments');
		if ($comment->where('id=' . $_GET['id'])->delete()) {
			$this->success('删除成功');
		} else {
			$this->error('删除失败');
		}
	}
	public function getCommentsSum() {
		$Comments = M('comments');
		$arr      = $Comments->where('userid=' . $_SESSION['userid'])->field('COUNT("id")')->select();
		return $arr[0]['COUNT("id")'];
	}

}