# 🦚 JANMASHTAMI EARN — Complete Setup Guide

This is the **step-by-step setup guide** for deploying the bot on standard **shared hosting / cPanel** with **PHP 8.1+ and MySQL**. It covers the entire flow end-to-end.

> **Time to set up:** ~20–30 minutes. **Requirements:** a domain with HTTPS, cPanel (or any Apache + PHP + MySQL host), and a Telegram account.

> **⚡ Quick path (ready in ~5 minutes):** upload the project, then open
> **`https://your-domain.com/install.php`** in your browser. It checks requirements,
> creates the MySQL database, imports `database/schema.sql` automatically, writes
> `bot/config.php`, and sets the Telegram webhook for you. After it finishes, do the
> few manual steps it lists (add channels, payout channel, Mini App URL, make the bot
> a channel admin). The full manual walkthrough below remains the reference for
> everything the installer does, so you can also do it all by hand if you prefer.

---

## ⚠️ Before you start

- Your hosting must run **PHP 8.1 or newer** and **MySQL 5.7+ / MariaDB 10.3+**.
- The **Mini App must be served over HTTPS** (Telegram requires it). Install a free SSL certificate first (cPanel → AutoSSL).
- You'll need the **numeric ID** of your Telegram account. Message [@userinfobot](https://t.me/userinfobot) and it will reply with it.

---

## 🧩 Step 1 — Create the Telegram bot

