<?php
require_once __DIR__ . '/config.php';

function sanitize($data) {
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

function check_user_auth() {
    if (!isset($_SESSION['user_id'])) {
        header("Location: " . SITE_URL . "/login");
        exit;
    }
}

function check_admin_auth() {
    if (!isset($_SESSION['admin_id'])) {
        header("Location: " . ADMIN_URL . "login");
        exit;
    }
}

/**
 * Replay System Engine
 * Calculates the execution delay/replay time window for Binance Streams
 */
function get_market_offset_time($symbol, $pdo) {
    $stmt = $pdo->prepare("SELECT delay_minutes, is_active FROM market_settings WHERE symbol = ? LIMIT 1");
    $stmt->execute([$symbol]);
    $market = $stmt->fetch();

    $now = time();

    if ($market && $market['is_active']) {
        // Admin setting converts to past seconds offset
        $delay_seconds = intval($market['delay_minutes']) * 60;
        return $now - $delay_seconds;
    }
    return $now;
}

function json_response($status, $message, $data = []) {
    header('Content-Type: application/json');
    echo json_encode(['status' => $status, 'message' => $message, 'data' => $data]);
    exit;
}