<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class MetaGraphService {
 public function v(){return config('services.meta.api_version','v25.0');}
 private function get($path,$token,$q=[]){$r=Http::timeout(20)->acceptJson()->get("https://graph.facebook.com/{$this->v()}/{$path}",$q+['access_token'=>$token]);if($r->failed())throw new RuntimeException($r->json('error.message',$r->body()));return $r->json();}
 private function post($path,$token,$q=[]){$r=Http::timeout(20)->acceptJson()->post("https://graph.facebook.com/{$this->v()}/{$path}",$q+['access_token'=>$token]);if($r->failed())throw new RuntimeException($r->json('error.message',$r->body()));return $r->json();}
 public function code($code,$redirect){return $this->get('oauth/access_token',config('services.meta.app_secret'),['client_id'=>config('services.meta.app_id'),'redirect_uri'=>$redirect,'client_secret'=>config('services.meta.app_secret'),'code'=>$code]);}
 public function long($token){return $this->get('oauth/access_token',$token,['grant_type'=>'fb_exchange_token','client_id'=>config('services.meta.app_id'),'client_secret'=>config('services.meta.app_secret'),'fb_exchange_token'=>$token]);}
 public function me($token){return $this->get('me',$token,['fields'=>'id,name']);}
 public function pages($token){return $this->get('me/accounts',$token,['fields'=>'id,name,access_token,tasks,category','limit'=>100]);}
 public function subscribe($page,$token){return $this->post($page.'/subscribed_apps',$token,['subscribed_fields'=>'leadgen']);}
 public function lead($id,$token){return $this->get($id,$token,['fields'=>'id,created_time,field_data,form_id,page_id,ad_id,adset_id,campaign_id']);}
 public function forms($page,$token){return $this->get($page.'/leadgen_forms',$token,['fields'=>'id,name,status,created_time','limit'=>100]);}
}
