<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\BlogPost;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class BlogController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = BlogPost::with('author:id,name')->withTrashed(false);

        if ($request->filled('search')) {
            $s = $request->input('search');
            $query->where(function ($q) use ($s) {
                $q->where('title', 'like', "%{$s}%")
                  ->orWhere('excerpt', 'like', "%{$s}%");
            });
        }

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

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

        $posts = $query->orderByDesc('created_at')->paginate(12);

        return response()->json($posts);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title'            => 'required|string|max:255',
            'excerpt'          => 'nullable|string|max:500',
            'content'          => 'required|string',
            'cover_image'      => 'nullable|string|max:2048',
            'status'           => 'required|in:draft,published,archived',
            'category'         => 'nullable|string|max:100',
            'tags'             => 'nullable|array',
            'tags.*'           => 'string|max:50',
            'published_at'     => 'nullable|date',
            'meta_title'       => 'nullable|string|max:70',
            'meta_description' => 'nullable|string|max:320',
        ]);

        $validated['author_id'] = auth()->id();
        $validated['slug']      = Str::slug($validated['title']) . '-' . Str::lower(Str::random(5));

        // Always stamp published_at with server UTC now() when publishing.
        // If the user explicitly provided a past date, honour it (e.g. backdating).
        // If the field is empty or a future date, default to now() so the post is immediately visible.
        if ($validated['status'] === 'published') {
            $userDate = isset($validated['published_at']) && $validated['published_at'] !== ''
                ? $validated['published_at']
                : null;
            $validated['published_at'] = ($userDate && \Carbon\Carbon::parse($userDate)->isPast())
                ? $userDate
                : now();
        } else {
            $validated['published_at'] = null;
        }

        $post = BlogPost::create($validated);
        $post->load('author:id,name');

        return response()->json(['message' => 'Post created.', 'data' => $post], 201);
    }

    public function show(BlogPost $blog): JsonResponse
    {
        $blog->load('author:id,name');
        return response()->json($blog);
    }

    public function update(Request $request, BlogPost $blog): JsonResponse
    {
        $validated = $request->validate([
            'title'            => 'sometimes|string|max:255',
            'excerpt'          => 'nullable|string|max:500',
            'content'          => 'sometimes|string',
            'cover_image'      => 'nullable|string|max:2048',
            'status'           => 'sometimes|in:draft,published,archived',
            'category'         => 'nullable|string|max:100',
            'tags'             => 'nullable|array',
            'tags.*'           => 'string|max:50',
            'published_at'     => 'nullable|date',
            'meta_title'       => 'nullable|string|max:70',
            'meta_description' => 'nullable|string|max:320',
        ]);

        // Normalise empty string → null
        if (array_key_exists('published_at', $validated)) {
            $validated['published_at'] = ($validated['published_at'] !== '' && $validated['published_at'] !== null)
                ? $validated['published_at']
                : null;
        }

        // Auto-stamp published_at when publishing.
        // Honour explicit past dates (backdating); replace future dates with now() to publish immediately.
        $newStatus = $validated['status'] ?? $blog->status;
        if ($newStatus === 'published') {
            $userDate = $validated['published_at'] ?? null;
            if ($userDate && \Carbon\Carbon::parse($userDate)->isPast()) {
                // Explicit past date: keep it
                $validated['published_at'] = $userDate;
            } elseif (!$userDate && $blog->published_at && $blog->published_at->isPast()) {
                // No new date supplied, existing date is in the past: preserve it
                $validated['published_at'] = $blog->published_at;
            } else {
                // No date, or future date: stamp now() so post is immediately live
                $validated['published_at'] = now();
            }
        }

        $blog->update($validated);
        $blog->load('author:id,name');

        return response()->json(['message' => 'Post updated.', 'data' => $blog]);
    }

    public function destroy(BlogPost $blog): JsonResponse
    {
        $blog->delete();
        return response()->json(['message' => 'Post deleted.']);
    }

    public function uploadImage(Request $request): JsonResponse
    {
        $request->validate([
            'image' => 'required|image|max:4096|mimes:jpg,jpeg,png,gif,webp',
        ]);

        $path = $request->file('image')->store('blog', 'public');

        // Return a root-relative URL (/storage/...) so it resolves correctly on
        // any host or port (XAMPP on :80, artisan serve on :8000, production).
        // Never use Storage::disk('public')->url() here because that bakes in
        // APP_URL which may not match the browser's current origin.
        return response()->json([
            'url'  => '/storage/' . $path,
            'path' => $path,
        ]);
    }
}
