<?php

namespace App\Http\Controllers\Api\v1;

use App\Components\Functions;
use App\Jobs\SendNotificationSocial;
use App\Models\Comment;
use App\Models\Hostel;
use App\Models\Notification;
use App\Models\RenterRoom;
use App\Models\Room;
use App\Models\SocialPost;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SocialController extends BaseController {
	//
	public function getPosts( Request $request ) {
		$limit = $request->input( 'limit', 5 );

		$lastId   = $request->input( 'last_id' );
		$hostelId = $request->input( 'hostel_id' );
		if ( empty( $lastId ) ) {

			$posts = SocialPost::select( \DB::raw( 'social_posts.*' ) )->leftJoin( 'hostel_posts', 'social_posts.id', '=', 'hostel_posts.social_post_id' )
			                   ->orderBy( 'social_posts.id', 'desc' )
			                   ->limit( $limit )
			                   ->offset( 0 );
		} else {
			$posts = SocialPost::select( \DB::raw( 'social_posts.*' ) )->orderBy( 'social_posts.id', 'desc' )
			                   ->leftJoin( 'hostel_posts', 'social_posts.id', '=', 'hostel_posts.social_post_id' )
			                   ->limit( $limit )
			                   ->where( 'social_posts.id', '<', $lastId );
		}

		if ( ! empty( $hostelId ) ) {
			$posts = $posts->where( 'hostel_posts.hostel_id', $hostelId );
		}

		if($hostelId == -1)
        {
            $posts = $posts->whereNull('hostel_posts.hostel_id');
        }

        if(empty($hostelId))
        {
            return response( [
                'status' => 1,
                'data'   => []
            ] );
        }

		$posts = $posts->get();

		foreach ( $posts as $post ) {
			$imageData = [];
			$images    = json_decode( $post->images, true );
			if ( is_array( $images ) ) {
				foreach ( $images as $image ) {
					$imageData[] = '/files/' . $image;
				}
			}

			$post->liked = Functions::checkLikePostApi( $post->id, $this->user->id );
			$post->user  = Functions::getUser( $post->user_id );

			$post->images = $imageData;
		}

		return response( [
			'status' => 1,
			'data'   => $posts
		] );
	}

    /**
     * @api {get} /post Chi tiết post_id
     * @apiName post
     * @apiGroup Social
     * @apiParam {String} post_id
     *
     * @apiDescription Api Lấy chi tiết post cộng đồng
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */

	public function detail( Request $request ) {
		$postId = $request->input( 'post_id' );

		$post = SocialPost::find( $postId );


		if ( ! $post ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$imageData = [];
		$images    = json_decode( $post->images, true );
		if ( is_array( $images ) ) {
			foreach ( $images as $image ) {
				$imageData[] = '/files/' . $image;
			}
		}

		$post->images = $imageData;

		$post->liked = Functions::checkLikePostApi( $post->id, $this->user->id );
		$post->user  = Functions::getUser( $post->user_id );

		return response( [
			'status'  => 1,
			'message' => 'Thành công',
			'data'    => $post
		] );

	}

    /**
     * @api {get} /comments Lấy comments 1 post
     * @apiName comments
     * @apiGroup Social
     * @apiParam {String} post_id
     * @apiParam {String} limit
     * @apiParam {String} last_id
     *
     * @apiDescription Api Lấy comments 1 post
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */
	public function getComments( Request $request ) {
		$postId = $request->input( 'post_id' );

		$limit = $request->input( 'limit', 5 );

		$lastId = $request->input( 'last_id' );
		if ( empty( $lastId ) ) {

			$comments = Comment::where( 'social_post_id', $postId )->orderBy( 'id', 'desc' )
			                   ->limit( $limit )
			                   ->offset( 0 )->get();
		} else {
			$comments = Comment::where( 'social_post_id', $postId )->orderBy( 'id', 'desc' )
			                   ->limit( $limit )
			                   ->where( 'id', '<', $lastId )->get();
		}

		foreach ( $comments as $comment ) {
			$imageData = [];
			$images    = json_decode( $comment->images, true );
			if ( is_array( $images ) ) {
				foreach ( $images as $image ) {
					$imageData[] = '/files/' . $image;
				}
			}
			$comment->images = $imageData;
			$comment->user   = Functions::getUser( $comment->user_id );
		}

		return response( [
			'status' => 1,
			'data'   => $comments
		] );
	}

	public function like( Request $request ) {
		$userId = $this->user->id;
		$postId = $request->input( 'post_id' );

		$check = Functions::checkLikePostApi( $postId, $userId );

		$post = SocialPost::find( $postId );

		if ( ! $post ) {
			return response( [
				'status'  => 0,
				'message' => 'Dữ liệu không hợp lệ'
			] );
		}

		$status = true;
		if ( $check ) {
			\DB::table( 'user_posts' )->where( 'user_id', $userId )
			   ->where( 'social_post_id', $postId )->delete();

			$status  = false;
			$message = 'Thích';
			\DB::table( 'social_posts' )->where( 'id', $postId )->decrement( 'number_likes' );
		} else {
			\DB::table( 'user_posts' )->insert( [
				'user_id'        => $userId,
				'social_post_id' => $postId,
				'created_at'     => Carbon::now()->toDateTimeString(),
				'updated_at'     => Carbon::now()->toDateTimeString(),
			] );
			\DB::table( 'social_posts' )->where( 'id', $postId )->increment( 'number_likes' );
			$message = 'Đã thích';

            $payload = json_encode( [
                'id'   => $post->id,
                'type' => config( 'constants.SOCIAL_POST' )
            ] );

            Notification::create( [
                'to_user' => $post->user_id,
                'title'   => 'Thông báo từ itro.vn',
                'user_id' => $this->user->id,
                'content' => $this->user->name . ' vừa thích bài viết của bạn: ' . $post->content,
                'payload' => $payload,
                'image'   => $this->user->image
            ] );
		}



		return response( [
			'status'  => 1,
			'message' => $message
		] );
	}

    /**
     * @api {post} /create-comment Tạo comment
     * @apiName create-comment
     * @apiGroup Social
     * @apiParam {String} content
     * @apiParam {File} images
     * @apiParam {String} post_id
     *
     * @apiDescription Api Lấy comments 1 post
     * @apiSuccess {Number} status 1 hoặc 0. 1 là thành công, 0 là không thành công.
     * @apiSuccess {String} message  Tin nhắn hệ thống.
     * @apiSuccess {String} data
     */


	public function createComment( Request $request ) {
		$content = $request->input( 'content' );
		$images  = $request->file( 'images' );
		$id      = $request->input( 'post_id' );

		$socialPost = SocialPost::find($id);

		if(!$socialPost)
		{
			return response([
				'status' => 0,
				'message' => 'Dữ liệu không hợp lệ'
			]);
		}

		$imageData = [];
		if ( isset( $images ) ) {


			foreach ( $images as $image ) {
				$imageData[] = Functions::uploadImage( $image );
			}
		}

		$comment = Comment::create( [
			'content'        => $content,
			'images'         => json_encode( $imageData ),
			'user_id'        => $this->user->id,
			'social_post_id' => $id,
		] );


		\DB::table( 'social_posts' )->where( 'id', $id )->increment( 'number_comments' );


		$comment->user = Functions::getUser( $comment->user_id );
		$retValImage   = [];
		foreach ( $imageData as $image ) {
			$retValImage[] = '/files/' . $image;
		}

		$comment->images = $retValImage;

		dispatch(new SendNotificationSocial($comment, $socialPost));

		return response( [
			'status' => 1,
			'data'   => $comment,
		] );
	}

	public function createPost( Request $request ) {
		$content  = $request->input( 'content' );
		$images   = $request->file( 'images-post' );
		$hostelId = $request->input( 'hostel_id' );

		$imageData = [];
		if ( isset( $images ) ) {
			foreach ( $images as $image ) {
				$imageData[] = Functions::uploadImage( $image );
			}
		}

		$post = SocialPost::create( [
			'content' => $content,
			'images'  => json_encode( $imageData ),
			'user_id' => $this->user->id
		] );

		// $userId = $this->user->id;
		if ( empty( $hostelId ) ) {
			$hostelId = Functions::getHostelByUser( $this->user );
		}

		if ( ! empty( $hostelId ) ) {
			\DB::table( 'hostel_posts' )->insert([
				'social_post_id' => $post->id,
				'hostel_id'      => $hostelId,
				'created_at'     => Carbon::now()->toDateTimeString(),
				'updated_at'     => Carbon::now()->toDateTimeString()
			] );
		}

		$renters = RenterRoom::where( 'hostel_id', $hostelId );

		$payload = [
			'id'   => $post->id,
			'type' => config( 'constants.SOCIAL_POST' )
		];

		$payload = json_encode( $payload );

		$content = '';
		if ( $this->user->type == User::RENTER ) {
			$renters    = $renters->where( 'user_id', '<>', $this->user->id );
			$roomRenter = RenterRoom::where( 'user_id', $this->user->id )->first();
			if ( $roomRenter ) {
				$roomId = $roomRenter->room_id;
				$room   = Room::find( $roomId );
				if ( $room ) {
					$content = $this->user->name . ' (P' . $room->name . ') vừa đăng bài viết trên cộng đồng. Hãy xem ngay!';
				}
			}

			$hostel = Hostel::find( $hostelId );

			if ( $hostel ) {

				Notification::create( [
					'to_user'   => $hostel->owner_id,
					'hostel_id' => $hostelId,
					'title'     => 'Thông báo từ itro.vn',
					'user_id'   => $this->user->id,
					'content'   => $content,
					'payload'   => $payload,
					'image'     => $this->user->image
				] );
			}

		} else if ( $this->user->type == User::OWNER ) {
			$content = $this->user->name . ' (Chủ trọ) vừa đăng bài viết trên cộng đồng. Hãy xem ngay!';
		}

		$renters = $renters->pluck( 'user_id' )->toArray();


		foreach ( $renters as $renter ) {
			Notification::create( [
				'to_user'   => $renter,
				'hostel_id' => $hostelId,
				'title'     => 'Thông báo từ itro.vn',
				'user_id'   => $this->user->id,
				'content'   => $content,
				'payload'   => $payload,
				'image'     => $this->user->image
			] );
		}

		$retValImage = [];

		foreach ( $imageData as $image ) {
			$retValImage[] = '/files/' . $image;
		}

		$post->images = $retValImage;
		$post->user   = Functions::getUser( $post->user_id );


		return response( [
			'status'  => 1,
			'message' => 'Thành công',
			'data'    => $post
		] );
	}
}
