<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\News;
use App\Models\NewsCategory;
use App\Models\ActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class NewsController extends Controller
{
    public function index()
    {
        $news = News::with(['category', 'author'])->latest()->paginate(15);
        return view('admin.news.index', compact('news'));
    }

    public function create()
    {
        $categories = NewsCategory::all();
        return view('admin.news.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title'       => 'required|string|max:255',
            'category_id' => 'required|exists:news_categories,id',
            'content'     => 'required|string',
            'status'      => 'required|in:published,draft',
            'is_featured' => 'nullable|boolean',
            'image'       => 'nullable|image|mimes:jpeg,png,jpg,webp|max:3072',
        ]);

        $imagePath = null;
        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '_' . Str::slug($request->title) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/news'), $filename);
            $imagePath = 'uploads/news/' . $filename;
        }

        $news = News::create([
            'title'       => $request->title,
            'slug'        => Str::slug($request->title) . '-' . time(),
            'category_id' => $request->category_id,
            'content'     => $request->content,
            'image'       => $imagePath,
            'is_featured' => $request->boolean('is_featured'),
            'status'      => $request->status,
            'author_id'   => Auth::id(),
        ]);

        ActivityLog::create([
            'user_id' => Auth::id(),
            'action'  => 'create_news',
            'details' => "Published news: {$news->title}",
            'ip_address' => request()->ip()
        ]);

        return redirect()->route('admin.news.index')->with('success', 'News article published successfully!');
    }

    public function edit(News $news)
    {
        $categories = NewsCategory::all();
        return view('admin.news.edit', compact('news', 'categories'));
    }

    public function update(Request $request, News $news)
    {
        $request->validate([
            'title'       => 'required|string|max:255',
            'category_id' => 'required|exists:news_categories,id',
            'content'     => 'required|string',
            'status'      => 'required|in:published,draft',
            'is_featured' => 'nullable|boolean',
            'image'       => 'nullable|image|mimes:jpeg,png,jpg,webp|max:3072',
        ]);

        if ($request->hasFile('image')) {
            if ($news->image && file_exists(public_path($news->image))) {
                unlink(public_path($news->image));
            }
            $file = $request->file('image');
            $filename = time() . '_' . Str::slug($request->title) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/news'), $filename);
            $news->image = 'uploads/news/' . $filename;
        }

        $news->update([
            'title'       => $request->title,
            'category_id' => $request->category_id,
            'content'     => $request->content,
            'is_featured' => $request->boolean('is_featured'),
            'status'      => $request->status,
        ]);
        $news->save();

        ActivityLog::create([
            'user_id' => Auth::id(),
            'action'  => 'update_news',
            'details' => "Updated news: {$news->title}",
            'ip_address' => request()->ip()
        ]);

        return redirect()->route('admin.news.index')->with('success', 'News article updated!');
    }

    public function destroy(News $news)
    {
        if ($news->image && file_exists(public_path($news->image))) {
            unlink(public_path($news->image));
        }
        $news->delete();
        return redirect()->route('admin.news.index')->with('success', 'News article deleted.');
    }

    // Category Management
    public function categories()
    {
        $categories = NewsCategory::withCount('news')->get();
        return view('admin.news.categories', compact('categories'));
    }

    public function storeCategory(Request $request)
    {
        $request->validate(['name' => 'required|string|max:100|unique:news_categories,name']);
        NewsCategory::create([
            'name' => $request->name,
            'slug' => Str::slug($request->name),
        ]);
        return back()->with('success', 'Category added!');
    }

    public function destroyCategory(NewsCategory $newsCategory)
    {
        $newsCategory->delete();
        return back()->with('success', 'Category deleted.');
    }
}
