<?php
namespace App\Http\Controllers;
use App\Models\{Member,Organization,WhatsAppLog};
use App\Services\OrganizationAccess;
use Illuminate\Http\Request;
class MemberController extends Controller {
    public function index(Request $request){
        $members=OrganizationAccess::apply(Member::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.members.index',compact('members','orgs'));
    }
    public function store(Request $request){
        $data=$request->validate(['organization_id'=>'required|exists:organizations,id','full_name'=>'required|max:150','nickname'=>'nullable|max:80','position'=>'required|max:120','whatsapp'=>'nullable|max:30','email'=>'nullable|email','sk_number'=>'nullable|max:120']);
        if (!$request->user()->isSuperAdmin()) $data['organization_id']=$request->user()->organization_id;
        $data['is_active']=true; Member::create($data);
        return back()->with('success','Data pengurus berhasil ditambahkan.');
    }
    public function whatsapp(Request $request, Member $member){
        abort_unless($request->user()->isSuperAdmin() || $request->user()->organization_id===$member->organization_id,403);
        $greeting="Assalamu'alaikum".($member->nickname ? ' '.$member->nickname : '');
        WhatsAppLog::create(['organization_id'=>$member->organization_id,'user_id'=>$request->user()->id,'member_id'=>$member->id,'message'=>$greeting,'clicked_at'=>now()]);
        $phone=preg_replace('/\D+/','',$member->whatsapp ?? ''); if (str_starts_with($phone,'0')) $phone='62'.substr($phone,1);
        return redirect()->away('https://wa.me/'.$phone.'?text='.rawurlencode($greeting));
    }
}
