<?php
/**
 * SmartForex Engine - Advanced Time-Shifting Price Feed API
 * Location: public_html/api/prices.php
 */

error_reporting(0);
ini_set('display_errors', 0);

define('DB_HOST', 'localhost');
define('DB_NAME', 'rakshita_relay');
define('DB_USER', 'rakshita_relay');
define('DB_PASS', 'rehman@169');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode([]);
    exit;
}

$symbol = isset($_GET['symbol']) ? preg_replace("/[^A-Z0-9]/", "", strtoupper($_GET['symbol'])) : 'BTCUSDT';
$interval = isset($_GET['interval']) ? preg_replace("/[^a-z0-9]/", "", strtolower($_GET['interval'])) : '1m';
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 150;

$delay_minutes = 0;
$updated_at = time();

try {
    $stmt = $pdo->prepare("SELECT delay_minutes, UNIX_TIMESTAMP(updated_at) as updated_time FROM market_settings WHERE symbol = ? AND is_active = 1 LIMIT 1");
    $stmt->execute([$symbol]);
    $market = $stmt->fetch();
    if ($market) {
        $delay_minutes = intval($market['delay_minutes']);
        $updated_at = intval($market['updated_time']);
    }
} catch (Exception $e) { }

// CORE FIX: Dynamic Shift Time. System past entry calculation check karke 
// jitna time elapsed hua hai use dynamic sync block me continuously inject karta rahega.
$elapsed_since_admin_trigger = time() - $updated_at;
$shifted_current_time = time() - ($delay_minutes * 60) + $elapsed_since_admin_trigger;
$endTimeMs = $shifted_current_time * 1000;

$binanceUrl = "https://data-api.binance.vision/api/v3/klines?symbol={$symbol}&interval={$interval}&limit={$limit}&endTime={$endTimeMs}";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $binanceUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
$response = curl_exec($ch);
curl_close($ch);

header('Content-Type: application/json');
$data = json_decode($response, true);
$formattedData = [];

if (is_array($data) && isset($data[0]) && is_array($data[0])) {
    foreach ($data as $candle) {
        $formattedData[] = [
            'time'  => intval($candle[0] / 1000), 
            'open'  => floatval($candle[1]),
            'high'  => floatval($candle[2]),
            'low'   => floatval($candle[3]),
            'close' => floatval($candle[4])
        ];
    }
    echo json_encode($formattedData);
} else {
    // Advanced Volatile Failover Simulator Engine 
    $baseTime = floor(($shifted_current_time - ($limit * 60)) / 60) * 60;
    $currentPrice = ($symbol === 'BTCUSDT') ? 63200.00 : 3400.00;
    $volatility = ($symbol === 'BTCUSDT') ? 40 : 5;

    for ($i = 0; $i < $limit; $i++) {
        $candleTime = $baseTime + ($i * 60);
        srand($candleTime); 
        $open = $currentPrice;
        $move = (rand(-100, 100) / 100) * $volatility;
        $close = $open + $move;
        $high = max($open, $close) + (rand(0, 50) / 100) * $volatility;
        $low = min($open, $close) - (rand(0, 50) / 100) * $volatility;
        
        $formattedData[] = [
            'time'  => intval($candleTime),
            'open'  => round($open, 2),
            'high'  => round($high, 2),
            'low'   => round($low, 2),
            'close' => round($close, 2)
        ];
        $currentPrice = $close; 
    }
    srand();
    echo json_encode($formattedData);
}
exit;