<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Http\Resources\PostResource;
use App\Models\Post;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PostController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Post::with(['user', 'category', 'images', 'tags'])
            ->where('status', 'open');

        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        if ($request->filled('category')) {
            $query->whereHas('category', fn ($q) => $q->where('slug', $request->category));
        }

        if ($request->filled('is_remote')) {
            $query->where('is_remote', filter_var($request->is_remote, FILTER_VALIDATE_BOOLEAN));
        }

        if ($request->filled('location')) {
            $query->where('location', 'like', '%' . $request->location . '%');
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhereHas('tags', fn ($t) => $t->where('tag', 'like', "%{$search}%"));
            });
        }

        $sort = $request->get('sort', 'latest');
        if ($sort === 'popular') {
            $query->withCount('applications')->orderByDesc('applications_count');
        } else {
            $query->latest();
        }

        $posts = $query->paginate(15);

        return response()->json([
            'success' => true,
            'data' => PostResource::collection($posts),
            'meta' => [
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'total' => $posts->total(),
            ],
        ]);
    }

    public function store(StorePostRequest $request): JsonResponse
    {
        $post = $request->user()->posts()->create([
            ...$request->validated(),
            'status' => 'open',
        ]);

        if ($request->filled('tags')) {
            foreach ($request->tags as $tag) {
                $post->tags()->create(['tag' => $tag]);
            }
        }

        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('posts', 'public');
            $post->images()->create(['image_path' => $path, 'order' => 0]);
        }

        $post->load(['user', 'category', 'images', 'tags']);

        return response()->json([
            'success' => true,
            'data' => new PostResource($post),
            'message' => 'Post berhasil dibuat',
        ], 201);
    }

    public function show(Post $post): JsonResponse
    {
        $post->load(['user', 'category', 'images', 'tags']);

        return response()->json([
            'success' => true,
            'data' => new PostResource($post),
        ]);
    }

    public function update(UpdatePostRequest $request, Post $post): JsonResponse
    {
        $this->authorizeOwner($request, $post);

        $post->update($request->validated());

        if ($request->has('tags')) {
            $post->tags()->delete();
            foreach ($request->tags as $tag) {
                $post->tags()->create(['tag' => $tag]);
            }
        }

        if ($request->hasFile('image')) {
            foreach ($post->images as $img) {
                Storage::disk('public')->delete($img->image_path);
                $img->delete();
            }
            $path = $request->file('image')->store('posts', 'public');
            $post->images()->create(['image_path' => $path, 'order' => 0]);
        } elseif ($request->boolean('remove_image')) {
            foreach ($post->images as $img) {
                Storage::disk('public')->delete($img->image_path);
                $img->delete();
            }
        }

        $post->load(['user', 'category', 'images', 'tags']);

        return response()->json([
            'success' => true,
            'data' => new PostResource($post),
            'message' => 'Post berhasil diperbarui',
        ]);
    }

    public function destroy(Request $request, Post $post): JsonResponse
    {
        $this->authorizeOwner($request, $post);

        $post->delete();

        return response()->json([
            'success' => true,
            'message' => 'Post berhasil dihapus',
        ]);
    }

    public function updateStatus(Request $request, Post $post): JsonResponse
    {
        $this->authorizeOwner($request, $post);

        $request->validate([
            'status' => 'required|in:open,taken,done,cancelled',
        ]);

        $post->update(['status' => $request->status]);

        return response()->json([
            'success' => true,
            'data' => new PostResource($post),
            'message' => 'Status post berhasil diperbarui',
        ]);
    }

    public function userPosts(string $username): JsonResponse
    {
        $posts = Post::with(['user', 'category', 'images', 'tags'])
            ->whereHas('user', fn ($q) => $q->where('username', $username))
            ->latest()
            ->paginate(15);

        return response()->json([
            'success' => true,
            'data' => PostResource::collection($posts),
            'meta' => [
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'total' => $posts->total(),
            ],
        ]);
    }

    private function authorizeOwner(Request $request, Post $post): void
    {
        if ($request->user()->id !== $post->user_id) {
            abort(403, 'Kamu tidak berhak melakukan aksi ini');
        }
    }
}
