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

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

class NewsController extends Controller {
    public function index() {
        return response()->json(News::latest()->get());
    }

    public function show($id) {
        return response()->json(News::findOrFail($id));
    }

    public function store(Request $request) {
        $data = $request->only(['title', 'content']);
        if ($request->hasFile('news_image')) {
            $data['image'] = $request->file('news_image')->store('news', 'public');
        }
        $news = News::create($data);
        return response()->json($news);
    }

    public function update(Request $request, $id) {
        $news = News::findOrFail($id);
        $data = $request->only(['title', 'content']);
        if ($request->hasFile('news_image')) {
            if ($news->image) Storage::disk('public')->delete($news->image);
            $data['image'] = $request->file('news_image')->store('news', 'public');
        }
        $news->update($data);
        return response()->json(['message' => 'Success']);
    }

    public function destroy($id) {
        $news = News::findOrFail($id);
        if ($news->image) Storage::disk('public')->delete($news->image);
        $news->delete();
        return response()->json(['message' => 'Deleted']);
    }
}