<?php
/**
 * check-trade-session.php
 * Checks & records whether a wallet has already placed a trade today (IST).
 *
 * GET  ?wallet=XX&action=check   → returns { traded: true/false, session_id, date }
 * POST { wallet, action:"mark" } → marks today as traded, returns { success, session_id }
 * POST { wallet, action:"mark", position, amount, rate } → same, with trade details
 */

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once '../config/db.php';

// ── IST today date string ─────────────────────────────────────
function getISTDate() {
    $dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
    return $dt->format('Y-m-d');
}

// ── Get wallet ────────────────────────────────────────────────
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'POST') {
    $body   = json_decode(file_get_contents('php://input'), true) ?? [];
    $wallet = trim($body['wallet'] ?? '');
    $action = trim($body['action'] ?? 'mark');
    $position = $body['position'] ?? '';
    $amount   = floatval($body['amount']   ?? 0);
    $rate     = floatval($body['rate']     ?? 0);
} else {
    $wallet = trim($_GET['wallet'] ?? '');
    $action = trim($_GET['action'] ?? 'check');
}

if (empty($wallet)) {
    echo json_encode(['status' => 'error', 'message' => 'wallet required']);
    exit;
}

$safeWallet = mysqli_real_escape_string($conn, $wallet);
$todayIST   = getISTDate();

// ── Ensure table exists ───────────────────────────────────────
mysqli_query($conn, "
    CREATE TABLE IF NOT EXISTS trade_sessions (
        id           INT AUTO_INCREMENT PRIMARY KEY,
        wallet       VARCHAR(100) NOT NULL,
        trade_date   DATE NOT NULL,
        position     VARCHAR(10)  DEFAULT NULL,
        amount       DECIMAL(18,4) DEFAULT 0,
        rate         DECIMAL(6,2)  DEFAULT 0,
        session_key  VARCHAR(64)  NOT NULL,
        created_at   DATETIME DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uq_wallet_date (wallet, trade_date)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

// ══════════════════════════════════════════════════════════════
// ACTION: CHECK
// ══════════════════════════════════════════════════════════════
if ($action === 'check') {
    $res = mysqli_query($conn,
        "SELECT session_key, position, amount, rate, created_at
         FROM trade_sessions
         WHERE wallet='$safeWallet' AND trade_date='$todayIST'
         LIMIT 1");
    $row = mysqli_fetch_assoc($res);
    if ($row) {
        echo json_encode([
            'status'     => 'success',
            'traded'     => true,
            'date'       => $todayIST,
            'session_id' => $row['session_key'],
            'position'   => $row['position'],
            'amount'     => $row['amount'],
            'rate'       => $row['rate'],
            'placed_at'  => $row['created_at'],
        ]);
    } else {
        echo json_encode([
            'status'  => 'success',
            'traded'  => false,
            'date'    => $todayIST,
        ]);
    }
    exit;
}

// ══════════════════════════════════════════════════════════════
// ACTION: MARK  (called right before trade is activated)
// ══════════════════════════════════════════════════════════════
if ($action === 'mark') {
    $sessionKey = bin2hex(random_bytes(16)); // unique token
    $safePos    = mysqli_real_escape_string($conn, $position);

    // INSERT IGNORE so concurrent requests don't double-insert
    $ok = mysqli_query($conn, "
        INSERT IGNORE INTO trade_sessions
            (wallet, trade_date, position, amount, rate, session_key)
        VALUES
            ('$safeWallet', '$todayIST', '$safePos', $amount, $rate, '$sessionKey')
    ");

    if ($ok && mysqli_affected_rows($conn) > 0) {
        // New row inserted → trade allowed
        echo json_encode([
            'status'     => 'success',
            'marked'     => true,
            'session_id' => $sessionKey,
            'date'       => $todayIST,
        ]);
    } else {
        // Row already existed (another device/tab beat us)
        $res = mysqli_query($conn,
            "SELECT session_key, created_at FROM trade_sessions
             WHERE wallet='$safeWallet' AND trade_date='$todayIST' LIMIT 1");
        $row = mysqli_fetch_assoc($res);
        echo json_encode([
            'status'     => 'already_traded',
            'marked'     => false,
            'date'       => $todayIST,
            'session_id' => $row['session_key'] ?? '',
            'placed_at'  => $row['created_at']  ?? '',
            'message'    => 'Trade already placed today from another device or session.',
        ]);
    }
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Unknown action']);