<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Blog;
use App\Services\AdminActivityLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class BlogController extends Controller
{
    public function index(): View
    {
        return view('admin.cms.blogs', [
            'blogs' => Blog::query()->latest('id')->get(),
        ]);
    }

    public function store(Request $request, AdminActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'title' => ['required', 'string', 'max:191'],
            'slug' => ['nullable', 'string', 'max:191'],
            'excerpt' => ['nullable', 'string', 'max:500'],
            'content' => ['required', 'string'],
            'featured_image' => ['nullable', 'image', 'max:3072'],
            'meta_title' => ['nullable', 'string', 'max:191'],
            'meta_description' => ['nullable', 'string', 'max:600'],
            'status' => ['required', 'in:draft,published'],
            'published_at' => ['nullable', 'date'],
        ]);

        $slug = $this->resolveUniqueSlug($validated['slug'] ?? null, $validated['title']);

        $imagePath = null;
        if ($request->hasFile('featured_image')) {
            $imagePath = $request->file('featured_image')->store('blogs', 'public');
        }

        $blog = Blog::query()->create([
            'title' => $validated['title'],
            'slug' => $slug,
            'excerpt' => $validated['excerpt'] ?? null,
            'content' => $validated['content'],
            'featured_image_path' => $imagePath,
            'meta_title' => $validated['meta_title'] ?? null,
            'meta_description' => $validated['meta_description'] ?? null,
            'status' => $validated['status'],
            'published_at' => $validated['status'] === 'published'
                ? ($validated['published_at'] ?? now())
                : null,
            'author_id' => auth()->id(),
        ]);

        $logger->log('blog.create', Blog::class, $blog->id);

        return back()->with('status', 'Blog created.');
    }

    public function update(Request $request, Blog $blog, AdminActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'title' => ['required', 'string', 'max:191'],
            'slug' => ['nullable', 'string', 'max:191'],
            'excerpt' => ['nullable', 'string', 'max:500'],
            'content' => ['required', 'string'],
            'featured_image' => ['nullable', 'image', 'max:3072'],
            'meta_title' => ['nullable', 'string', 'max:191'],
            'meta_description' => ['nullable', 'string', 'max:600'],
            'status' => ['required', 'in:draft,published'],
            'published_at' => ['nullable', 'date'],
        ]);

        $slug = $this->resolveUniqueSlug($validated['slug'] ?? null, $validated['title'], $blog->id);

        if ($request->hasFile('featured_image')) {
            $blog->featured_image_path = $request->file('featured_image')->store('blogs', 'public');
        }

        $blog->title = $validated['title'];
        $blog->slug = $slug;
        $blog->excerpt = $validated['excerpt'] ?? null;
        $blog->content = $validated['content'];
        $blog->meta_title = $validated['meta_title'] ?? null;
        $blog->meta_description = $validated['meta_description'] ?? null;
        $blog->status = $validated['status'];
        $blog->published_at = $validated['status'] === 'published'
            ? ($validated['published_at'] ?? ($blog->published_at ?? now()))
            : null;
        $blog->save();

        $logger->log('blog.update', Blog::class, $blog->id);

        return back()->with('status', 'Blog updated.');
    }

    public function destroy(Blog $blog, AdminActivityLogger $logger): RedirectResponse
    {
        $blogId = $blog->id;
        $blog->delete();
        $logger->log('blog.delete', Blog::class, $blogId);

        return back()->with('status', 'Blog deleted.');
    }

    private function resolveUniqueSlug(?string $slug, string $title, ?int $ignoreId = null): string
    {
        $base = Str::slug($slug ?: $title);
        if ($base === '') {
            $base = 'blog';
        }

        $candidate = $base;
        $i = 1;
        while (Blog::query()
            ->when($ignoreId, fn ($query) => $query->where('id', '!=', $ignoreId))
            ->where('slug', $candidate)
            ->exists()) {
            $candidate = $base.'-'.$i;
            $i++;
        }

        return $candidate;
    }
}
