<?php
namespace backend\controllers;


use backend\models\Book;
use backend\models\BookMark;
use backend\models\Category;
use backend\models\Chapter;
use backend\models\Comment;
use backend\models\Feedback;

use backend\models\Quote;
use yii;
use yii\web\Controller;


class ApiController extends Controller
{
    public $enableCsrfValidation = false;
    public function actionIndex()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $link = Yii::$app->request->absoluteUrl;
        $link = explode("?",$link);
        $link = $link[0].'/';
        $listApi = array(
            '1.---------' => '------------',
            'Book' => $link.'book',
            '2.---------' => '------------',
            'Chapter' => $link.'chapter',
            '3.---------' => '------------',
            'Book Mark' => $link.'bookmark',
            '4.---------' => '------------',
            'Quote' => $link.'quote',
            '5.---------' => '------------',
            'Search BookMark' => $link.'search_bookmark',
            '6.---------' => '------------',
            'Search Chapter' => $link.'search_chapter',
            '7.---------' => '------------',
            'Search Quote' => $link.'search_quote',
            '8.---------' => '------------',
            'Category' => $link.'category',
            '9.---------' => '------------',
            'Book By Category' => $link.'book_by_category',
            '10.---------' => '------------',
            'Last Chapter By Book' => $link.'last_chapter_by_book',
            '11.---------' => '------------',
            'Book New Update' => $link.'book_new_update',
            '12.---------' => '------------',
            'View Book' => $link.'view_book',
            '13.---------' => '------------',
            'Top View' => $link.'top_view',
        );
        return $listApi;
    }

    public function actionSearch_quote()
    {
        $rescordPerPage = 10;
        $chapterId = isset($_REQUEST['chapterId']) ? $_REQUEST['chapterId'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        $chapter = Quote::find()->where(['chapterId' => $chapterId])->limit($rescordPerPage)->offset($startindex)->orderBy(["quoteIndex"=>SORT_ASC])->all();
        $data = array();
        // var_dump($bookmark);exit;
        if(count($chapter)>0)
        {
            foreach($chapter as $item)
            {
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                $image = $path . '/images/quote/' . $item->image;
                $image = str_replace(" ", "%20", $image);
                $item->image = $image;
                $data[]=$item;
            }
            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'message' => 'OK',
            );
        }
        else
        {
            return array(
                'status' => 'ERROR',
                'data' => '',
                'message' => 'Not found data!',
            );
        }
    }

	public function actionAddcomment()
    {
        //$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $bookId = isset($_REQUEST['bookId']) ? $_REQUEST['bookId'] : '';
        $chapterId = isset($_REQUEST['chapterId']) ? $_REQUEST['chapterId'] : '';
        $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : '';
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : '';
        //$date = isset($_REQUEST['date']) ? $_REQUEST['date'] : '';
        $status = isset($_REQUEST['status']) ? $_REQUEST['status'] : '';

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		
        $comment = new Comment();
        $comment->chapterId = $chapterId;
        $comment->bookId = $bookId;
        $comment->name = $name;
        $comment->content = $content;
        $comment->datetime = date('Y-m-d H:i:s',strtotime('Now'));
        $comment->status = $status;
        if($comment->save()){
            return array(
                'status' => 'success',
                'data' => '',
                'message' => 'OK',
            );
        }else
        {
            return array(
                'status' => 'error',
                'data' => '',
                'message' => 'Fail.!',
            );
        }
    }

    public function actionComment()
    {
        $chapterId = isset($_REQUEST['chapterId']) ? $_REQUEST['chapterId'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data = array();
        $rescordPerPage = 20;
        $startindex = $page * $rescordPerPage - $rescordPerPage;

        $cate= Comment::find()->where('chapterId='.$chapterId)->all();
        $allpage=ceil(count($cate)/$rescordPerPage);

        $listComment = Comment::find()->where('chapterId='.$chapterId)->limit($rescordPerPage)->offset($startindex)->orderBy(["id"=>SORT_DESC])->all();
        if(count($listComment)>0)
        {
            foreach ($listComment as $item) {
                $item->datetime = strtotime($item->datetime);
                $data[] = $item;
            }

            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'allpage'=>$allpage,
                'message' => 'OK',
            );
        }
        else
            return array(
                'status' => 'ERROR',
                'data' => '',
                // 'allpage'=>$allpage,
                'message' => 'Not found comment!',
            );
    }
    public function actionSearch_chapter()
    {
        $rescordPerPage = 10;
        $bookId = isset($_REQUEST['bookId']) ? $_REQUEST['bookId'] : '';
        //$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        //$startindex = $page * $rescordPerPage - $rescordPerPage;
        $chapter = Chapter::find()->where('bookId ='.$bookId)->orderBy(["chapterIndex"=>SORT_ASC,'id' =>SORT_ASC])->all();
        $data = array();
        // var_dump($bookmark);exit;
        if(count($chapter)>0)
        {
            foreach($chapter as $item)
            {
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                if(strlen($item->image)>0)
                    $image = $path . '/images/chapter/' . $item->image;
                else
                    $image = 'File is not exist!';
                // $image = str_replace(" ", "%20", $image);
                $item->image = $image;

				$item->type = isset($item->type) ? $item->type : 0;
                if(strlen($item->directURL)>0)
                {
					$item->attachment = $item->directURL;
                    
                }
                else
				{
					if(strlen($item->attachment)>0)
					{
						$attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
						$item->attachment = $attachment;
					}else{
						$item->attachment = '';
					}
				}

                $data[]=$item;
            }
            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'message' => 'OK',
            );
        }
        else
        {
            return array(
                'status' => 'ERROR',
                'data' => '',
                'message' => 'Not found data!',
            );
        }


    }
    public function actionSearch_bookmark()
    {
        $rescordPerPage = 10;
        $bookId = isset($_REQUEST['bookId']) ? $_REQUEST['bookId'] : '';
        $chapterId = isset($_REQUEST['chapterId']) ? $_REQUEST['chapterId'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        $bookmark = BookMark::find()->where(['bookId' => $bookId, 'chapterId' => $chapterId])->limit($rescordPerPage)->offset($startindex)->orderBy(["id"=>SORT_DESC])->all();
        $data = array();
       // var_dump($bookmark);exit;
        if(count($bookmark)>0)
        {
            foreach($bookmark as $item)
            {
                $data[] = $item;
            }
            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'message' => 'OK',
            );
        }
        else
        {
            return array(
                'status' => 'ERROR',
                'data' => '',
                'message' => 'Not found data!',
            );
        }


    }
    public function actionQuotes()
    {
        $rescordPerPage = 10;
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        if($id == 0 || $id == NULL)
        {
            if($page == 0)
            {
                $listNews= Quote::find()->orderBy(["quoteIndex"=>SORT_ASC])->all();
                //var_dump($listNews);exit;
            }
            else
            {
                $listNews = Quote::find()->limit($rescordPerPage)->offset($startindex)->orderBy(["quoteIndex"=>SORT_ASC])->all();
                $data = array();
            }

            foreach ($listNews as $item) {
               // $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                //$actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                $image = $path . '/images/quote/' . $item->image;
                $image = str_replace(" ", "%20", $image);
                $item->image = $image;
                $data[] = $item;
            }

            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'message' => 'OK',
            );
        }
        else
        {
            $listNews= Quote::find()->where('id ='.$id)->one();
            $data = array();
            if(isset($listNews))
            {
                $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
              //  $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                $image = $path . '/images/quote/' . $listNews->image;
                $image = str_replace(" ", "%20", $image);
                $listNews->image = $image;
                $data[] = $listNews;
                return array(
                    'status' => 'SUCCESS',
                    'data' => $data,
                    'message' => 'OK',
                );
            }
            else
            {
                return array(
                    'status' => 'ERROR',
                    'data' => '',
                    'message' => 'Not found data',
                );
            }
        }
    }
    public function actionBookmark()
    {
        $rescordPerPage = 10;
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        if($id == 0 || $id == NULL)
        {
            if($page == 0)
            {
                $listNews= BookMark::find()->all();
                //var_dump($listNews);exit;
            }
            else
            {
                $listNews = BookMark::find()->limit($rescordPerPage)->offset($startindex)->orderBy(["id"=>SORT_DESC])->all();
                $data = array();
            }

            foreach ($listNews as $item) {
                $data[] = $item;
            }

            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'message' => 'OK',
            );
        }
        else
        {
            $listNews= BookMark::find()->where('id ='.$id)->one();
            $data = array();
            if(isset($listNews))
            {
                $data[] = $listNews;
                return array(
                    'status' => 'SUCCESS',
                    'data' => $data,
                    'message' => 'OK',
                );
            }
            else
            {
                return array(
                    'status' => 'ERROR',
                    'data' => '',
                    'message' => 'Not found data',
                );
            }
        }
    }

    public function actionChapter()
    {
        $rescordPerPage = 5;
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        if($id == 0 || $id == NULL)
        {
            if($page == 0)
            {
                $listNews= Chapter::find()->all();
                $allpage= 1;
                //var_dump($listNews);exit;
            }
            else
            {
                $chapter= Chapter::find()->all();
                $numschap= count($chapter);
                $allpage=ceil($numschap/$rescordPerPage);

                $listNews = Chapter::find()->limit($rescordPerPage)->offset($startindex)->orderBy(['chapterIndex' => SORT_ASC,'id' => SORT_ASC])->all();
                $data = array();
            }

            foreach ($listNews as $item) {
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                if(strlen($item->image)>0)
                    $image = $path . '/images/chapter/' . $item->image;
                else
                    $image = 'File is not exist!';


                // $image = str_replace(" ", "%20", $image);
                $item->image = $image;
                if(strlen($item->directURL)>0)
                {
					$item->attachment = $item->directURL;
                }
                else
                    $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                    $item->attachment = $attachment;
				
                $item->bookMarkIndex = isset($item->bookMarkIndex) ? $item->bookMarkIndex : '';
                $data[] = $item;
            }

            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'allpage'=>$allpage,
                'message' => 'OK',
            );
        }
        else
        {
            $listNews= Chapter::find()->where('id ='.$id)->one();
            $data = array();
            if(isset($listNews))
            {
				$path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;

                if(strlen($listNews->directURL)>0)
					$attach = $listNews->directURL;
                else
                    $attach = $path . '/uploads/chapter/' . $listNews->attachment;
                $listNews->attachment = $attach;
				
                $listNews->bookMarkIndex = isset($listNews->bookMarkIndex) ? $listNews->bookMarkIndex : '';
                $data[] = $listNews;
                return array(
                    'status' => 'SUCCESS',
                    'data' => $data,
                    'message' => 'OK',
                );
            }
            else
            {
                return array(
                    'status' => 'ERROR',
                    'data' => '',
                    'message' => 'Not found data',
                );
            }
        }

    }

    public function actionBook()
    {
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '';


        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $rescordPerPage = 10;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        $book= Book::find()->all();
        $numsbook= count($book);
        $allpage=ceil($numsbook/$rescordPerPage);
        if(($id == 0 && $id == NULL))
        {
            if($page == 0)
            {
                $listNews= Book::find()->orderBy(["title"=>SORT_ASC])->all();
                //var_dump($listNews);exit;
            }
            else
            {
                $listNews = Book::find()->limit($rescordPerPage)->offset($startindex)->orderBy(["title"=>SORT_ASC])->all();
                $data = array();
            }
                foreach ($listNews as $item) {
                    $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                    $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
                    $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                    if(strlen($item->image)>0){
                        $image = $path . '/images/book/' . $item->image;
                        // $image = str_replace(" ", "%20", $image);
                        $item->image = $image;
                    }
                    else
                    {
                        $image = $path . '/images/www/no_image.jpg';
                        $item->image = $image;
                    }


                    if(strlen($item->attachment)>0)
                    {
                        $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                        $item->attachment = $attachment;
                    }
                    else
                        $item->attachment = '';

                    $positonChapterNew = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->all();
                    $position = count($positonChapterNew) - 1;
                    $lastchapter = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->one();
                    //var_dump($lastchapter);exit;
                    $idLastChapter = 0;
                    $bookId = 0;
                    $title = '';
                    $bookMark = 0;
                    $imageChapter = '';
                    $type = 0;
                    $time = '';
                    $chapterIndex = 0;
                    $attachment  = '';
					$direct= '';
                    if(count($lastchapter)>0)
                    {
                        //if($item->type == 1)
                        //{
                            if(strlen($lastchapter->image)>0){
                                $imageChapter = $path . '/images/chapter/' . $lastchapter->image;
                            }
                            else
                            {
                                $imageChapter = $path . '/images/www/no_image.jpg';
                                $lastchapter->image = $imageChapter;
                            }

                            if(strlen($lastchapter->directURL)>0)
                            {
								$attachment = $lastchapter->directURL;
                                
                            }
                            else
                                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                                $attachment = str_replace('web','uploads',$path).'/attachment/'.$lastchapter->attachment;
                                //$attachment = $attachment;

                            $idLastChapter = isset($lastchapter->id) ? $lastchapter->id : 0;
                            $bookId = $lastchapter->bookId;
                            $title = $lastchapter->title;
                            $bookMark = $position;
                            $type = $lastchapter->type;
                            $time = $lastchapter->time;
                            $chapterIndex = $lastchapter->chapterIndex;
                        /*}else
                        {
                            $idLastChapter = 0;
                            $bookId = 0;
                            $title = '';
                            $bookMark = 0;
                            $imageChapter = '';
                            $type = 0;
                            $time = '';
                            $chapterIndex = 0;
                        }*/
                    }

                    //echo $idLastChapter;exit;
                    $data[] = array(
                        'id'=>$item->id,
                        'title'=>$item->title,
                        'author'=>$item->author,
                        'publisher'=>$item->publisher,
                        'image'=>$item->image,
                        'description'=>$item->description,
                        'type'=>isset($item->type) ? $item->type : 0,
                        'attachment'=>$item->attachment,
                        'categoryId'=>$item->categoryId,

                        'last chapter'=> array(
                            'chapter_id'=> $idLastChapter,
                            'bookId'=> $bookId,
                            'title_chapter'=> $title,
                            'bookMarkIndex'=> $bookMark,
                            'image_chapter'=> $imageChapter,
                            'type_chapter'=> isset($type) ? $type : 0,
                            'time'=> $time,
                            'chapterIndex'=> $chapterIndex,
                            'attachment'=>$attachment
                        ),
                    );
                }

                return array(
                    'status' => 'SUCCESS',
                    'data' => $data,
                    'allpage'=>$allpage,
                    'message' => 'OK',
                );
        }
        else
        {
            $listNews= Book::find()->where('id ='.$id)->one();
            $data = array();
            if(isset($listNews))
            {
                $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                $image = $path . '/images/book/' . $listNews->image;
                $image = str_replace(" ", "%20", $image);
                $listNews->image = $image;
                if(strlen($listNews->attachment)>0)
                {
                    $attachment = str_replace('web','uploads',$path).'/attachment/'.$listNews->attachment;
                    $listNews->attachment = $attachment;
                }
                else
                    $listNews->attachment = '';
                $data[] = $listNews;

                return array(
                    'status' => 'SUCCESS',
                    'data' => $data,
                    'message' => 'OK',
                );
            }
            else
            {
                return array(
                    'status' => 'ERROR',
                    'data' => '',
                    'message' => 'Not found data',
                );
            }
        }
    }

    public function actionSearchbook()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $searchKey = isset($_REQUEST['searchKey']) ? $_REQUEST['searchKey'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';


        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $rescordPerPage = 10;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        $book= Book::find()->where(['LIKE', 'title', $searchKey])
            ->orWhere(" description LIKE '%$searchKey%' OR author LIKE '%$searchKey%' ")
            ->all();
        $numsbook= count($book);
        $allpage=ceil($numsbook/$rescordPerPage);

        $listNews = Book::find()->where(['LIKE', 'title', $searchKey])
            ->orWhere(" description LIKE '%$searchKey%' OR author LIKE '%$searchKey%' ")
            ->limit($rescordPerPage)
            ->offset($startindex)
            ->orderBy(["title"=>SORT_ASC,"id"=>SORT_DESC])
            ->all();
        $data = array();
        foreach ($listNews as $item) {
            $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
            $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
            if(strlen($item->image)>0){
                $image = $path . '/images/book/' . $item->image;
                // $image = str_replace(" ", "%20", $image);
                $item->image = $image;
            }
            else
            {
                $image = $path . '/images/www/no_image.jpg';
                $item->image = $image;
            }


            if(strlen($item->attachment)>0)
            {
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                $item->attachment = $attachment;
            }
            else
                $item->attachment = '';

            $positonChapterNew = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->all();
            $position = count($positonChapterNew) - 1;
            $lastchapter = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->one();
            //var_dump($lastchapter);exit;
            $idLastChapter = 0;
            $bookId = 0;
            $title = '';
            $bookMark = 0;
            $imageChapter = '';
            $type = 0;
            $time = '';
            $chapterIndex = 0;
            $attachment  = '';
            if(count($lastchapter)>0)
            {
                if(strlen($lastchapter->image)>0){
                    $imageChapter = $path . '/images/chapter/' . $lastchapter->image;
                }
                else
                {
                    $imageChapter = $path . '/images/www/no_image.jpg';
                    $lastchapter->image = $imageChapter;
                }

                if(strlen($lastchapter->directURL)>0)
                {
                    $attachment = $lastchapter->directURL;
                }
                else
					$path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                    $attachment = str_replace('web','uploads',$path).'/attachment/'.$lastchapter->attachment;
                    //$lastchapter->attachment = $attachment;
                    

                $idLastChapter = isset($lastchapter->id) ? $lastchapter->id : 0;
                $bookId = $lastchapter->bookId;
                $title = $lastchapter->title;
                $bookMark = $position;
                $type = $lastchapter->type;
                $time = $lastchapter->time;
                $chapterIndex = $lastchapter->chapterIndex;
            }

            $data[] = array(
                'id'=>$item->id,
                'title'=>$item->title,
                'author'=>$item->author,
                'publisher'=>$item->publisher,
                'image'=>$item->image,
                'description'=>$item->description,
                'type'=>isset($item->type) ? $item->type : 0,
                'attachment'=>$item->attachment,
                'categoryId'=>$item->categoryId,

                'last chapter'=> array(
                    'chapter_id'=> $idLastChapter,
                    'bookId'=> $bookId,
                    'title_chapter'=> $title,
                    'bookMarkIndex'=> $bookMark,
                    'image_chapter'=> $imageChapter,
                    'type_chapter'=> isset($type) ? $type : 0,
                    'time'=> $time,
                    'chapterIndex'=> $chapterIndex,
                    'attachment'=>$attachment
                ),
            );
        }

        return array(
            'status' => 'SUCCESS',
            'data' => $data,
            'allpage'=>$allpage,
            'message' => 'OK',
        );

    }

    public function actionSearchchapter()
    {
        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $searchKey = isset($_REQUEST['searchKey']) ? $_REQUEST['searchKey'] : '';

        $chapter= Chapter::find()->where(['LIKE', 'title', $searchKey])
            ->orWhere("id in (SELECT chapterId from quote WHERE content LIKE '%$searchKey%')")
			->orWhere("bookId in (SELECT id from book WHERE title LIKE '%$searchKey%' OR author LIKE '%$searchKey%')")
            ->orderBy('chapterIndex ASC, id DESC')
            ->all();
        $data= array();
        //var_dump($chapter);exit;
        if(count($chapter)>0)
        {
            foreach($chapter as $item)
            {
                $book= Book::find()->where('id ='.$item->bookId)->one();
                if(count($book)>0)
                {
                    $title= isset($book->title) ? $book->title : '';

                    if(strlen($book->image)>0)
                    {
                        $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                        $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
                        $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                        $image = $path . '/images/book/' . $book->image;
                        // $image = str_replace(" ", "%20", $image);
                        //$book->image = $image;
                    }
                    else
                    {
                        $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                        $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
                        $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                        $image = $path . '/images/www/no_image.jpg';
                    }
                }
                else
                {
                    $title= '';

                    $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                    $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
                    $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                    $image = $path . '/images/www/no_image.jpg';
                }

                if(strlen($item->directURL)>0)
                {
                    $attachment = $item->directURL;
                }
                else
					$path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                    $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                    //$item->attachment = $attachment;
                    

                $data[]= array(
                    'id'=>$item->id,
                    'title'=>isset($item->title) ? $item->title : '',
                    'bookId'=>isset($item->bookId) ? $item->bookId : '',
                    'titleBook'=>$title,
                    'imageBook'=>$image,
                    'bookMarkIndex'=>isset($item->bookMarkIndex) ? $item->bookMarkIndex : '',
					'type'=>isset($item->type) ? $item->type : 0,
                    'attachment' => $attachment,
                    'chapterIndex' => $item->chapterIndex
                );
            }
            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'message' => 'OK',
            );
        }
        else
        {
            return array(
                'status' => 'ERROR',
                'data' => '',
                'message' => 'Title not exist !',
            );
        }
    }

    public function actionCategory()
    {
        //$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $data = array();
        $rescordPerPage = 100;
        $startindex = $page * $rescordPerPage - $rescordPerPage;

        $cate= Category::find()->all();
        $allpage=ceil(count($cate)/$rescordPerPage);
		$path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
        $listCate = Category::find()->limit($rescordPerPage)->offset($startindex)->orderBy(["order"=>SORT_ASC])->all();
        //var_dump($listCate);exit;
        if(count($listCate)>0)
        {
            foreach ($listCate as $item) {
				if(strlen($item->image)>0){
                $image = $path . '/images/category/' . $item->image;
                $item->image = $image;
				}
				else
				{
					$image = $path . '/images/www/no_image.jpg';
					$item->image = $image;
				}
			
                $data[] = $item;
            }

            return array(
                'status' => 'SUCCESS',
                'data' => $data,
                'allpage'=>$allpage,
                'message' => 'OK',
            );
        }
        else
            return array(
                'status' => 'ERROR',
                'data' => '',
               // 'allpage'=>$allpage,
                'message' => 'Not found category!',
            );
    }

    public function actionBook_by_category()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $categoryId = isset($_REQUEST['categoryId']) ? $_REQUEST['categoryId'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';

        $data = array();
        $rescordPerPage = 10;
        $startindex = $page * $rescordPerPage - $rescordPerPage;

        if($categoryId == 0 || strlen($categoryId) == 0)
        {
            $books = Book::find()->all();
            $allpage = ceil(count($books)/$rescordPerPage);

            $listNews = Book::find()->limit($rescordPerPage)->offset($startindex)->orderBy(["id"=>SORT_DESC])->all();
            if(count($listNews)>0)
            {
                foreach ($listNews as $item) {
                    $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                    $image = $path . '/images/book/' . $item->image;
                    // $image = str_replace(" ", "%20", $image);
                    $item->image = $image;
                    //$item->attachment = isset($item->attachment) ? $item->attachment : '';
                    if(strlen($item->attachment)>0)
                    {
                        $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                        $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                        $item->attachment = $attachment;
                    }
                    else
                        $item->attachment = '';
                    $data[] = $item;
                }

                return array(
                    'status' => 'SUCCESS',
                    'data' => $data,
                    'allpage'=>$allpage,
                    'message' => 'OK',
                );
            }
            else
                return array(
                    'status' => 'ERROR',
                    'data' => '',
                    //'allpage'=>$allpage,
                    'message' => 'OK',
                );

        }
        else
        {
            $books = Book::find()->where('categoryId ='.$categoryId)->all();
            $allpage = ceil(count($books)/$rescordPerPage);

            $listNews = Book::find()->where('categoryId ='.$categoryId)->limit($rescordPerPage)->offset($startindex)->orderBy(["id"=>SORT_DESC])->all();
            if(count($listNews)>0)
            {
                foreach ($listNews as $item) {
                    $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                    $image = $path . '/images/book/' . $item->image;
                    // $image = str_replace(" ", "%20", $image);
                    $item->image = $image;
                    //$item->attachment = isset($item->attachment) ? $item->attachment : '';
                    if(strlen($item->attachment)>0)
                    {
                        $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                        $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                        $item->attachment = $attachment;
                    }
                    else
                        $item->attachment = '';
                    $data[] = $item;
                }

                return array(
                    'status' => 'SUCCESS',
                    'data' => $data,
                    'allpage'=>$allpage,
                    'message' => 'OK',
                );
            }
            else
                return array(
                    'status' => 'ERROR',
                    'data' => '',
                    //'allpage'=>$allpage,
                    'message' => 'OK',
                );

        }
    }

    public function actionLast_chapter_by_book()
    {
		\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		//$listChapter = Chapter::find()->where("time > curdate() - INTERVAL DAYOFWEEK(curdate())+365 DAY")->orderBy(["id"=>SORT_DESC])->all();
		$listChapter = Chapter::find()->orderBy(["id"=>SORT_DESC])->all();
		//var_dump($listChapter);exit;
		$data = array();
		$bookIDs = array();
		
		$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '1';
        $rescordPerPage = 10;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
		$endindex = $startindex + $rescordPerPage-1;
		$iTemp = 0;
		
		//echo count($listChapter).'<br/>'; exit;
		foreach($listChapter as $aChapter)
		{
			if (!in_array($aChapter->bookId, $bookIDs))
			{
				$book = Book::find()->where('id='.$aChapter->bookId)->one();
				if (count($book) == 0)
					continue;
				
				$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
				$actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
				$path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
				if(strlen($book['image']) > 0)
				{
					$image = $path . '/images/book/' . $book->image;
					$image = str_replace(" ", "%20", $image);
				}else
				{
					$image = $path . '/images/www/no_image.jpg';
				}
				$book['image'] = $image;
				//
				$bookIDs[] = $aChapter->bookId;
				//
				$positonChapterNew = Chapter::find()->where('bookId='.$aChapter->bookId)->orderBy(["id"=>SORT_DESC])->all();
				$position = count($positonChapterNew) - 1;
				if(strlen($aChapter->directURL)>0)
                {
                    $attach = $aChapter->directURL;
                }
                else{
					if(strlen($aChapter->attachment)>0)
					{
						$attachment = str_replace('web','uploads',$path).'/attachment/'.$aChapter->attachment;
						$attach = $attachment;
					}else
					{
						$attach = '';
					}
					
				}
                    
				//
				if ($iTemp >= $startindex && $iTemp <= $endindex)
				{
					$data[] = array(
						'id'=>$book['id'],
						'title'=>$book['title'],
						'author'=>$book['author'],
						'publisher'=>$book['publisher'],
						'image'=>$book['image'],
						'description'=>$book['description'],
						'type'=>isset($book['type']) ? $book['type'] : 0,
						'attachment'=>isset($book['attachment']) ? $book['attachment'] : '',
						'categoryId'=>$book['categoryId'],
						'last chapter'=> array(
							'chapter_id'=> $aChapter->id,
							'bookId'=> $aChapter->bookId,
							'title_chapter'=> $aChapter->title,
							'bookMarkIndex'=> $position,
							'image_chapter'=> isset($aChapter->image) ? $aChapter->image : '',
							'type_chapter'=> isset($aChapter->type) ? $aChapter->type : 0,
							'time'=> $aChapter->time,
							'chapterIndex'=> $aChapter->chapterIndex,
							'attachment'=> $attach
						),
					);
					$iTemp++;
				} else if ($iTemp < $startindex){
					$iTemp++;
					continue;
				}
				else if ($iTemp > $endindex){
					break;
				}
			}
		}
		
		return array(
			'status' => 'SUCCESS',
			'data' => $data,
			'allpage'=>1,
			'message' => 'OK',
        );		
    }

    public function actionView_book()
    {
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : '';

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if(($id == 0 || $id == NULL))
        {
            return array(
                'status' => 'ERROR',
                'data' => '',
                'message' => 'Not found data',
            );
        }
        else
        {
            $view = Book::find()->where('id='.$id)->one();
            if(isset($view)){
                $view->view= $view->view +1;
                $view->save(false);
                return array(
                    'status' => 'SUCCESS',
                    //'data' => array(),
                    'message' => 'OK',
                );
            }
            else{
                return array(
                    'status' => 'SUCCESS',
                    //'data' => array(),
                    'message' => 'Not found data',
                );
            }
        }
    }

    public function actionTop_view()
    {
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $rescordPerPage = 10;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        $book= Book::find()->all();
        $numsbook= count($book);
        $allpage=ceil($numsbook/$rescordPerPage);
        
		$listNews = Book::find()->limit($rescordPerPage)->offset($startindex)->orderBy(["view"=>SORT_DESC])->all();
		$data = array();
        
        foreach ($listNews as $item) {
            $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
            $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
            $image = $path . '/images/book/' . $item->image;
            // $image = str_replace(" ", "%20", $image);
            $item->image = $image;

            if(strlen($item->attachment)>0)
            {
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                $item->attachment = $attachment;
            }            

			$positonChapterNew = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->all();
			$position = count($positonChapterNew) - 1;
			$lastchapter = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->one();
			
			$idLastChapter = 0;
			$bookId = 0;
			$title = '';
			$bookMark = 0;
			$imageChapter = '';
			$type = 0;
			$time = '';
			$chapterIndex = 0;
			$attach= '';
            if(count($lastchapter)>0)
            {
                if($item->type == 1)
                {
                    if(strlen($lastchapter->image)>0){
                        $imageChapter = $path . '/images/chapter/' . $lastchapter->image;
                    }
                    else
                    {
                        $imageChapter = $path . '/images/www/no_image.jpg';
                        $lastchapter->image = $imageChapter;
                    }
					
					if(strlen($lastchapter->directURL)>0){
						$attach = $lastchapter->directURL;	
					}
					else
					{
						$path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
						$attachment = str_replace('web','uploads',$path).'/attachment/'.$lastchapter->attachment;
						$attach = $attachment;
							
					}
                    $idLastChapter = $lastchapter->id;
                    $bookId = $lastchapter->bookId;
                    $title = $lastchapter->title;
                    $bookMark = $position;
                    $type = $lastchapter->type;
                    $time = $lastchapter->time;
                    $chapterIndex = $lastchapter->chapterIndex;
                }else
                {
                    $idLastChapter = 0;
                    $bookId = 0;
                    $title = '';
                    $bookMark = 0;
                    $imageChapter = '';
                    $type = 0;
                    $time = '';
                    $chapterIndex = 0;
					$attach = '';
                }
            }
			
            $data[] = array(
                'id'=>$item->id,
                'title'=>$item->title,
                'author'=>$item->author,
                'publisher'=>$item->publisher,
                'image'=>$item->image,
                'description'=>$item->description,
                'type'=>isset($item->type) ? $item->type : 0,
                'attachment'=>isset($item->attachment) ? $item->attachment : '',
                'categoryId'=>$item->categoryId,
                'last chapter'=> array(
				'chapter_id'=> $idLastChapter,
				'bookId'=> $bookId,
				'title_chapter'=> $title,
				'bookMarkIndex'=> $bookMark,
				'image_chapter'=> isset($imageChapter) ? $imageChapter : '',
				'type_chapter'=> isset($type) ? $type : 0,
				'time'=> $time,
				'chapterIndex'=> $chapterIndex,
				'attachment'=>$attach
                ),
            );
        }

        return array(
            'status' => 'SUCCESS',
            'data' => $data,
            'allpage'=>$allpage,
            'message' => 'OK',
        );
    }

    public function actionBook_new_update()
    {
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $rescordPerPage = 10;
        $startindex = $page * $rescordPerPage - $rescordPerPage;
        $book= Book::find()->all();
        $numsbook= count($book);
        $allpage=ceil($numsbook/$rescordPerPage);
        
		$listNews = Book::find()->limit($rescordPerPage)->offset($startindex)->orderBy(["id"=>SORT_DESC])->all();
		$data = array();
        
        foreach ($listNews as $item) {
            $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $actual_link = str_replace("/web/index.php/api/book", "", $actual_link);
            $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
            $image = $path . '/images/book/' . $item->image;
            // $image = str_replace(" ", "%20", $image);
            $item->image = $image;

            if(strlen($item->attachment)>0)
            {
                $path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
                $attachment = str_replace('web','uploads',$path).'/attachment/'.$item->attachment;
                $item->attachment = $attachment;
            }            

			$positonChapterNew = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->all();
			$position = count($positonChapterNew) - 1;
			$lastchapter = Chapter::find()->where('bookId='.$item->id)->orderBy(["id"=>SORT_DESC])->one();
			$idLastChapter = 0;
            $bookId = 0;
            $title = 0;
            $bookMark = 0;
            $imageChapter = '';
            $type = 0;
            $time = '';
            $chapterIndex = 0;
			$attach = '';
            if(count($lastchapter)>0)
            {
                if($item->type == 1)
                {
                    if(strlen($lastchapter->image)>0){
                        $imageChapter = $path . '/images/chapter/' . $lastchapter->image;
                    }
                    else
                    {
                        $imageChapter = $path . '/images/www/no_image.jpg';
                        $lastchapter->image = $imageChapter;
                    }
					
					if(strlen($lastchapter->directURL)>0){
						$attach = $lastchapter->directURL;	
					}
					else
					{
						$path= "http://$_SERVER[HTTP_HOST]".Yii::$app->urlManager->baseUrl;
						$attachment = str_replace('web','uploads',$path).'/attachment/'.$lastchapter->attachment;
						$attach = $attachment;
					}
                    $idLastChapter = $lastchapter->id;
                    $bookId = $lastchapter->bookId;
                    $title = $lastchapter->title;
                    $bookMark = $position;
                    $type = $lastchapter->type;
                    $time = $lastchapter->time;
                    $chapterIndex = $lastchapter->chapterIndex;
                }else
                {
                    $idLastChapter = 0;
                    $bookId = 0;
                    $title = '';
                    $bookMark = 0;
                    $imageChapter = '';
                    $type = 0;
                    $time = '';
                    $chapterIndex = 0;
					$attach = '';
                }
				$data[] = array(
					'id'=>$item->id,
					'title'=>$item->title,
					'author'=>$item->author,
					'publisher'=>$item->publisher,
					'image'=>$item->image,
					'description'=>$item->description,
					'type'=>isset($item->type) ? $item->type : 0,
					'attachment'=>isset($item->attachment) ? $item->attachment : '',
					'categoryId'=>$item->categoryId,
					'last chapter'=> array(
						'chapter_id'=> $idLastChapter,
						'bookId'=> $bookId,
						'title_chapter'=> $title,
						'bookMarkIndex'=> $bookMark,
						'image_chapter'=> isset($imageChapter) ? $imageChapter : '',
						'type_chapter'=> isset($type) ? $type : 0,
						'time'=> $time,
						'chapterIndex'=> $chapterIndex,
						'attachment'=>$attach
					),
				);
            }
            
        }

        return array(
            'status' => 'SUCCESS',
            'data' => $data,
            'allpage'=>$allpage,
            'message' => 'OK',
        );
    }

    public function actionFeedback()
    {
        $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : '';
        $email = isset($_REQUEST['email']) ? $_REQUEST['email'] : '';
        $subject = isset($_REQUEST['subject']) ? $_REQUEST['subject'] : '';
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : '';

        // Format data return to Json
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if(strlen($name) == 0 OR strlen($email) == 0 OR strlen($content) == 0)
        {
            return array(
                'status' => 'ERROR',
                'message' => 'Please check param: name/ email/ content!',
            );
        }
        else
        {
            $feedback = new Feedback();
            $feedback->name = $name;
            $feedback->email = $email;
            $feedback->subject = $subject;
            $feedback->content = $content;
            $feedback->status = 1; // Open
            $feedback->createdDate = date('Y-m-d H:i:s',strtotime('Now'));
            $feedback->save();

            return array(
                'status' => 'SUCCESS',
                'message' => 'OK',
            );
        }
    }
}