<?php
/**
 * Evolution WhatsApp API Proxy
 * Configuração dinâmica - detecta ambiente automaticamente
 */

// Detectar ambiente (staging ou produção)
$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';

// Anti-cache headers
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Expires: 0');

// CORS Headers - dinâmico baseado no ambiente
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; charset=UTF-8');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Configurar sessão ANTES de iniciar
ini_set('session.save_path', '/opt/alt/php83/var/lib/php/session');
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax'
]);

session_name($sessionName);
session_start();

// Verificar auth
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode([
        'error' => 'Não autorizado',
        'debug' => [
            'session_id' => session_id(),
            'save_path' => session_save_path(),
            'has_user' => isset($_SESSION['user_id']),
            'session_data' => array_keys($_SESSION)
        ]
    ]);
    exit;
}

// Config Evolution API
$evolutionApiUrl = 'https://evo.duolead.com.br';
$evolutionApiKey = 'montaloja2025';

// Parâmetros
$action = $_GET['action'] ?? $_POST['action'] ?? '';
$instance = $_GET['instance'] ?? $_POST['instance'] ?? '';

if (empty($action)) {
    http_response_code(400);
    echo json_encode(['error' => 'Action required']);
    exit;
}

// Rotas da API
$apiUrl = '';
$method = 'GET';
$postData = null;

switch ($action) {
    case 'status':
        $apiUrl = "$evolutionApiUrl/instance/connectionState/$instance";
        break;
    case 'qrcode':
        $apiUrl = "$evolutionApiUrl/instance/connect/$instance";
        break;
    case 'create':
        $apiUrl = "$evolutionApiUrl/instance/create";
        $method = 'POST';
        $postData = json_encode([
            'instanceName' => $instance,
            'integration' => 'WHATSAPP-BAILEYS',
            'qrcode' => true
        ]);
        break;
    case 'logout':
        $apiUrl = "$evolutionApiUrl/instance/logout/$instance";
        $method = 'DELETE';
        break;
    case 'delete':
        $apiUrl = "$evolutionApiUrl/instance/delete/$instance";
        $method = 'DELETE';
        break;
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        exit;
}

// cURL para Evolution API
$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'apikey: ' . $evolutionApiKey,
        'Content-Type: application/json'
    ],
    CURLOPT_TIMEOUT => 30,
    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);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    http_response_code(500);
    echo json_encode(['error' => 'API Error: ' . $error]);
    exit;
}

// Retornar resposta
http_response_code($httpCode);
echo $response;