<?php
namespace App\Http\Controllers;
use App\Models\{Activity,Organization};
use App\Services\{ImageOptimizerService,OrganizationAccess};
use Illuminate\Http\Request;
class ActivityController extends Controller {
    public function index(Request $request){
        $activities=OrganizationAccess::apply(Activity::with('organization')->latest('start_at'),$request->user())->paginate(20);
        $orgs=$request->user()->isSuperAdmin()?Organization::where('is_active',true)->orderBy('name')->get():Organization::whereKey($request->user()->organization_id)->get();
        return view('admin.activities.index',compact('activities','orgs'));
    }
    public function store(Request $request, ImageOptimizerService $images){
        $data=$request->validate(['organization_id'=>'required|exists:organizations,id','title'=>'required|max:200','type'=>'nullable|max:80','description'=>'nullable','start_at'=>'nullable|date','end_at'=>'nullable|date','location'=>'nullable|max:200','latitude'=>'nullable|numeric','longitude'=>'nullable|numeric','budget'=>'nullable|numeric|min:0','status'=>'required|in:planned,running,done,cancelled','featured_image'=>'nullable|image|max:10240']);
        if(!$request->user()->isSuperAdmin())$data['organization_id']=$request->user()->organization_id;
        if($request->hasFile('featured_image'))$data['featured_image']=$images->storeWebp($request->file('featured_image'),'activities');
        $data['public_visible']=$request->boolean('public_visible',true); $data['aggregate_to_main']=$request->boolean('aggregate_to_main',true);
        Activity::create($data); return back()->with('success','Kegiatan berhasil ditambahkan.');
    }
}
