# BTC Catch Miner — MySQL Edition 🚀
## Full Setup Guide

---

## 📦 Files Included

| File | Description |
|------|-------------|
| `install.sql` | MySQL database schema — run once |
| `config.php` | All configuration (DB, Bot, FaucetPay) |
| `db.php` | PDO MySQL wrapper class |
| `api.php` | Full API handler with MySQL |
| `events.php` | SSE endpoint for live withdraw feed |
| `index.html` | Game UI with live feed + advanced withdraw |
| `game.js` | Full game logic + SSE client |
| `style.css` | Dark neon crypto theme |

---

## ⚡ Quick Setup

### 1. Create MySQL Database
```sql
CREATE DATABASE btcgame CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

### 2. Import Schema
```bash
mysql -u root -p btcgame < install.sql
```

### 3. Edit `config.php`
```php
define('DB_HOST', 'localhost');
define('DB_NAME', 'btcgame');
define('DB_USER', 'your_db_user');
define('DB_PASS', 'your_db_password');

define('BOT_TOKEN',    'YOUR_TELEGRAM_BOT_TOKEN');
define('BOT_USERNAME', 'YourBotUsername');
define('WEBAPP_URL',   'https://yourdomain.com/btcgame/index.html');

define('FAUCETPAY_API_KEY', 'your_faucetpay_api_key');
```

### 4. Upload all files to your web server (PHP 8.0+)

### 5. Set file permissions
```bash
chmod 755 *.php *.html *.js *.css
```

### 6. Configure your Telegram Bot
- Use [@BotFather](https://t.me/BotFather) to create/edit your bot
- Set the WebApp URL:  
  `/setmenubutton` → URL → `https://yourdomain.com/btcgame/index.html`

---

## 🆕 New Features

### MySQL Database
- All player data, withdrawals, referrals, game sessions stored in MySQL
- Atomic transactions prevent coin duplication
- Rate limiting now uses DB (no more lock files)

### Live Withdraw Feed (SSE)
- Real-time broadcasts to all connected users via Server-Sent Events
- Shows latest 10 withdrawals with scroll for history
- Auto-reconnects on disconnect
- Usernames are privacy-masked (e.g., `joh****`)
- Displays Telegram profile photos

### Advanced Withdraw
- **Custom amount** — withdraw any amount up to your balance
- **MAX button** — auto-fills maximum available SAT
- **Fee summary** — shows amount, fee, you receive, coins used, est. time
- **4-step progress indicator** with live status (✅/❌/⏳)
- **Detailed receipt** — includes FaucetPay TX ID, email, timestamp
- **Status tracking** — pending → processing → success/failed
- **Retry-safe** — coins refunded automatically on failure
- **History** — full withdrawal history with status colors

### Telegram Profile Photos
- Auto-fetched on first login via `getUserProfilePhotos` API
- Displayed in profile card, leaderboard, live feed
- Falls back to initials if unavailable

### Referral System (MySQL)
- Referrals stored in dedicated `referrals` table
- Prevents duplicate referral rewards with `UNIQUE KEY`
- Referrer notified via Telegram bot message
- Full referral history queryable

---

## 🗄️ Database Tables

### `players` — Core player data
### `withdrawals` — Full withdrawal history with status
### `referrals` — Referral tracking (prevents duplicates)
### `game_sessions` — Every game played (analytics)
### `rate_limits` — API rate limiting per IP

---

## ⚙️ PHP Requirements

- PHP 8.0+
- PDO + PDO_MySQL extension
- cURL extension
- OpenSSL extension
- `set_time_limit` allowed (for SSE)

---

## 🔒 Security Notes

- Telegram `initData` validated on every API call
- Score submissions signed with HMAC
- All inputs sanitized
- Rate limiting: 60 requests / 60 seconds per IP
- Coins deducted atomically before FaucetPay call
- Auto-refund on FaucetPay failure

---

## 🛠️ Nginx Config (recommended)

```nginx
location /btcgame/events.php {
    proxy_pass         http://127.0.0.1:9000;
    proxy_buffering    off;
    proxy_cache        off;
    proxy_set_header   X-Accel-Buffering no;
    keepalive_timeout  120s;
    send_timeout       120s;
}
```

## 🛠️ Apache (.htaccess)

```apache
<Files "events.php">
    Header set X-Accel-Buffering "no"
    Header set Cache-Control "no-cache"
</Files>
```

---

## v3 Update — Changelog

### 🎁 Daily Bonus — One-claim-per-day with Countdown
- Bonus reduced to **20 coins** (was 100/200).
- After claiming, the button shows a live **HH:MM:SS countdown** to midnight UTC.
- Server-side: `last_daily` date check prevents any duplicate claims.
- Client `next_daily_ts` field drives the countdown without extra API calls.

### 📋 Daily Tasks — Recruiter replaces First Mine
- `d1 First Mine` (**Play 1 game**) → replaced by `d1 Recruiter` (**Invite 2 referrals today**).
- Progress resets daily. The game tracks new referrals earned *today* using a baseline snapshot stored in `localStorage` at each day-start.
- All daily task rewards reduced for sustainability (see table below).

| Task | Old Reward | New Reward |
|---|---|---|
| Recruiter (d1) | — | 30 |
| Mining Shift (d2) | 100 | 15 |
| Coin Collector (d3) | 50 | 10 |
| Daily Devotion (d4) | 30 | 5 |
| Big Earner (d5) | 80 | 20 |
| Watch & Earn (d6) | 50 | 10 |
| Special / Social tasks | various | ~25–40% of original |

### 💸 Withdraw — Tiered Gate
- **First 5 withdrawals**: fully free, no conditions.
- **6th withdrawal onwards**: player must complete **and claim all 6 daily tasks** before each withdrawal.
- Gate is enforced both client-side (instant UX feedback, redirects to Tasks) and server-side (API returns HTTP 403 if `daily_tasks_claimed` flag is false).
- Withdraw page shows remaining free-withdrawal count, then a clear lock notice with a direct "Go to Tasks" button.

### 💰 Coin Economy — 100K-player Budget
Tuned to keep total payout under **500,000 SAT** across 100,000 players:

| Setting | Old | New |
|---|---|---|
| COIN_VALUE | 5 | 1 |
| DIAMOND_VALUE | 25 | 5 |
| BOMB_PENALTY | 50 | 10 |
| MAX_SCORE_PER_GAME | 5,000 | 500 |
| DAILY_BONUS_COINS | 100 | 20 |
| REFERRAL_BONUS_COINS | 500 | 50 |
| DAILY_GAME_POINTS | 10 | 5 |

### 🛠 Database
- Run `migrate.sql` on existing installations to apply v3 changes.
- `db.php` gains a `DB::val()` helper for scalar queries.
- `publicPlayer()` now returns `next_daily_ts` (Unix timestamp) and `withdrawal_count`.
