<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreNewsRequest;
use App\Models\AuditLog;
use App\Models\News;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

class NewsController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/News/Index', [
            'news' => News::query()->latest()->paginate(20),
        ]);
    }

    public function store(StoreNewsRequest $request): RedirectResponse
    {
        $data = $request->safe()->except('image');

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

        $news = News::create([
            ...$data,
            'user_id' => $request->user()->id,
        ]);

        AuditLog::record('news.created', $news, $data);

        return back()->with('success', 'News post created.');
    }

    public function update(StoreNewsRequest $request, News $news): RedirectResponse
    {
        $data = $request->safe()->except('image');

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

        $news->update($data);

        AuditLog::record('news.updated', $news, $data);

        return back()->with('success', 'News post updated.');
    }

    public function destroy(News $news): RedirectResponse
    {
        AuditLog::record('news.deleted', $news);

        $news->delete();

        return back()->with('success', 'News post deleted.');
    }
}
