<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\PostCollection;
use App\Http\Resources\PostCommentCollection;
use App\Http\Resources\PostImageCollection;
use App\Http\Resources\PostResource;
use App\Models\Post;
use App\Models\PostBookmark;
use App\Models\PostImage;
use App\Models\PostLike;
use App\Models\Province;
use App\Traits\HttpResponses;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class APIPostController extends Controller
{
    use HttpResponses;

    private $limit = 6;

    public function index()
    {
        $posts = Post::where('user_id', '<>', Auth::id())->where('status', true)->limit(24)->get();
        return new PostCollection($posts);
    }

    public function profilePosts()
    {
        $posts = Post::where('user_id', '=', Auth::id())->where('status', true)->limit(24)->get();
        return new PostCollection($posts);
    }

    public function store(Request $request)
    {
        /* $attrs = $request->validate([
            // 'body' => 'required|string'
        ]); */

        // return $this->abort();

        /*    $lat = $request->latitude;
        $lng = $request->longitude;
        $data = file_get_contents("https://maps.google.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false&key=AIzaSyA8DS8wJ3n43UCASASr8J4Fx_nrFIfUtiY");
        $data = json_decode($data);
        // return $data;
        $add_array  = $data->results;
        $add_array = $add_array[0];
        $add_array = $add_array->address_components;
        $country = "Not found";
        $state = "Not found";
        $city = "Not found";
        foreach ($add_array as $key) {
            if ($key->types[0] == 'administrative_area_level_2') {
                $city = $key->long_name;
            }
            if ($key->types[0] == 'administrative_area_level_1') {
                $state = $key->long_name;
            }
            if ($key->types[0] == 'country') {
                $country = $key->long_name;
            }
        }
        // return "Country : ".$country." ,State : ".strtolower($state)." ,City : ".$city;
        $province =  Province::where('name_en', strtolower($state))->first(); */

        $newPost = Post::create([
            'user_id' => Auth::id(),
            'latitude' => $request['latitude'],
            'longitude' => $request['longitude'],
            'place_id' => $request['place_id'],
            'google_place_name' => $request['google_place_name'],
            'google_place_id' => $request['google_place_id'],
            'google_place_url' => $request['google_place_url'],
            'google_place_address' => $request['google_place_address'],
            'description' => $request['description'],
            'province_id' => $request['province_id'],
            // 'province_id' => $province?->id,
            'like_count' => 0,
            'comment_count' => 0,
            'language_code' => $request['language_code'],
            'enable_comment' => $request['enable_comment'] ?? true,
            'is_public' => $request['is_public'] ?? true,
            'status' => $request['status'] ?? true,
        ]);

        /*  if ($request->hasfile('images')) {
            $request->validate([
                'images' => 'required',
                'images.*' => 'mimes:jpeg,jpg,png,gif,csv,txt,pdf|max:2048'
            ]);
            foreach ($request->file('images') as $file) {
                $name = Carbon::now()->timestamp . '_' . $file->getClientOriginalName();
                $hostwithHttp = request()->getSchemeAndHttpHost();
                $file->move(public_path() . '/images/posts/', $name);   //move files
                $path = $hostwithHttp . '/images/posts/' . $name;     //set path
                $postImage = new PostImage();
                $postImage->post_id = $newPost->id;
                $postImage->description = $name;
                $postImage->image_url = $path;
                $postImage->save();
            }
        } */

        $post = Post::findOrFail($newPost->id);

        return new PostResource($post);
    }

    public function upload(Request $request, String $postId)
    {

        $request->validate([
            'images' => 'required',
            'images.*' => 'mimes:jpeg,jpg,png,gif,csv,txt,pdf'
        ]);

        if ($request->hasfile('images')) {
            foreach ($request->file('images') as $file) {
                $name = $file->getClientOriginalName();
                $hostwithHttp = request()->getSchemeAndHttpHost();
                $file->move(public_path() . '/images/posts/', $name);   //move files
                $path = $hostwithHttp . '/images/posts/' . $name;     //set path

                $postImage = new PostImage();
                $postImage->post_id = $postId;
                $postImage->description = $name;
                $postImage->image_url = $path;
                $postImage->save();
            }
        }
        // return $this->success(null,'OK OK');
        $postImages = PostImage::where('post_id', $postId)->get();
        return $this->success(
            new PostImageCollection($postImages),
            'Post Images have been uploaded succesfully'
        );
        // $postImages->toJson(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }

    public function show($id)
    {
        $post = Post::with('images')->find($id);
        return new PostResource($post);
    }

    public function update(Request $request)
    {
         $attrs = $request->validate([
            'id' => 'required',
            'description' => 'required',
            'enable_comment' => 'required',
            'is_public' => 'required',
            'google_place_name'=> 'nullable',
            'google_place_id'=> 'nullable',
            'google_place_url'=> 'nullable',
            'google_place_address'=> 'nullable',
            'latitude'=> 'nullable',
            'longitude'=> 'nullable',
        ]);

        $post = Post::find($request->id);
        $post->update($attrs);

        return new PostResource($post);
    }

    public function destroy($id)
    {
        //
    }

    public function inactive(Request $request)
    {
        $validated = $request->validate([
            'post_id' => 'required',
        ]);
        $post = Post::find($validated['post_id']);
        if(!$post){
            $this->abort();
        }
        $this->isNotAuthorized($post);
        $post->update([
            'status' => false,
        ]);

        return $this->success(
            data: null,
            message: 'Post has been deactivated successfully'
        );
    }

    private function isNotAuthorized($post)
    {
        if (Auth::user()->id !== $post->user_id) {
            return $this->error('', 'You are not authorized to make this request', 403);
        }
    }

    public function getPosts(Request $request)
    {
        $search       = $request['search'];
        $userId       = $request['user_id'];
        $language     = $request['language'];
        $provinceId   = $request['province_id'];
        $offset       = $request['offset'] ?? 1;

        $results = Post::query();

        $results->when($search, function ($q) use ($search) {
            $q ->where('posts.description', 'LIKE', '%' . $search . '%');
        });

        $results->when($userId, function ($q) use ($userId) {
            $q ->where('posts.user_id', $userId);
        });

        $results->when($provinceId, function ($q) use ($provinceId) {
            $q ->where('posts.province_id', $provinceId);
        });

        $results->when($language, function ($q) use ($language) {
            $q ->where('posts.language_code', $language);
        });

        // $posts = $results->limit(24)->get();

        // $posts = Post::where('user_id', '<>', Auth::id())->where('status', true)->limit(24)->get();

        /* $filter = $request['filter'];
        $language = $request['language'] ?? 'th';

        if ($filter != null) {
            $posts = Post::where('description', 'like', '%' . $filter . '%')
                ->where('user_id', '!=', Auth::id())
                ->where('status', true)
                ->where('language_code', $language)
                ->orderBy('id', 'ASC')
                ->paginate($this->limit, ['*'], 'page', $offset)->items();
        } else {
            $posts = Post::where('user_id', '<>', Auth::id())
                ->where('status', true)
                ->where('language_code', $language)
                ->orderBy('id', 'DESC')
                ->paginate($this->limit, ['*'], 'page', $offset)->items();
        } */

         $posts = $results
                    ->where('user_id', '<>', Auth::id())
                    ->where('status', true)
                    ->orderBy('id', 'DESC')
                    ->paginate($this->limit, ['*'], 'page', $offset)
                    ->items();

        return $this->success(
            data:  new PostCollection($posts),
            message: 'Posts have been responded successdully'
        );
    }

    public function getPostsByHashtag(Request $request, $offset)
    {
        $hashtag = $request->hashtag;
        $posts = Post::with(['user', 'province', 'place', 'images'])
            ->where('description', 'like', '%' . $hashtag . '%')
            ->where('user_id', '!=', Auth::id())
            ->where('status', true)
            ->orderBy('id', 'DESC')
            ->paginate($this->limit, ['*'], 'page', $offset)->items();
        return $posts;
    }

    public function like(Request $request)
    {
        $attrs = $request->validate([
            'post_id' => 'required',
            'user_id' => 'required',
        ]);
        $message = 'Post has been successfully liked';
        $postLike = PostLike::where('post_id', $attrs['post_id'])->where('user_id', $attrs['user_id'])->first();
        $post = Post::find($attrs['post_id']);
        if ($post == null) {
            return $this->error(null, 'data not found', 404);
        }
        if ($postLike == null) {
            $postLike =  PostLike::create([
                'post_id' =>  $attrs['post_id'],
                'user_id' =>  $attrs['user_id'],
            ]);
            $post->update([
                'like_count' => $post->like_count + 1,
            ]);
        } else {
            $postLike->delete();
            $post->update([
                'like_count' => $post->like_count - 1,
            ]);
            $message = 'Post has been successfully unliked';
        }

        return $this->success($post, $message, 200);
    }

    public function getComments($postId)
    {
        $comments = Post::find($postId)->comments()->where('status', true)->orderBy('id', 'DESC')->limit(60)->get();
        // return $comments;
        return new PostCommentCollection($comments);
    }

    public function bookmark(Request $request)
    {
        $attrs = $request->validate([
            'post_id' => 'required',
            'user_id' => 'required',
        ]);
        $message = 'Bookmark has been successfully added';
        $postBookmark = PostBookmark::where('post_id', $attrs['post_id'])->where('user_id', $attrs['user_id'])->first();
        $post = Post::find($attrs['post_id']);
        if ($post == null) {
            return $this->error(null, 'data not found', 404);
        }
        if ($postBookmark == null) {
            $postBookmark =  PostBookmark::create([
                'post_id' =>  $attrs['post_id'],
                'user_id' =>  $attrs['user_id'],
            ]);
            $post->update([
                'like_count' => $post->like_count + 1,
            ]);
        } else {
            $postBookmark->delete();
            $message = 'Bookmark has been successfully deleted';
        }

        return $this->success(
            data: $post,
            message: $message);
    }
}