1. Open [@BotFather](https://t.me/BotFather) in Telegram.
2. Send `/newbot`, then follow the prompts:
   - Give the bot a **name**, e.g. `Janmashtami Earn`.
   - Give it a **username**, e.g. `janmashtami_earn_bot` (must end in `bot`).
3. Copy the **bot token** (looks like `1234567890:AAE...`). Keep it secret.
4. **Recommended:** send `/setcommands` and paste:
   ```text
   start - Start the bot
   help - Help & FAQ
   ```
5. **Recommended:** send `/setjoingroups` → disable if you only want private-chat use.

---

## 🗄️ Step 2 — Create the MySQL database (cPanel)

1. In cPanel → **MySQL® Databases**:
   - Create a **database**, e.g. `mydb_janmashtami`.
   - Create a **user**, e.g. `mydb_bot`, with a strong password.
   - **Add User to Database** → grant **ALL PRIVILEGES**.
2. Note the **host** — on most cPanel hosts it is `localhost`.

---

## 📦 Step 3 — Import the database schema

**Option A (phpMyAdmin):**
1. Open **phpMyAdmin**.
2. Select your database (`mydb_janmashtami`).
3. Click the **Import** tab → choose the file `database/schema.sql` → **Go**.

**Option B (terminal, if you have SSH):**
```bash
mysql -u mydb_bot -p mydb_janmashtami < database/schema.sql
```

This creates all tables (users, devices, referrals, transactions, withdrawals, required_channels, settings, security_logs, rate_limits, flow_states, broadcast_jobs) with indexes and default settings.

---

## ⚙️ Step 4 — Configure `bot/config.php`

Open `bot/config.php` and set your real values:

```php
define('BOT_TOKEN', '1234567890:AAE...');          // from BotFather
define('BOT_USERNAME', 'janmashtami_earn_bot');    // no leading @

define('DB_HOST', 'localhost');
define('DB_PORT', 3306);
define('DB_NAME', 'mydb_janmashtami');
define('DB_USER', 'mydb_bot');
define('DB_PASS', 'YOUR_STRONG_PASSWORD');
define('DB_CHARSET', 'utf8mb4');

define('ADMIN_IDS', [
    7271001234,          // YOUR numeric Telegram ID
    // 987654321,        // add more admins here
]);

define('BASE_URL', 'https://your-domain.com/');          // site root
define('VERIFY_WEBAPP_URL', 'https://your-domain.com/miniapp/');

define('WEBHOOK_SECRET', 'a-long-random-string-unique-to-you');
```

> 🔐 **Security tip:** If your host lets you, move `bot/config.php` **outside** the public web root (one level above `public_html`). The included `.htaccess` also blocks direct access as a second layer.

---

## 🚀 Step 5 — Upload the project

1. In cPanel, open **File Manager**.
2. Navigate to `public_html/` (or a subfolder like `public_html/janmashtami/`).
3. Upload the entire `janmashtami-earn/` folder, keeping the structure intact:
   ```
   public_html/
   └── janmashtami-earn/     (or upload its contents directly into public_html)
       ├── bot/
       ├── miniapp/
       ├── admin/
       ├── database/
       ├── logs/
       ├── .htaccess
       └── README.md
   ```

> If you upload the `janmashtami-earn/` folder as-is, the site URL becomes `https://your-domain.com/janmashtami/`. If you upload its **contents** into `public_html/`, the URL becomes `https://your-domain.com/`. Adjust `BASE_URL` / `VERIFY_WEBAPP_URL` accordingly.

---

## 🔒 Step 6 — Enable HTTPS

1. In cPanel, open **SSL/TLS Status**.
2. Click **Run AutoSSL** (or install a Let's Encrypt certificate) for your domain.
3. Visit `https://your-domain.com/miniapp/` — it should load (even if an error shows for `api.php`, that's fine at this stage).
4. (Optional) Uncomment the force-HTTPS block at the top of `.htaccess`.

---

## 🪝 Step 7 — Set the Telegram webhook

Open this URL in your browser (replace the placeholder):

```
https://api.telegram.org/botBOT_TOKEN/setWebhook?url=https://your-domain.com/bot/webhook.php
```

If the project is in a subfolder:
```
https://api.telegram.org/botBOT_TOKEN/setWebhook?url=https://your-domain.com/janmashtami/bot/webhook.php
```

**Check that it worked:**
```
https://api.telegram.org/botBOT_TOKEN/getWebhookInfo
```
You should see `"url": "https://your-domain.com/bot/webhook.php"` and `"ok": true`.

> 💡 If you ever change the webhook, run the `setWebhook` command again — or first `deleteWebhook`, then set it fresh.

---

## 🖥️ Step 8 — Configure the Mini App in BotFather

1. Open [@BotFather](https://t.me/BotFather).
2. Send `/newapp` to create a Web App (or `/myapps` → choose Edit for an existing one).
3. Attach your bot, give the app a **name** and a **short name**.
4. Set the **Web App URL** to:
   ```
   https://your-domain.com/miniapp/
   ```
   (or `https://your-domain.com/janmashtami/miniapp/` if in a subfolder).
5. (You'll open this app from a **Web App button** the bot sends when a user taps **Start Earning** / **VERIFY DEVICE**.)

---

## 📢 Step 9 — Add the bot to required channels

1. Create (or choose) the channel(s) that users must join.
2. Add your **bot as an administrator** of each channel. Grant it:
   - **Post messages**
   - **Read messages** (so it can check membership)
   - (Recommended) **Edit messages** etc.
3. Get each channel's **numeric ID** (`-100...`). Use [@getidsbot](https://t.me/getidsbot) (add the channel, then send a message there, and it reports the ID).
4. In the **admin panel → Channels**, add each channel:
   - **Channel ID** (numeric, e.g. `-1001234567890`)
   - **Channel username** (optional)
   - **Channel title**
   - **Invite link** (`https://t.me/...`)
   - **Active** (Enabled)

---

## 👑 Step 10 — Set your admin Telegram IDs

Make sure your numeric Telegram ID is in `ADMIN_IDS` in `bot/config.php`. These IDs can:
- Press **APPROVE** / **REJECT** on payout-channel messages.
- Log in to the **web admin panel**.

---

## 🏦 Step 11 — Configure the payout channel

1. Create a **private Telegram channel** (e.g. "JE Payouts").
2. Add your **bot as an administrator** with **Post messages** + **Edit messages** (+ Edit others, Delete).
3. Get the channel's **numeric ID** (`-100...`) via [@getidsbot](https://t.me/getidsbot).
4. In the **admin panel → Settings → Payout Channel ID**, enter that ID.
5. **Test:** run a real withdrawal and verify the payout message appears.
6. **Test:** press **APPROVE** and **REJECT** as an admin — confirm the message edits and the user is notified.

---

## ✅ Step 12 — Configure settings & test end-to-end

1. In the **admin panel → Settings**, confirm:
   - Welcome reward = ₹1
   - Referral reward = ₹1
   - Minimum withdrawal = ₹5
   - Payout channel ID filled in
   - Verify WebApp URL filled in
2. Get your admin auto-login link: (after logging in) **admin/index.php?setup=1**.
3. Run the **complete test** below.

---

## 🧪 Complete test checklist

**Bot registration**
- [ ] Open your bot, tap **Start**. You should see the welcome screen.
- [ ] Tap **Start Earning** → join the required channels → **VERIFY JOIN** → open the **Mini App** → **VERIFY DEVICE**.
- [ ] You receive **₹1** and the dashboard appears. Tapping **Refresh** doesn't re-credit.

**Referral**
- [ ] Send your **referral link** to a friend who has a **different device**. They verify → you get **₹1** once.
- [ ] **Same-device referral:** if a referred friend verifies on a device you (or another user) already used, their referral is **rejected** and you earn **₹0**. It never qualifies.

**Withdrawal**
- [ ] **₹5 or more** → Withdraw → enter UPI → enter amount → Confirm. Payout appears in the payout channel (masked UPI).
- [ ] Below ₹5 is blocked; invalid UPI is rejected; amount > balance is blocked.

**Admin payout**
- [ ] As an admin, **APPROVE** → user notified, channel message marked ✅, `total_withdrawn` increases.
- [ ] As an admin, **REJECT** → user's balance refunded, channel message marked ❌.
- [ ] Non-admins tapping the buttons are rejected; double-processing is blocked.

---

## 🧹 Cron (optional but recommended)

Set up a daily cron in cPanel to clean up expired rows and old logs:

```
0 3 * * * /usr/bin/php /home/USER/public_html/bot/cron.php
```

> Replace the PHP binary path (some hosts use `/usr/local/bin/php` or a cPanel "PHP" wrapper) and adjust the project path. Payout approval/rejection is **instant via Telegram** — it does **not** depend on cron.

---

## 🆘 Troubleshooting

| Issue | Likely cause / fix |
|---|---|
| `getWebhookInfo` shows `404` | Wrong webhook URL. Use the full path including the subfolder if any. |
| Bot doesn't reply | Webhook not set, or hosting blocks outbound `api.telegram.org` calls. Allow outbound HTTPS. |
| Mini App shows "Verification failed" | The Mini App must run over **HTTPS** and must be opened **from Telegram** (not a browser URL). |
| Mini App says "Join channels first" | The user hasn't joined every required channel. Ensure the bot is admin so it can verify. |
| Payout request not showing | Set the correct **Payout Channel ID** in Settings and add the bot as admin with post/edit perms. |
| Approve/Reject says "Unauthorized" | Your Telegram ID isn't in `ADMIN_IDS`, or you're not the payout-channel admin. |
| ₹1 not credited | Check `welcome_reward_claimed` — it's paid once. Or the user is blocked / shared a device. |
| Same device referral | By design: same-device referrals are **rejected** (₹0 to referrer). |

---

## 🔐 Security notes

- **Secrets are server-side only** — the token, DB password, and secrets are never shipped to the browser.
- **Server is authoritative** — the frontend can never award money, change a balance, mark a referral valid, or approve a payout.
- **Admin panel** uses secure sessions (HttpOnly + SameSite=Lax + Secure on HTTPS), CSRF tokens, and `session_regenerate_id` on login.
- **SQL injection** is prevented via PDO prepared statements everywhere; **XSS** via output escaping.
- **Rate limiting** is MySQL-backed (works on shared hosting, survives restarts).

---

## 📚 Reference

See `README.md` for architecture, full file structure, and the complete specification mapping.
