<?php
namespace App\Http\Controllers;
use App\Models\Organization;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class OrganizationUnitController extends Controller {
    public function index(Request $request){
        abort_unless($request->user()->isSuperAdmin(),403);
        $units=Organization::whereIn('type',['banom','lembaga'])->orderBy('sort_order')->orderBy('name')->get();
        return view('admin.organizations.index',compact('units'));
    }
    public function store(Request $request){
        abort_unless($request->user()->isSuperAdmin(),403);
        $data=$request->validate(['name'=>'required|max:180','acronym'=>'nullable|max:80','type'=>'required|in:banom,lembaga','slug'=>'nullable|max:100|alpha_dash','theme_color'=>'nullable|max:20']);
        $mwc=Organization::where('type','mwcnu')->firstOrFail();
        $slug=$data['slug'] ?: Str::slug($data['acronym'] ?: $data['name']);
        if(Organization::where('slug',$slug)->exists()) return back()->withErrors(['slug'=>'Slug sudah digunakan.']);
        Organization::create(array_merge($data,['parent_id'=>$mwc->id,'slug'=>$slug,'website'=>url('/'.$slug),'is_active'=>true,'public_page_enabled'=>true,'show_in_main_menu'=>true,'aggregate_news'=>true,'aggregate_events'=>true,'aggregate_programs'=>true,'include_in_statistics'=>true,'include_in_reports'=>true]));
        return back()->with('success','Banom/Lembaga berhasil ditambahkan.');
    }
    public function update(Request $request, Organization $organization){
        abort_unless($request->user()->isSuperAdmin(),403);
        abort_unless(in_array($organization->type,['banom','lembaga']),404);
        $data=$request->validate(['is_active'=>'sometimes|boolean','public_page_enabled'=>'sometimes|boolean','show_in_main_menu'=>'sometimes|boolean','aggregate_news'=>'sometimes|boolean','aggregate_events'=>'sometimes|boolean','aggregate_programs'=>'sometimes|boolean','aggregate_gallery'=>'sometimes|boolean','include_in_statistics'=>'sometimes|boolean','include_in_reports'=>'sometimes|boolean']);
        $organization->update($data); return back()->with('success','Pengaturan unit diperbarui.');
    }
}
