<?php
/**
 * Sample Webhook Endpoint for Trading Signal Extractor
 *
 * Upload this file to your web server and use its URL in the extension.
 * Example: https://yourdomain.com/sample_webhook.php
 */

// Allow CORS (if needed)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

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

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Get the JSON payload
$json = file_get_contents('php://input');
$signal = json_decode($json, true);

// Validate data
if (!$signal) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    exit;
}

// Log the signal to a file
$logFile = 'signals.log';
$timestamp = date('Y-m-d H:i:s');
$logEntry = sprintf(
    "[%s] Alert: %s | Entry: %s | TP: %s | SL: %s\n",
    $timestamp,
    $signal['alertSignal'] ?? 'null',
    $signal['entryPrice'] ?? 'null',
    $signal['takeProfit'] ?? 'null',
    $signal['stopLoss'] ?? 'null'
);

file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

// Process the signal
$action = 'NO_ACTION';
$message = '';

if (isset($signal['alertSignal'])) {
    switch ($signal['alertSignal']) {
        case 1:
            $action = 'BUY';
            $message = 'Buy signal received';
            // TODO: Add your buy logic here
            // Example: executeBuyOrder($signal['entryPrice'], $signal['stopLoss'], $signal['takeProfit']);
            break;

        case -1:
            $action = 'SELL';
            $message = 'Sell signal received';
            // TODO: Add your sell logic here
            // Example: executeSellOrder($signal['entryPrice'], $signal['stopLoss'], $signal['takeProfit']);
            break;

        case 2:
            $action = 'EXIT_LONG';
            $message = 'Exit long signal received';
            // TODO: Add your exit long logic here
            // Example: closePosition('long');
            break;

        case -2:
            $action = 'EXIT_SHORT';
            $message = 'Exit short signal received';
            // TODO: Add your exit short logic here
            // Example: closePosition('short');
            break;

        case 0:
            $action = 'NO_SIGNAL';
            $message = 'No active signal';
            break;

        default:
            $action = 'UNKNOWN';
            $message = 'Unknown signal value';
    }
}

// Optional: Save to database
// saveToDatabase($signal);

// Optional: Forward to MT5 bot
// forwardToMT5($signal);

// Optional: Send notification
// sendNotification($message);

// Respond with success
$response = [
    'success' => true,
    'action' => $action,
    'message' => $message,
    'received' => $signal,
    'timestamp' => $timestamp
];

echo json_encode($response);

// Log the response
$logEntry = sprintf("[%s] Response: %s\n", $timestamp, json_encode($response));
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

?>
