<?php
/**
 * GET  → Lee el perfil de negocio del número WA turnero desde la Graph API
 * POST accion=guardar → Actualiza campos del perfil (about, description, address, email, websites, vertical)
 * POST accion=foto    → Sube imagen y la aplica como foto de perfil
 */
require_once __DIR__ . '/_helpers.php';
requireTurnero();
require_once __DIR__ . '/../../../services/WhatsAppService.php';

$token   = getConfigFromDB('whatsapp_token', '');
$phoneId = getConfigFromDB('whatsapp_phone_number_id_turnero', '')
        ?: getConfigFromDB('whatsapp_phone_number_id', '');
$apiBase = 'https://graph.facebook.com/v22.0/';

if (!$token || !$phoneId) jsonError('Token o Phone ID del turnero no configurados.', 422);

// ── GET: cargar perfil actual ────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $fields = 'about,address,description,email,profile_picture_url,websites,vertical,messaging_product';
    $url    = $apiBase . $phoneId . '/whatsapp_business_profile?fields=' . $fields
            . '&access_token=' . urlencode($token);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
    ]);
    $resp = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $data = json_decode($resp, true);
    if ($http !== 200 || isset($data['error'])) {
        jsonError($data['error']['message'] ?? 'Error al leer perfil de WhatsApp', $http);
    }

    $perfil = $data['data'][0] ?? $data;
    jsonOk(['perfil' => $perfil]);
}

// ── POST ────────────────────────────────────────────────────
requireMethod('POST');

// Detectar si viene como multipart (foto) o JSON
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
$esMultipart = str_contains($contentType, 'multipart/form-data');

if ($esMultipart) {
    $accion = $_POST['accion'] ?? '';
} else {
    $datos  = inputJson();
    $accion = $datos['accion'] ?? '';
}

// ── POST accion=foto ─────────────────────────────────────────
if ($accion === 'foto') {
    if (empty($_FILES['foto']) || $_FILES['foto']['error'] !== UPLOAD_ERR_OK) {
        jsonError('No se recibió imagen válida.');
    }
    $file     = $_FILES['foto'];
    $mime     = mime_content_type($file['tmp_name']);
    $allowed  = ['image/jpeg', 'image/png'];
    if (!in_array($mime, $allowed, true)) jsonError('Solo se aceptan JPG o PNG.');
    if ($file['size'] > 5 * 1024 * 1024) jsonError('Imagen máxima: 5 MB.');

    // 1. Subir media a WhatsApp
    $uploadUrl = $apiBase . $phoneId . '/media';
    $ch = curl_init($uploadUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $token],
        CURLOPT_POSTFIELDS     => [
            'messaging_product' => 'whatsapp',
            'type'              => $mime,
            'file'              => new CURLFile($file['tmp_name'], $mime, $file['name']),
        ],
        CURLOPT_TIMEOUT        => 30,
    ]);
    $resp = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $uploadData = json_decode($resp, true);
    if ($http !== 200 || empty($uploadData['id'])) {
        jsonError('Error al subir imagen: ' . ($uploadData['error']['message'] ?? $resp));
    }
    $mediaHandle = $uploadData['id'];

    // 2. Aplicar como foto de perfil
    $profileUrl = $apiBase . $phoneId . '/whatsapp_business_profile';
    $payload    = json_encode([
        'messaging_product'      => 'whatsapp',
        'profile_picture_handle' => $mediaHandle,
    ]);
    $ch = curl_init($profileUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json',
        ],
        CURLOPT_TIMEOUT        => 15,
    ]);
    $resp2 = curl_exec($ch);
    $http2 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $r2 = json_decode($resp2, true);
    if (isset($r2['error'])) jsonError('Error al aplicar foto: ' . $r2['error']['message']);
    jsonOk([], 'Foto de perfil actualizada');
}

// ── POST accion=guardar ──────────────────────────────────────
if ($accion === 'guardar') {
    $campos = ['about', 'description', 'address', 'email', 'vertical'];
    $body   = ['messaging_product' => 'whatsapp'];

    foreach ($campos as $c) {
        $val = trim($datos[$c] ?? '');
        if ($val !== '') $body[$c] = $val;
    }
    // Websites: array de hasta 2
    $web = array_filter(array_map('trim', (array)($datos['websites'] ?? [])));
    if ($web) $body['websites'] = array_values($web);

    $url     = $apiBase . $phoneId . '/whatsapp_business_profile';
    $payload = json_encode($body);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST  => 'POST',
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json',
        ],
        CURLOPT_TIMEOUT        => 15,
    ]);
    $resp = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $r = json_decode($resp, true);
    if (isset($r['error'])) jsonError('Error de WhatsApp: ' . $r['error']['message']);
    jsonOk([], 'Perfil de WhatsApp actualizado');
}

jsonError('Acción no reconocida.');
