<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlogPost;
use App\Services\MediaUsageSyncService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class BlogPostController extends Controller
{
    public function index()
    {
        $blogPosts = BlogPost::query()
            ->orderByDesc('is_featured')
            ->orderBy('sort_order')
            ->orderByDesc('published_at')
            ->orderByDesc('created_at')
            ->paginate(10);

        return view('admin.blog-posts.index', compact('blogPosts'));
    }

    public function create()
    {
        return view('admin.blog-posts.create');
    }

    public function store(Request $request, MediaUsageSyncService $mediaUsageSyncService)
    {
        $blogPost = BlogPost::create($this->validatedData($request));
        $this->syncFeaturedFlag($blogPost);
        $mediaUsageSyncService->syncForBlogPost($blogPost);

        return redirect()->route('admin.blog-posts.index')->with('success', 'Blog post created successfully.');
    }

    public function edit(BlogPost $blogPost)
    {
        return view('admin.blog-posts.edit', compact('blogPost'));
    }

    public function update(Request $request, BlogPost $blogPost, MediaUsageSyncService $mediaUsageSyncService)
    {
        $blogPost->update($this->validatedData($request, $blogPost));
        $this->syncFeaturedFlag($blogPost);
        $mediaUsageSyncService->syncForBlogPost($blogPost);

        return redirect()->route('admin.blog-posts.index')->with('success', 'Blog post updated successfully.');
    }

    public function destroy(BlogPost $blogPost)
    {
        $blogPost->delete();

        return redirect()->route('admin.blog-posts.index')->with('success', 'Blog post deleted successfully.');
    }

    protected function validatedData(Request $request, ?BlogPost $blogPost = null): array
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'slug' => ['required', 'string', 'max:255', Rule::unique('blog_posts', 'slug')->ignore($blogPost?->id)],
            'badge' => ['nullable', 'string', 'max:255'],
            'reading_time' => ['nullable', 'string', 'max:255'],
            'excerpt' => ['nullable', 'string'],
            'content' => ['nullable', 'string'],
            'featured_image_media_id' => ['nullable', 'integer', 'exists:media,id'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
            'is_featured' => ['nullable', 'boolean'],
            'is_published' => ['nullable', 'boolean'],
            'published_at' => ['nullable', 'date'],
            'seo_title' => ['nullable', 'string', 'max:255'],
            'seo_description' => ['nullable', 'string'],
        ]);

        $data['is_featured'] = $request->boolean('is_featured');
        $data['is_published'] = $request->boolean('is_published');
        $data['sort_order'] = (int) ($data['sort_order'] ?? 0);

        if ($data['is_published'] && blank($data['published_at'] ?? null)) {
            $data['published_at'] = now();
        }

        if (! $data['is_published'] && blank($data['published_at'] ?? null)) {
            $data['published_at'] = null;
        }

        return $data;
    }

    protected function syncFeaturedFlag(BlogPost $blogPost): void
    {
        if (! $blogPost->is_featured) {
            return;
        }

        BlogPost::query()
            ->where('id', '!=', $blogPost->getKey())
            ->update(['is_featured' => false]);
    }
}
