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

$conn = require __DIR__ . '/../../app/config/database.php';
require_login();
csrf_verify();

$u = current_user();
$assetId = (int)($_POST['asset_id'] ?? 0);
if ($assetId < 1) { flash('err','Invalid asset'); redirect('crypto_wallet.php'); }

$s = faucet_settings($conn);
if (!$s['enabled']) { flash('err','Faucet is disabled'); redirect('crypto_wallet.php'); }

$perClaim = (float)$s['per_claim'];
$dailyLimit = (float)$s['daily_limit'];
$cooldown = (int)$s['cooldown_minutes'];

try {
  $conn->begin_transaction();

  // cooldown check
  $last = faucet_user_last_claim($conn, (int)$u['id'], $assetId);
  if ($last) {
    $st = $conn->prepare("SELECT TIMESTAMPDIFF(MINUTE, ?, NOW()) AS mins");
    $st->bind_param("s", $last);
    $st->execute();
    $mins = (int)($st->get_result()->fetch_assoc()['mins'] ?? 999999);
    if ($mins < $cooldown) {
      $conn->rollback();
      throw new Exception("Cooldown active. Try again later.");
    }
  }

  // daily limit check
  $today = faucet_user_today_total($conn, (int)$u['id'], $assetId);
  if (($today + $perClaim) > $dailyLimit) {
    $conn->rollback();
    throw new Exception("Daily faucet limit reached.");
  }

  ensure_wallet($conn, (int)$u['id'], $assetId);

  // lock wallet row
  $st = $conn->prepare("SELECT balance FROM crypto_wallets WHERE user_id=? AND asset_id=? FOR UPDATE");
  $st->bind_param("ii", $u['id'], $assetId);
  $st->execute();
  $w = $st->get_result()->fetch_assoc();
  $bal = (float)($w['balance'] ?? 0);

  $newBal = $bal + $perClaim;
  $up = $conn->prepare("UPDATE crypto_wallets SET balance=? WHERE user_id=? AND asset_id=?");
  $up->bind_param("dii", $newBal, $u['id'], $assetId);
  $up->execute();

  // record txn
  $ref = now_ref('FAUC');
  $st2 = $conn->prepare("
    INSERT INTO crypto_txn (ref,user_id,asset_id,type,amount,fee,total_debit,status,destination,created_at)
    VALUES (?,?,?,'faucet',?,0,0,'approved','FAUCET',NOW())
  ");
  $st2->bind_param("siid", $ref, $u['id'], $assetId, $perClaim);
  $st2->execute();

  $conn->commit();

  flash('msg',"Faucet credited: {$perClaim}");
  redirect('crypto_wallet.php');

} catch(Throwable $e) {
  $conn->rollback();
  flash('err',$e->getMessage());
  redirect('crypto_wallet.php');
}
