<?php
namespace App\Http\Controllers;
use App\Models\PopupAnnouncement;
use App\Services\ImageOptimizerService;
use Illuminate\Http\Request;
class PopupController extends Controller {
    public function index(){ $popups=PopupAnnouncement::latest()->get(); return view('admin.popups.index',compact('popups')); }
    public function store(Request $request, ImageOptimizerService $images){
        abort_unless($request->user()->isSuperAdmin(),403);
        $data=$request->validate(['title'=>'required|max:180','body'=>'required|max:2000','button_label'=>'nullable|max:80','button_url'=>'nullable|max:500','frequency'=>'required|in:always,once_session,once_day','starts_at'=>'nullable|date','ends_at'=>'nullable|date','image'=>'nullable|image|max:10240']);
        if($request->hasFile('image'))$data['image_path']=$images->storeWebp($request->file('image'),'popups',1400,80);
        $data['show_desktop']=$request->boolean('show_desktop'); $data['show_mobile']=$request->boolean('show_mobile'); $data['is_active']=$request->boolean('is_active'); unset($data['image']);
        PopupAnnouncement::create($data); return back()->with('success','Popup pengumuman berhasil dibuat.');
    }
    public function toggle(Request $request, PopupAnnouncement $popup){ abort_unless($request->user()->isSuperAdmin(),403); $popup->update(['is_active'=>!$popup->is_active]); return back()->with('success','Status popup diperbarui.'); }
}
