<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Berita;
use Illuminate\Http\Request;

class BeritaController extends Controller
{
    public function index()
    {
        $beritas = Berita::where('status', 'published')->latest()->get();

        return response()->json([
            'success' => true,
            'message' => 'Daftar berita',
            'data' => $beritas->map(fn($item) => $this->transform($item)),
        ]);
    }

    public function show($id)
    {
        $berita = Berita::find($id);

        if (!$berita || $berita->status !== 'published') {
            return response()->json([
                'success' => false,
                'message' => 'Berita tidak ditemukan',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'message' => 'Detail berita',
            'data' => $this->transform($berita),
        ]);
    }

    private function transform(Berita $berita)
    {
        return [
            'id' => $berita->id,
            'judul' => $berita->judul,
            'kategori' => $berita->kategori,
            'ringkasan' => $berita->ringkasan,
            'isi' => $berita->isi,
            'penulis' => $berita->penulis,
            'gambar_url' => $berita->gambar ? asset('storage/' . $berita->gambar) : null,
            'created_at' => $berita->created_at->toDateTimeString(),
        ];
    }
}
