<?php
// CORS handled by nginx - don't add here to avoid duplicates
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    // Let nginx handle OPTIONS
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

$authActions = ['signup', 'check-status', 'verify', 'create-account', 'login', 'list', 'edit', 'help', 'resend-verification'];
$passActions = ['request-reset', 'validate-token', 'confirm-reset', 'change-password', 'forgot'];
$chatActions = ['get-messages', 'post-message', 'delete-message', 'get-settings', 'save-settings', 'list-user', 'get-user-profile'];


$merchProductActions = ['list-products', 'scrape', 'edit-product', 'delete-product'];
$merchCollectionActions = ['list-collections', 'create-collection', 'launch', 'update-collection', 'delete-collection'];

if (in_array($action, $merchProductActions)) {
    $url = 'https://n8n.srv837412.hstgr.cloud/webhook/merch-products-v4';
    if ($action === 'list-products') { $input['action'] = 'list'; }
} elseif (in_array($action, $merchCollectionActions)) {
    $url = 'https://n8n.srv837412.hstgr.cloud/webhook/merch-collection-v4';
} else
if (in_array($action, $authActions)) {
    $url = 'https://n8n.srv837412.hstgr.cloud/webhook/god-auth';
} elseif (in_array($action, $passActions)) {
    $url = 'https://n8n.srv837412.hstgr.cloud/webhook/god-pass';
} elseif (in_array($action, $chatActions)) {
    $url = 'https://n8n.srv837412.hstgr.cloud/webhook/god-chat';
} else {
    echo json_encode(['ok' => false, 'error' => 'Unknown action: ' . $action]);
    exit;
}

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($input));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    echo json_encode(['ok' => false, 'error' => 'Curl error: ' . $error]);
} else {
    echo $response ?: json_encode(['ok' => false, 'error' => 'No response from webhook']);
}
