<?php
namespace App\Http\Controllers;
use App\Models\MetaConnection;
use App\Models\MetaPage;
use App\Services\MetaGraphService;
use Illuminate\Http\Request;
use Throwable;
class MetaController extends Controller {
 public function index(){return view('meta.index',['connection'=>MetaConnection::with('pages')->latest()->first()]);}
 public function redirect(MetaGraphService $m){$state=bin2hex(random_bytes(24));session(['meta_state'=>$state]);$scope='pages_show_list,pages_read_engagement,pages_manage_metadata,leads_retrieval,ads_read,ads_management,business_management';$q=http_build_query(['client_id'=>config('services.meta.app_id'),'redirect_uri'=>route('meta.callback'),'state'=>$state,'scope'=>$scope,'response_type'=>'code']);return redirect('https://www.facebook.com/'.$m->v().'/dialog/oauth?'.$q);}
 public function callback(Request $r,MetaGraphService $m){if(!hash_equals((string)session('meta_state'),(string)$r->state))return redirect()->route('meta.index')->with('error','Invalid OAuth state.');try{$short=$m->code($r->code,route('meta.callback'));$long=$m->long($short['access_token']);$token=$long['access_token']??$short['access_token'];$me=$m->me($token);$c=MetaConnection::updateOrCreate(['id'=>1],['meta_user_id'=>$me['id']??null,'meta_user_name'=>$me['name']??null,'access_token'=>$token,'token_expires_at'=>isset($long['expires_in'])?now()->addSeconds($long['expires_in']):null,'status'=>'connected','last_synced_at'=>now(),'last_error'=>null]);foreach($m->pages($token)['data']??[] as $p)MetaPage::updateOrCreate(['page_id'=>$p['id']],['meta_connection_id'=>$c->id,'name'=>$p['name']??$p['id'],'category'=>$p['category']??null,'access_token'=>$p['access_token']??null,'status'=>'available','last_synced_at'=>now()]);return redirect()->route('meta.index')->with('success','Meta connected and Pages discovered.');}catch(Throwable $e){return redirect()->route('meta.index')->with('error',$e->getMessage());}}
 public function subscribe(MetaPage $page,MetaGraphService $m){try{$m->subscribe($page->page_id,$page->access_token);$page->update(['subscribed'=>true,'status'=>'connected','last_synced_at'=>now(),'last_error'=>null]);return back()->with('success','Lead webhook enabled.');}catch(Throwable $e){$page->update(['status'=>'error','last_error'=>$e->getMessage()]);return back()->with('error',$e->getMessage());}}
 public function forms(MetaPage $page,MetaGraphService $m){return response()->json($m->forms($page->page_id,$page->access_token));}
}
