<?php

namespace App\Http\Controllers\CommunityManager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Str;

class BlogController extends Controller
{
    public function index()
    {
        $posts = Post::query()->with('author:id,name')->latest()->paginate(20);
        
        return view('community.blog.index', compact('posts'));
    }

    public function create()
    {
        return view('community.blog.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'excerpt' => 'nullable|string|max:500',
            'category' => 'nullable|string|max:100',
            'tags' => 'nullable|string',
            'image' => 'nullable|image|max:2048',
            'is_published' => 'boolean',
        ]);
        
        $excerpt = $request->excerpt;
        if (!$excerpt) {
            $excerpt = Str::limit(strip_tags((string) $request->content), 200);
        }

        $tags = null;
        if ($request->filled('tags')) {
            $tags = collect(explode(',', (string) $request->tags))
                ->map(fn ($t) => trim($t))
                ->filter(fn ($t) => $t !== '')
                ->unique()
                ->values()
                ->all();
        }

        $isPublished = $request->boolean('is_published');

        $data = [
            'title' => $request->title,
            'slug' => Str::slug($request->title),
            'content' => $request->content,
            'excerpt' => $excerpt,
            'category' => $request->category,
            'tags' => $tags,
            'author_id' => auth()->id(),
            'status' => $isPublished ? 'published' : 'draft',
            'published_at' => $isPublished ? now() : null,
        ];
        
        if ($request->hasFile('image')) {
            $data['featured_image'] = $request->file('image')->store('blog', 'public');
        }
        
        Post::create($data);
        
        return redirect()->route('community.blog.index')
            ->with('success', 'Article cree avec succes.');
    }

    public function edit(Post $post)
    {
        return view('community.blog.edit', compact('post'));
    }

    public function update(Request $request, Post $post)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'excerpt' => 'nullable|string|max:500',
            'category' => 'nullable|string|max:100',
            'tags' => 'nullable|string',
            'image' => 'nullable|image|max:2048',
            'is_published' => 'boolean',
        ]);
        
        $excerpt = $request->excerpt;
        if (!$excerpt) {
            $excerpt = Str::limit(strip_tags((string) $request->content), 200);
        }

        $tags = null;
        if ($request->filled('tags')) {
            $tags = collect(explode(',', (string) $request->tags))
                ->map(fn ($t) => trim($t))
                ->filter(fn ($t) => $t !== '')
                ->unique()
                ->values()
                ->all();
        }

        $isPublished = $request->boolean('is_published');

        $data = [
            'title' => $request->title,
            'content' => $request->content,
            'excerpt' => $excerpt,
            'category' => $request->category,
            'tags' => $tags,
            'status' => $isPublished ? 'published' : 'draft',
            'published_at' => $isPublished ? ($post->published_at ?: now()) : null,
        ];

        if ($request->title !== $post->title) {
            $data['slug'] = Str::slug($request->title);
        }
        
        if ($request->hasFile('image')) {
            $data['featured_image'] = $request->file('image')->store('blog', 'public');
        }
        
        $post->update($data);
        
        return redirect()->route('community.blog.index')
            ->with('success', 'Article mis a jour.');
    }

    public function destroy(Post $post)
    {
        $post->delete();
        
        return back()->with('success', 'Article supprime.');
    }

    public function togglePublish(Post $post)
    {
        $isCurrentlyPublished = $post->status === 'published' && $post->published_at && $post->published_at->lte(now());
        $nextPublished = !$isCurrentlyPublished;

        $post->update([
            'status' => $nextPublished ? 'published' : 'draft',
            'published_at' => $nextPublished ? now() : null,
        ]);
        
        return back()->with('success', 'Statut de publication mis a jour.');
    }
}
