<?php
/**
 * API - Obtener perfil de WhatsApp Business
 * Consulta la información del perfil desde la API de WhatsApp Cloud
 */

require_once '../config/config.php';

header('Content-Type: application/json; charset=utf-8');

requireAuthentication();

try {
    $config = getWhatsAppConfigFromDB();
    $token   = $config['token'] ?? '';
    $phoneId = $config['phone_number_id'] ?? '';
    $apiUrl  = rtrim($config['api_url'] ?: 'https://graph.facebook.com/v22.0/', '/');

    if (empty($token) || empty($phoneId)) {
        echo json_encode(['success' => false, 'error' => 'Token o Phone Number ID no configurado']);
        exit;
    }

    $url = "{$apiUrl}/{$phoneId}/whatsapp_business_profile?fields=about,address,description,email,profile_picture_url,websites,vertical";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ["Authorization: Bearer {$token}"],
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,
        CURLOPT_SSLVERSION     => CURL_SSLVERSION_TLSv1_2,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error    = curl_error($ch);
    curl_close($ch);

    if ($error) {
        throw new Exception("Error de conexión: {$error}");
    }

    $data = json_decode($response, true);

    if ($httpCode !== 200) {
        $msg = $data['error']['message'] ?? 'Error desconocido';
        throw new Exception("API error ({$httpCode}): {$msg}");
    }

    // La API devuelve { data: [ {...profile} ] }
    $profile = isset($data['data'][0]) ? $data['data'][0] : $data;

    echo json_encode(['success' => true, 'data' => $profile]);

} catch (Exception $e) {
    error_log('[get_whatsapp_profile] ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
