<?php
namespace App\Http\Controllers;
use App\Models\{News,Organization};
use App\Services\{ImageOptimizerService,OrganizationAccess};
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class NewsController extends Controller {
    public function index(Request $request){
        $items=OrganizationAccess::apply(News::with('organization')->latest(),$request->user())->paginate(20);
        $orgs=$request->user()->isSuperAdmin()?Organization::orderBy('name')->get():Organization::whereKey($request->user()->organization_id)->get();
        return view('admin.news.index',compact('items','orgs'));
    }
    public function store(Request $request, ImageOptimizerService $images){
        $data=$request->validate(['organization_id'=>'required|exists:organizations,id','title'=>'required|max:220','excerpt'=>'nullable|max:500','content'=>'required','category'=>'nullable|max:80','status'=>'required|in:draft,review,published','featured_image'=>'nullable|image|max:10240']);
        if (!$request->user()->isSuperAdmin()) $data['organization_id']=$request->user()->organization_id;
        $data['user_id']=$request->user()->id; $data['slug']=Str::slug($data['title']).'-'.Str::lower(Str::random(4));
        if ($request->hasFile('featured_image')) $data['featured_image']=$images->storeWebp($request->file('featured_image'),'news');
        if ($data['status']==='published') $data['published_at']=now(); News::create($data);
        return back()->with('success','Berita berhasil disimpan. Foto otomatis dioptimasi ke WebP bila GD tersedia.');
    }
}
