<?php

namespace App\Http\Controllers\Backend;

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

class SocialController extends AdminController
{
    //
    public function __construct()
    {
        Carbon::setLocale('vi');
    }

    public function index()
    {
        $items = Hostel::orderBy('id', 'desc');

        if (auth('backend')->check()) {
            if (auth('backend')->user()->type == User::OWNER) {
                $items = $items->where('owner_id', auth('backend')->user()->id);
            }
        }

        $items = $items->get();

        return view('admin.social.index', compact('items'));
    }

    public function getPosts(Request $request)
    {
        $page = $request->input('page');
        $lastId = $request->input('last_id');
	    $hostelId = $request->input( 'hostel_id' );

        $limit = 5;
        if(!empty($page)) {

            $offset = ($page - 1) * $limit;

            $posts = SocialPost::orderBy('social_posts.id', 'desc')
	            ->leftJoin( 'hostel_posts', 'social_posts.id', '=', 'hostel_posts.social_post_id' )
                ->limit($limit)
                ->offset($offset);
        } else if (!empty($lastId))
        {
            $posts = SocialPost::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);
	    }

	    $posts = $posts->get();

        return response([
            'status' => 1,
            'html' => view('admin.social.posts', compact('posts'))->render()
        ]);
    }

    public function like($id, Request $request)
    {
        $userId = auth('backend')->user()->id;
        $postId = $id;

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

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

        $check = Functions::checkLikePost($postId);

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

            $status = false;
            \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');
            $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' => auth('backend')->user()->id,
                'content' => auth('backend')->user()->name . ' vừa thích bài viết của bạn: ' . $post->content,
                'payload' => $payload,
                'image'   => auth('backend')->user()->image
            ] );
        }



        return response([
            'status' => 1,
            'html' => view('admin.social.like', compact('status', 'postId'))->render()
        ]);
    }

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

        $comments = Comment::where('social_post_id', $postId)->where('id', '<', $lastId)->limit(4)->get();

        return response([
            'status' => 1,
            'html' => view('admin.social.comments', compact('comments'))->render()
        ]);
    }

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

	    $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' => auth('backend')->user()->id,
            'social_post_id' => $id,
        ]);

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

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

        return response([
            'status' => 1,
            'html' => view('admin.social.single_comment', compact('comment'))->render()
        ]);
    }

    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' => auth('backend')->user()->id
        ]);

        $userId = auth('backend')->user()->id;
        if(empty($hostelId)) {
	        $hostelId = Functions::getHostelByUser(auth('backend')->user());
        }

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

        return response([
            'status' => 1,
            'html' => view('admin.social.single', compact('post'))->render()
        ]);
    }
}
