<?php

namespace frontend\controllers;

use Yii;
use common\models\Comment;

class CommentController extends \yii\web\Controller
{
    public function actionIndex()
    {
        $post = Comment::find()->with('user')->orderBy('created_at ASC')->all();

        $comments = array();

        foreach($post as $p)
        {
            $comments[$p['comment_id']] = array(
                'id' => $p['comment_id'],
                'parent' => $p['comment_pid'],
                'content' => $p['content'],
                'username' => $p->user->username,
                'created_at' => $p['created_at'],
                'childs' => array()
            );
        }

        foreach ($comments as $key => &$val)
        {
            if ($val['parent'] != 0)
            {
                $comments[$val['parent']]['childs'][] =& $val;
            }
        }
        unset($val);

        foreach ($comments as $key => $val)
        {
            if ($val['parent'] != 0)
            {
                unset($comments[$key]);
            }
        }

        if (Yii::$app->request->get('action') == 'reload')
        {
            return $this->renderAjax('index', array('data' => $comments));
        }
        else
        {
            return $this->render('index', array('data' => $comments, 'reload' => false));
        }
    }

    public function actionCreate()
    {
        $comment = new Comment;

        $comment->user_id = Yii::$app->user->identity->id;
        $comment->content = Yii::$app->request->post('content');
        $comment->entity_id = 3;//Yii::$app->request->post('entity_id');
        $comment->comment_pid = Yii::$app->request->post('parent_id');
        $comment->created_at = date('Y-m-d H:i:s', time());

        $comment->save();

    }

}
