<?php
declare(strict_types=1);
require dirname(__DIR__).'/app/bootstrap.php';

header('Content-Type: text/plain; charset=utf-8');
header('Cache-Control: no-store');

if($_SERVER['REQUEST_METHOD']==='GET'){
    $mode=(string)($_GET['hub_mode']??$_GET['hub.mode']??'');
    $token=(string)($_GET['hub_verify_token']??$_GET['hub.verify_token']??'');
    $challenge=(string)($_GET['hub_challenge']??$_GET['hub.challenge']??'');
    $expected=(string)(whatsapp_config()['verify_token']??'');
    if($mode==='subscribe'&&$expected!==''&&hash_equals($expected,$token)){echo $challenge;exit;}
    http_response_code(403);echo 'Verification failed';exit;
}

if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);echo 'Method not allowed';exit;}
if(!billing_schema_is_current()){http_response_code(503);echo 'Maintenance';exit;}
$raw=file_get_contents('php://input')?:'';
$signature=(string)($_SERVER['HTTP_X_HUB_SIGNATURE_256']??'');
if(!whatsapp_webhook_signature_valid($raw,$signature)){http_response_code(403);echo 'Invalid signature';exit;}
$payload=json_decode($raw,true);
if(!is_array($payload)){http_response_code(400);echo 'Invalid JSON';exit;}
try{whatsapp_process_webhook($payload);http_response_code(200);echo 'EVENT_RECEIVED';}
catch(Throwable $e){error_log('Soda ZW WhatsApp webhook: '.$e->getMessage());http_response_code(500);echo 'Processing error';}
