<?php
// =========================
// MRDCA Bot API (Model B - high-water mark se zámkem na safe)
// =========================
//
// Endpointy:
//   type=getStartDate
//     params: account_number
//     response: JSON {"start_date":"YYYY-MM-DD HH:MM:SS"} (UTC) | {"start_date":null}
//
//   type=report_profit
//     params: account_number, current_profit (může být záporné)
//     response: plaintext "ok" | "error: <reason>"
//     Atomicita: jeden UPDATE statement, GREATEST se vyhodnotí na úrovni řádku
//                pod row-level lockem InnoDB.
//
//   type=getPoolSettings
//     params: account_number
//     response: JSON s pool_total + weight_distribution + Model B diagnostikou
//
// Vzorce Model B:
//   max_profit = MAX(stored_max_profit, current_profit)
//   safe       = max_profit * safe_pct
//   pool       = MAX(0, current_profit - safe)
//   pool_total = pool + pool_manual

require_once __DIR__ . '/db.php';

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    http_response_code(500);
    die("error: db connection failed");
}

$type          = $_REQUEST['type'] ?? '';
$accountNumber = $_REQUEST['account_number'] ?? '';

// =========================================================================
// getStartDate
// =========================================================================
if ($type === 'getStartDate') {
    if ($accountNumber === '') {
        http_response_code(400);
        die("error: missing account_number");
    }

    try {
        $stmt = $pdo->prepare("SELECT start_date FROM bot_mrdca WHERE account_number = ?");
        $stmt->execute([$accountNumber]);
        $startDate = $stmt->fetchColumn();
    } catch (PDOException $e) {
        http_response_code(500);
        error_log('mrdca_api getStartDate: ' . $e->getMessage());
        die("error: db error");
    }

    header('Content-Type: application/json');
    // false (account neexistuje) i NULL (sloupec NULL) → null v JSON
    echo json_encode(['start_date' => ($startDate === false ? null : $startDate)]);
    exit;
}

// =========================================================================
// report_profit
// =========================================================================
if ($type === 'report_profit') {
    if ($accountNumber === '') {
        http_response_code(400);
        die("error: missing account_number");
    }

    $rawProfit = $_REQUEST['current_profit'] ?? '';
    if ($rawProfit === '' || !is_numeric($rawProfit)) {
        http_response_code(400);
        die("error: invalid number");
    }
    $cp = floatval($rawProfit);

    try {
        // Existence check (proti race s mazáním účtu - levné, jednou SELECT)
        $exists = $pdo->prepare("SELECT 1 FROM bot_mrdca WHERE account_number = ?");
        $exists->execute([$accountNumber]);
        if (!$exists->fetchColumn()) {
            // 200 + plaintext: bot to ignoruje, dál pingá. Admin musí účet
            // založit v dashboardu, jinak Model B counters nikdy nestartují.
            die("error: unknown account");
        }

        // Atomicky v jednom UPDATE - GREATEST nad původní hodnotou max_profit
        // (každý GREATEST vidí stejný řádek pod row-level lockem InnoDB).
        $stmt = $pdo->prepare("
            UPDATE bot_mrdca SET
              current_profit = :cp1,
              max_profit     = GREATEST(max_profit, :cp2),
              safe           = GREATEST(max_profit, :cp3) * safe_pct,
              pool           = GREATEST(0, :cp4 - GREATEST(max_profit, :cp5) * safe_pct),
              last_report_at = UTC_TIMESTAMP()
            WHERE account_number = :acc
        ");
        $stmt->execute([
            'cp1' => $cp, 'cp2' => $cp, 'cp3' => $cp, 'cp4' => $cp, 'cp5' => $cp,
            'acc' => $accountNumber,
        ]);
    } catch (PDOException $e) {
        http_response_code(500);
        error_log('mrdca_api report_profit: ' . $e->getMessage());
        die("error: db error");
    }

    echo "ok";
    exit;
}

// =========================================================================
// getPoolSettings
// =========================================================================
if ($type === 'getPoolSettings') {
    if ($accountNumber === '') {
        http_response_code(400);
        die("error: missing account_number");
    }

    try {
        $stmt = $pdo->prepare("
            SELECT account_number, slots, safe_pct, pool, pool_manual, weight_distribution,
                   safe, current_profit, max_profit, last_report_at
              FROM bot_mrdca
             WHERE account_number = ?
        ");
        $stmt->execute([$accountNumber]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        http_response_code(500);
        error_log('mrdca_api getPoolSettings: ' . $e->getMessage());
        die("error: db error");
    }

    header('Content-Type: application/json');

    if ($row) {
        // Bot kontroluje `slots > 0` jako sanity flag (= účet je zkonfigurovaný).
        // `safePrc` posíláme dál pro kompatibilitu s ApiClient.cs Print logem -
        // server `safe` je nově hotová absolutní hodnota, ale bot starou verzi
        // proměnné v třídě má a deserializuje ji.
        $pool       = floatval($row['pool']);
        $poolManual = floatval($row['pool_manual']);
        $safePctVal = floatval($row['safe_pct']);
        echo json_encode([
            'account_number'      => $row['account_number'],
            'slots'               => intval($row['slots']),
            'safePrc'             => intval(round($safePctVal * 100)),
            'pool'                => $pool,
            'pool_manual'         => $poolManual,
            'pool_total'          => $pool + $poolManual,
            'weight_distribution' => $row['weight_distribution'],
            'safe'                => floatval($row['safe']),
            'safe_pct'            => $safePctVal,
            'current_profit'      => floatval($row['current_profit']),
            'max_profit'          => floatval($row['max_profit']),
            'last_report_at'      => $row['last_report_at'],
        ]);
    } else {
        // Account neznámý - bot dostane defaults se slots=0, takže zůstane v "not configured" módu.
        echo json_encode([
            'account_number'      => '0',
            'slots'               => 0,
            'safePrc'             => 0,
            'pool'                => 0.0,
            'pool_manual'         => 0.0,
            'pool_total'          => 0.0,
            'weight_distribution' => '25,25,25,25',
            'safe'                => 0.0,
            'safe_pct'            => 0.0,
            'current_profit'      => 0.0,
            'max_profit'          => 0.0,
            'last_report_at'      => null,
        ]);
    }
    exit;
}

http_response_code(400);
die("error: unknown type. Supported: getStartDate, report_profit, getPoolSettings");
