<?php
namespace App\Http\Controllers;
use App\Models\{Organization,Program};
use App\Services\OrganizationAccess;
use Illuminate\Http\Request;
class ProgramController extends Controller {
    public function index(Request $request){
        $programs=OrganizationAccess::apply(Program::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.programs.index',compact('programs','orgs'));
    }
    public function store(Request $request){
        $data=$request->validate(['organization_id'=>'required|exists:organizations,id','name'=>'required|max:200','category'=>'nullable|max:100','target'=>'nullable|max:255','due_date'=>'nullable|date','budget'=>'nullable|numeric|min:0','progress'=>'required|integer|min:0|max:100','status'=>'required|in:not_started,running,done,late']);
        if (!$request->user()->isSuperAdmin()) $data['organization_id']=$request->user()->organization_id;
        Program::create($data); return back()->with('success','Program kerja berhasil ditambahkan.');
    }
}
