<?php
// app/helpers/crypto_tools.php
require_once __DIR__ . '/functions.php';

function crypto_rate(mysqli $conn, int $assetId): array {
  $st = $conn->prepare("SELECT rate_usd, rate_ghs FROM crypto_rates WHERE asset_id=? LIMIT 1");
  $st->bind_param("i", $assetId);
  $st->execute();
  $r = $st->get_result()->fetch_assoc();
  return [
    'usd' => (float)($r['rate_usd'] ?? 0),
    'ghs' => (float)($r['rate_ghs'] ?? 0),
  ];
}

function ensure_wallet(mysqli $conn, int $userId, int $assetId): void {
  $st = $conn->prepare("
    INSERT IGNORE INTO crypto_wallets (user_id, asset_id, balance, locked_balance)
    VALUES (?, ?, 0, 0)
  ");
  $st->bind_param("ii", $userId, $assetId);
  $st->execute();
}

function cold_reserve_get(mysqli $conn, int $assetId): float {
  $st = $conn->prepare("SELECT balance FROM crypto_cold_reserve WHERE asset_id=? LIMIT 1");
  $st->bind_param("i", $assetId);
  $st->execute();
  $r = $st->get_result()->fetch_assoc();
  return (float)($r['balance'] ?? 0);
}

function cold_reserve_ensure(mysqli $conn, int $assetId): void {
  $st = $conn->prepare("INSERT IGNORE INTO crypto_cold_reserve (asset_id, balance) VALUES (?, 0)");
  $st->bind_param("i", $assetId);
  $st->execute();
}

function faucet_settings(mysqli $conn): array {
  $r = $conn->query("SELECT * FROM crypto_faucet_settings WHERE id=1")->fetch_assoc();
  return [
    'enabled' => (int)($r['enabled'] ?? 0),
    'daily_limit' => (float)($r['daily_limit'] ?? 0),
    'per_claim' => (float)($r['per_claim'] ?? 0),
    'cooldown_minutes' => (int)($r['cooldown_minutes'] ?? 1440),
  ];
}

function faucet_user_today_total(mysqli $conn, int $userId, int $assetId): float {
  $st = $conn->prepare("
    SELECT COALESCE(SUM(amount),0) AS s
    FROM crypto_txn
    WHERE user_id=? AND asset_id=? AND type='faucet' AND status='approved'
      AND DATE(created_at)=CURDATE()
  ");
  $st->bind_param("ii", $userId, $assetId);
  $st->execute();
  $r = $st->get_result()->fetch_assoc();
  return (float)($r['s'] ?? 0);
}

function faucet_user_last_claim(mysqli $conn, int $userId, int $assetId): ?string {
  $st = $conn->prepare("
    SELECT created_at
    FROM crypto_txn
    WHERE user_id=? AND asset_id=? AND type='faucet' AND status='approved'
    ORDER BY id DESC LIMIT 1
  ");
  $st->bind_param("ii", $userId, $assetId);
  $st->execute();
  $r = $st->get_result()->fetch_assoc();
  return $r['created_at'] ?? null;
}
