# ArcRam Bot & Mini App - Private Structure & Technical Map

This file contains the internal codebase structure, data flows, and configurations for the ArcRam project. **This file should be kept private and not committed to public repositories.**

---

## 🗺️ Project Directory & Codebase Map

### 📁 Directory Layout
```
project/
├── .github/workflows/
│   └── deploy.yml            # GitHub Actions deployment workflow (SSH & chmod setup)
├── assets/                   # Public assets (images, styles, etc.)
├── classes/                  # Core PHP Class Controllers (Business Logic)
│   ├── data/                 # JSON data & temporary assets
│   ├── form_states/          # User form step session files
│   ├── pending_messages/     # Temporary message storage for admin approval
│   ├── AIChatHandler.php     # Multi-model AI Integration (GPT, DeepSeek, Qwen)
│   ├── BotHandler.php        # Monolithic Bot Handler (Bot flows, keyboards, commands)
│   ├── BroadcastHandler.php  # Handles admin broadcast messages
│   ├── Database.php          # MySQLi Database Wrapper & Query Handler
│   ├── FileHandler.php       # File uploads, downloads, and validation logic
│   ├── FormManager.php       # Dynamic Multi-step Form Processor Engine
│   ├── Forms.php             # Form Fields Config Definition (e.g. ad_creation)
│   ├── InlineQueryHandler.php# Telegram Inline Queries (Search projects/profiles)
│   ├── IppanelSmsHandler.php # SMS verification gateway integrations
│   ├── Logger.php            # Logging to file & sending debug logs to Telegram channel
│   ├── PendingMessageManager.php # Handles messages awaiting admin approval
│   ├── WebAppHelper.php      # Mini App security verification & request helper
│   └── cache.php             # File/Memory caching logic
├── config/
│   ├── AppConfig.php         # Loads .env variables and holds configuration arrays
│   └── jdf.php               # Jalali (Shamsi) Calendar utility functions
├── cron/
│   └── expire_projects.php   # Cron job to mark expired projects/ads
├── log/                      # Daily system and error log outputs (Requires 777 perms)
├── data/
│   └── state/                # Form flow lock/JSON files (Requires 777 perms)
├── miniapp/                  # Telegram Mini App (Web App) Frontend & API
│   ├── api.php               # Backend API endpoint for the Web App
│   ├── index.html            # Main HTML UI for the Web App
│   ├── styles.css            # Stylesheets for the Web App
│   ├── error_log             # Mini app specific error logs
│   └── js/, fonts/, images/  # Frontend static resources
├── payment/
│   └── ZarinpalPaymentHandler.php # Zarinpal gateway API (Invoice creation & verification)
├── public/                   # Public Web Endpoints
│   ├── bot.php               # Telegram webhook endpoint (Reads php://input)
│   ├── diagnose.php          # System and Telegram Webhook diagnostic script
│   ├── broadcast_panel.php   # Admin web panel for sending broad messages
│   ├── receipt.php           # User payment receipt web page
│   ├── project_cron.php      # Main scheduled task cron execution entry point
│   ├── run_scheduler.php     # System command scheduler
│   └── update_block_statistics.php # Stats updating cron
├── .env                      # Environment Variables (DB credentials, API Keys, Tokens)
├── .htaccess                 # Apache routing and directory security config
└── composer.json             # PHP packages configuration
```

---

## 🗃️ Codebase Analysis & Data Flows

### 1. Webhook Routing
* **Entry Point**: `public/bot.php`
* When a user sends a message or clicks a button, Telegram sends an update JSON payload via POST to `public/bot.php`.
* `bot.php` decodes the input and determines the update type:
  * Regular Messages / Commands (`/start`): routed to `$bot->handleRequest()` in `classes/BotHandler.php`.
  * Callback Queries (Inline buttons): routed to `$bot->handleCallbackQuery()` in `classes/BotHandler.php`.
  * Inline Queries (Typing @botusername ...): routed to `$bot->handleInlineQuery()` in `classes/InlineQueryHandler.php`.
  * Pre-Checkout (Payments): routed to `$bot->handlePreCheckoutQuery()` in `classes/BotHandler.php`.

### 2. Database Integration
* **Class**: `classes/Database.php`
* Uses PHP's `mysqli` extension to connect to the database configured in `.env`.
* Manages core tables: `users` (chat_id, points, balance, is_admin), `channels` (subscription requirements), `packages` (token bundles), `transactions` (Zarinpal history), and project/ad data.

### 3. Multi-Step Forms & States
* **Classes**: `classes/FormManager.php`, `classes/Forms.php`, `classes/StateManager.php`
* Creating ads or listing items involves a multi-step conversational form. The structure of these forms (fields, validation, prompt messages) is defined in `classes/Forms.php`.
* User progress is kept between webhook invocations by saving JSON files in `data/state/` named `{chat_id}.json` using `classes/StateManager.php`. A locking mechanism `{chat_id}.lock` is used to prevent parallel processing race conditions.

### 4. AI Chat Integration
* **Class**: `classes/AIChatHandler.php`
* Allows users to interact with AI models directly inside the bot.
* Supported services configured via `config/AppConfig.php` and `.env`:
  * **OpenAI (GPT-3.5-turbo / GPT-4)**
  * **DeepSeek (deepseek-chat)**
  * **Qwen (qwen-chat)**
* Manages token counts, handles system prompts, logs chat logs, and calculates usage based on user package tokens.

### 5. Payments & Invoices
* **Classes**: `payment/ZarinpalPaymentHandler.php`
* Integrates Zarinpal IPG.
* When purchasing tokens or paying for ad listings, the user gets a payment link.
* Once paid, Zarinpal redirects them back to `public/bot.php` (with query parameters like `tokenPurchase`, `adPayment`, or `walletCharge`). The bot verifies the transaction with Zarinpal, credits the user/ad in the DB, and notifies the user and administrators.

---

## 🛠️ Environment Configuration (.env)

Make sure your `.env` contains the following keys on the production server:

```env
APP_NAME=Arc
APP_ENV=production
APP_DEBUG=false

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

BOT_TOKEN=your_telegram_bot_token
MERCHANT_ID=your_zarinpal_merchant_id
BOT_LINK=https://t.me/your_bot_username?start=
BOT_USERNAME=your_bot_username

GPT_API_KEY=your_openai_key
GPT_MODEL=gpt-3.5-turbo
GPT_TEMPERATURE=0.5

DEEPSEEK_API_KEY=your_deepseek_key
```
