'token'])); $db = new PDO('pgsql:host=10.1.0.3;port=5432;dbname=adx_system','admin',weval_secret('WEVAL_PG_ADMIN_PASS')); $db->exec("SET search_path TO ethica, admin"); switch($action) { case 'status': $cfg = []; try { $cfg = $db->query("SELECT * FROM whatsapp_config LIMIT 1")->fetch(PDO::FETCH_ASSOC); } catch(Exception $e) { try { $db->exec("CREATE TABLE IF NOT EXISTS ethica.whatsapp_config (id SERIAL PRIMARY KEY, phone_number_id TEXT, access_token TEXT, business_id TEXT, status TEXT DEFAULT 'pending', created_at TIMESTAMP DEFAULT NOW())"); } catch(Exception $e2) {} } echo json_encode(['ok'=>1,'configured'=>!empty($cfg),'config'=>$cfg?['phone_number_id'=>$cfg['phone_number_id']??'','status'=>$cfg['status']??'pending']:null]); break; case 'configure': if ($_SERVER['REQUEST_METHOD'] !== 'POST') die(json_encode(['error'=>'POST'])); $data = json_decode(file_get_contents('php://input'), true); $pnid = $data['phone_number_id'] ?? ''; $at = $data['access_token'] ?? ''; $bid = $data['business_id'] ?? ''; if (!$pnid || !$at) die(json_encode(['error'=>'Missing phone_number_id or access_token'])); try { $db->exec("CREATE TABLE IF NOT EXISTS ethica.whatsapp_config (id SERIAL PRIMARY KEY, phone_number_id TEXT, access_token TEXT, business_id TEXT, status TEXT DEFAULT 'active', created_at TIMESTAMP DEFAULT NOW())"); } catch(Exception $e) {} $db->prepare("INSERT INTO ethica.whatsapp_config (phone_number_id, access_token, business_id, status) VALUES (?, ?, ?, 'active')") ->execute([$pnid, $at, $bid]); echo json_encode(['ok'=>1,'message'=>'WhatsApp Meta configured']); break; case 'send': if ($_SERVER['REQUEST_METHOD'] !== 'POST') die(json_encode(['error'=>'POST'])); $data = json_decode(file_get_contents('php://input'), true); $to = $data['to'] ?? ''; $message = $data['message'] ?? ''; $template = $data['template'] ?? ''; $cfg = $db->query("SELECT * FROM ethica.whatsapp_config WHERE status='active' LIMIT 1")->fetch(PDO::FETCH_ASSOC); if (!$cfg) die(json_encode(['error'=>'WhatsApp not configured'])); $payload = $template ? json_encode(['messaging_product'=>'whatsapp','to'=>$to,'type'=>'template','template'=>['name'=>$template,'language'=>['code'=>'fr']]]) : json_encode(['messaging_product'=>'whatsapp','to'=>$to,'type'=>'text','text'=>['body'=>$message]]); $ch = curl_init("https://graph.facebook.com/v18.0/{$cfg['phone_number_id']}/messages"); curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_POST=>true, CURLOPT_POSTFIELDS=>$payload, CURLOPT_HTTPHEADER=>["Authorization: Bearer {$cfg['access_token']}","Content-Type: application/json"], CURLOPT_TIMEOUT=>10]); $resp = json_decode(curl_exec($ch), true); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo json_encode(['ok'=>$code==200,'http_code'=>$code,'response'=>$resp]); break; }