<?php
require_once __DIR__ . '/inc/database.php';
header('Content-Type: text/plain; charset=utf-8');

// Optional username filter
$username = isset($_GET['username']) ? $_GET['username'] : null;

// Check if bets table exists
$existsRes = $conn->query("SHOW TABLES LIKE 'bets'");
$exists = ($existsRes && $existsRes->num_rows > 0) ? 'yes' : 'no';
echo "bets_table_exists: $exists\n";
if ($exists !== 'yes') { exit; }

// Reason kolonu var mı?
$hasReasonColumn = false;
$colRes = $conn->query("SHOW COLUMNS FROM bets LIKE 'reason'");
$hasReasonColumn = ($colRes && $colRes->num_rows > 0);

// Total count
$countSql = 'SELECT COUNT(*) AS cnt FROM bets';
if ($username) { $stmt = $conn->prepare('SELECT COUNT(*) AS cnt FROM bets WHERE username = ?'); $stmt->bind_param('s', $username); $stmt->execute(); $countRes = $stmt->get_result(); } else { $countRes = $conn->query($countSql); }
if ($countRes && $row = $countRes->fetch_assoc()) { echo 'bets_total_count' . ($username ? ('_for_' . $username) : '') . ': ' . $row['cnt'] . "\n"; }

// Last 5 rows
$sql = "SELECT id, username, event_name, market_name, selected_odd_label, odd_value, stake_amount, status, event_date, bet_date, potential_winnings" . ($hasReasonColumn ? ", reason" : "") . " FROM bets ORDER BY id DESC LIMIT 5";
$res = $conn->query($sql);
if(!$res){
    echo "query_err " . $conn->error . "\n";
    exit;
}
$count = 0;
while($row = $res->fetch_assoc()){
    echo $row['id'] . ' | ' . $row['username'] . ' | ' . $row['event_name'] . ' | ' . $row['market_name'] . ' | ' . $row['selected_odd_label'] . ' | odds=' . $row['odd_value'] . ' | stake=' . $row['stake_amount'] . ' | status=' . $row['status'] . ' | event_date=' . $row['event_date'] . ' | bet_date=' . $row['bet_date'] . ' | pw=' . $row['potential_winnings'] . ($hasReasonColumn ? (' | reason=' . ($row['reason'] ?? '')) : '') . "\n";
    $count++;
}
if ($count === 0) {
    echo "no rows\n";
}
?>