<?php
namespace App\Http\Controllers;
use App\Models\{Letter,Organization};
use App\Services\OrganizationAccess;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class LetterController extends Controller {
    public function index(Request $request){
        $letters=OrganizationAccess::apply(Letter::with('organization')->latest('letter_date'),$request->user())->paginate(20);
        $orgs=$request->user()->isSuperAdmin()?Organization::orderBy('name')->get():Organization::whereKey($request->user()->organization_id)->get();
        return view('admin.letters.index',compact('letters','orgs'));
    }
    public function store(Request $request){
        $data=$request->validate(['organization_id'=>'required|exists:organizations,id','direction'=>'required|in:incoming,outgoing','number'=>'nullable|max:150','type'=>'required|max:100','subject'=>'required|max:200','sender'=>'nullable|max:200','recipient'=>'nullable|max:200','letter_date'=>'required|date','body'=>'nullable|string','status'=>'required|in:draft,pending,published,disposition,done,cancelled']);
        if (!$request->user()->isSuperAdmin()) $data['organization_id']=$request->user()->organization_id;
        $data['qr_token']=Str::upper(Str::random(12)); Letter::create($data);
        return back()->with('success','Surat berhasil disimpan.');
    }
}
