<?php
/**
 * Proxy para API Evolution (WhatsApp) - Versão Simplificada
 */

// Headers CORS e Anti-cache PRIMEIRO
// Detectar ambiente
$isStaging = (strpos($_SERVER['HTTP_HOST'] ?? '', 'dev.') !== false);
$currentDomain = $isStaging ? 'https://dev.duolead.com.br' : 'https://duolead.com.br';
$sessionName = $isStaging ? 'montaloja_staging_session' : 'montaloja_session';

header('Access-Control-Allow-Origin: ' . $currentDomain);
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate');

// Se for preflight, retornar OK
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Iniciar sessão
if (session_status() === PHP_SESSION_NONE) {
    session_name($sessionName);
    session_start();
}

// Verificar autenticação básica
if (empty($_SESSION['user_id']) || empty($_SESSION['store_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Não autorizado', 'debug' => 'session_missing']);
    exit;
}

// Configurações da API Evolution
$apiBase = 'https://evo.duolead.com.br';
$apiKey = 'montaloja2025';

// Pegar parâmetros
$action = $_GET['action'] ?? '';
$instance = $_GET['instance'] ?? '';

if (empty($instance)) {
    http_response_code(400);
    echo json_encode(['error' => 'Instância não informada']);
    exit;
}

// Sanitizar
$instance = preg_replace('/[^a-zA-Z0-9_-]/', '', $instance);

// Definir endpoint
$endpoint = '';
$method = 'GET';
$postData = null;

switch ($action) {
    case 'status':
        $endpoint = "/instance/connectionState/{$instance}";
        break;
    case 'create':
        $endpoint = "/instance/create";
        $method = 'POST';
        $postData = json_encode([
            'instanceName' => $instance,
            'qrcode' => true,
            'integration' => 'WHATSAPP-BAILEYS'
        ]);
        break;
    case 'connect':
        $endpoint = "/instance/connect/{$instance}";
        break;
    case 'disconnect':
        $endpoint = "/instance/logout/{$instance}";
        $method = 'DELETE';
        break;
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Ação inválida']);
        exit;
}

// Fazer requisição
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $apiBase . $endpoint,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => ['apikey: ' . $apiKey, 'Content-Type: application/json'],
    CURLOPT_SSL_VERIFYPEER => false
]);

if ($method === 'POST') {
    curl_setopt($ch, CURLOPT_POST, true);
    if ($postData) curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
} elseif ($method === 'DELETE') {
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}

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

http_response_code($httpCode);
echo $response;
