<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NewsArticle;
use App\Models\NewsGallery;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class NewsAdminController extends Controller
{
    public function index()
    {
        $newsArticles = NewsArticle::orderByDesc('published_at')->orderByDesc('created_at')->paginate(15);
        return view('admin.news.index', compact('newsArticles'));
    }

    public function create()
    {
        return view('admin.news.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:news_articles,slug',
            'excerpt' => 'nullable|string|max:500',
            'content' => 'required|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'category' => 'nullable|string|max:100',
            'author' => 'nullable|string|max:255',
            'published_at' => 'nullable|date',
            'status' => 'nullable|in:draft,published,archived',
            'reading_time' => 'nullable|integer|min:1',
            'featured' => 'boolean',
            'seo_title' => 'nullable|string|max:70',
            'seo_description' => 'nullable|string|max:160',
        ]);

        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('news', 'public');
        }

        $data['featured'] = $request->boolean('featured');

        $article = NewsArticle::create($data);

        if ($request->hasFile('gallery')) {
            foreach ($request->file('gallery') as $i => $file) {
                $path = $file->store('news/gallery', 'public');
                $article->gallery()->create([
                    'file_path' => $path,
                    'sort_order' => $i,
                ]);
            }
        }

        return redirect()->route('admin.news.index')->with('success', 'Notícia criada com sucesso.');
    }

    public function edit($id)
    {
        $newsArticle = NewsArticle::with('gallery')->findOrFail($id);
        return view('admin.news.edit', compact('newsArticle'));
    }

    public function update(Request $request, $id)
    {
        $news = NewsArticle::with('gallery')->findOrFail($id);

        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:news_articles,slug,' . $id,
            'excerpt' => 'nullable|string|max:500',
            'content' => 'required|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048',
            'category' => 'nullable|string|max:100',
            'author' => 'nullable|string|max:255',
            'published_at' => 'nullable|date',
            'status' => 'nullable|in:draft,published,archived',
            'reading_time' => 'nullable|integer|min:1',
            'featured' => 'boolean',
            'seo_title' => 'nullable|string|max:70',
            'seo_description' => 'nullable|string|max:160',
        ]);

        if ($request->hasFile('image')) {
            if ($news->image) {
                Storage::disk('public')->delete($news->image);
            }
            $data['image'] = $request->file('image')->store('news', 'public');
        }

        $data['featured'] = $request->boolean('featured');

        $news->update($data);

        if ($request->hasFile('gallery')) {
            $maxOrder = $news->gallery->max('sort_order') ?? 0;
            foreach ($request->file('gallery') as $i => $file) {
                $path = $file->store('news/gallery', 'public');
                $news->gallery()->create([
                    'file_path' => $path,
                    'sort_order' => $maxOrder + $i + 1,
                ]);
            }
        }

        return redirect()->route('admin.news.index')->with('success', 'Notícia atualizada com sucesso.');
    }

    public function destroy($id)
    {
        $news = NewsArticle::with('gallery')->findOrFail($id);

        if ($news->image) {
            Storage::disk('public')->delete($news->image);
        }

        foreach ($news->gallery as $item) {
            Storage::disk('public')->delete($item->file_path);
        }

        $news->gallery()->delete();
        $news->delete();

        return redirect()->route('admin.news.index')->with('success', 'Notícia removida com sucesso.');
    }

    public function destroyGallery($id, $galleryId)
    {
        $gallery = NewsGallery::where('news_article_id', $id)->findOrFail($galleryId);
        Storage::disk('public')->delete($gallery->file_path);
        $gallery->delete();

        return redirect()->back()->with('success', 'Imagem removida da galeria.');
    }
}