<?php
/**
 * API - Actualizar perfil de WhatsApp Business
 * Actualiza about, description, address, email, websites
 */

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

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

requireAuthentication();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

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;
    }

    // Construir payload solo con campos presentes y no vacíos
    $payload = ['messaging_product' => 'whatsapp'];

    $allowed = ['about', 'address', 'description', 'email', 'vertical'];
    foreach ($allowed as $field) {
        if (isset($input[$field])) {
            $payload[$field] = trim($input[$field]);
        }
    }

    // websites es un array
    if (!empty($input['websites'])) {
        $websites = array_values(array_filter(array_map('trim', (array)$input['websites'])));
        if (!empty($websites)) {
            $payload['websites'] = $websites;
        }
    }

    $url = "{$apiUrl}/{$phoneId}/whatsapp_business_profile";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => [
            "Authorization: Bearer {$token}",
            "Content-Type: application/json",
        ],
        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}");
    }

    echo json_encode(['success' => true, 'message' => 'Perfil actualizado correctamente']);

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