<?php
namespace App\Services;
use App\Models\WhatsAppMessage;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class WhatsAppService {
 private function cfg($key){return config('services.whatsapp.'.$key);}
 public function sendText(string $to,string $body,?int $leadId=null,?int $userId=null): WhatsAppMessage {
  $msg=WhatsAppMessage::create(['lead_id'=>$leadId,'user_id'=>$userId,'to_phone'=>$to,'body'=>$body,'status'=>'queued','type'=>'text']);
  if(!$this->cfg('phone_number_id')||!$this->cfg('access_token')){$msg->update(['status'=>'configuration_error','error_message'=>'WhatsApp Cloud API credentials are not configured.']);return $msg;}
  try {
   $url='https://graph.facebook.com/'.config('services.meta.api_version','v25.0').'/'.$this->cfg('phone_number_id').'/messages';
   $response=Http::withToken($this->cfg('access_token'))->acceptJson()->post($url,['messaging_product'=>'whatsapp','to'=>$to,'type'=>'text','text'=>['preview_url'=>false,'body'=>$body]]);
   if($response->failed()) throw new RuntimeException($response->json('error.message',$response->body()));
   $msg->update(['status'=>'sent','provider_message_id'=>$response->json('messages.0.id'),'payload'=>$response->json()]);
  } catch(\Throwable $e) {$msg->update(['status'=>'failed','error_message'=>$e->getMessage()]);}
  return $msg;
 }
}
