# 🚀 Server Deployment Guide - Charity API

Yeh guide aapko batayega ki kaise aap apni PHP Charity API ko live server par deploy karein aur ChatGPT ke saath connect karein.

## 📋 Table of Contents

1. [Server Requirements](#server-requirements)
2. [Deployment Steps](#deployment-steps)
3. [.htaccess Configuration](#htaccess-configuration)
4. [Testing After Deployment](#testing-after-deployment)
5. [ChatGPT Integration](#chatgpt-integration)
6. [MCP Setup](#mcp-setup)
7. [Troubleshooting](#troubleshooting)

---

## 🔧 Server Requirements

### Minimum Requirements:
- **PHP Version**: 7.4 ya higher (PHP 8.0+ recommended)
- **Extensions**: 
  - `curl` (API calls ke liye)
  - `json` (JSON handling ke liye)
- **Web Server**: Apache ya Nginx
- **SSL Certificate**: HTTPS ke liye (ChatGPT ke liye required)

### Check PHP Version:
```bash
php -v
```

### Check Required Extensions:
```bash
php -m | grep curl
php -m | grep json
```

---

## 📤 Deployment Steps

### Option 1: cPanel / Shared Hosting

1. **Files Upload Karein:**
   ```
   - api.php
   - mcp.php
   - config.php
   - utils.php
   - .htaccess (IMPORTANT - CORS aur security ke liye)
   - test.html (optional, testing ke liye)
   - openapi.yaml (ChatGPT ke liye)
   ```

2. **Public Folder Mein Upload Karein:**
   - `public_html/` ya `www/` folder mein
   - Ya `htdocs/` folder mein

3. **Permissions Set Karein:**
   - Files: `644`
   - Folders: `755`
   - `.htaccess`: `644` (ensure it's readable)

4. **Test Karein:**
   ```
   https://mcp.illumemedia.app/api.php?action=test
   ```

### Option 2: VPS / Cloud Server (Ubuntu/Debian)

#### Step 1: Server Setup
```bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install PHP and extensions
sudo apt install php php-curl php-json apache2 -y

# Or for Nginx:
sudo apt install php-fpm php-curl php-json nginx -y
```

#### Step 2: Files Upload
```bash
# Create project directory
sudo mkdir -p /var/www/charity-api
cd /var/www/charity-api

# Upload files (use FTP, SCP, or Git)
# Files: api.php, mcp.php, config.php, utils.php, .htaccess, test.html, openapi.yaml

# Set permissions
sudo chmod 644 *.php *.html *.yaml .htaccess
sudo chmod 755 .
```

#### Step 3: Apache Configuration

**Apache Virtual Host:**
```apache
<VirtualHost *:80>
    ServerName mcp.illumemedia.app
    DocumentRoot /var/www/charity-api
    
    <Directory /var/www/charity-api>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/charity-api-error.log
    CustomLog ${APACHE_LOG_DIR}/charity-api-access.log combined
</VirtualHost>
```

**Enable and Restart:**
```bash
sudo a2ensite charity-api.conf
sudo systemctl restart apache2
```

#### Step 4: Nginx Configuration (Alternative)

**Nginx Config:**
```nginx
server {
    listen 80;
    server_name mcp.illumemedia.app;
    root /var/www/charity-api;
    index api.php;

    location / {
        try_files $uri $uri/ /api.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index api.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
```

**Enable and Restart:**
```bash
sudo ln -s /etc/nginx/sites-available/charity-api /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### Option 3: Heroku / Cloud Platforms

**Heroku Setup:**
```bash
# Install Heroku CLI
# Create Procfile
echo "web: vendor/bin/heroku-php-apache2" > Procfile

# Deploy
git init
git add .
git commit -m "Initial commit"
heroku create your-app-name
git push heroku main
```

---

## 🔒 SSL Certificate Setup (HTTPS Required)

### Let's Encrypt (Free SSL):

```bash
# Install Certbot
sudo apt install certbot python3-certbot-apache -y

# For Apache
sudo certbot --apache -d mcp.illumemedia.app

# For Nginx
sudo certbot --nginx -d mcp.illumemedia.app

# Auto-renewal
sudo certbot renew --dry-run
```

### After SSL Setup:
- Update `config.php` if needed
- Test: `https://mcp.illumemedia.app/api.php?action=test`

---

## 📄 .htaccess Configuration

### Kya .htaccess Zaroori Hai?

**Haan, BOHOT IMPORTANT hai!** `.htaccess` file:

✅ **CORS Headers** - ChatGPT ke liye zaroori  
✅ **Security Headers** - XSS, clickjacking protection  
✅ **HTTPS Redirect** - Security  
✅ **PHP Settings** - Timeout, memory optimization  
✅ **File Protection** - Sensitive files hide  

### Setup Steps:

1. **File Already Ready:**
   - `.htaccess` file project mein already hai
   - Direct upload kar dein

2. **Upload Karein:**
   - Same folder mein jahan `api.php` hai
   - Root directory: `public_html/` ya `www/`

3. **Permissions:**
   ```bash
   chmod 644 .htaccess
   ```

4. **Apache Module Check:**
   ```bash
   # mod_rewrite enable karein (agar nahi hai)
   sudo a2enmod rewrite
   sudo systemctl restart apache2
   ```

5. **Apache Config Check:**
   ```apache
   # /etc/apache2/sites-available/000-default.conf
   <Directory /var/www/html>
       AllowOverride All
   </Directory>
   ```

### Nginx Users:

- `.htaccess` file Nginx mein kaam nahi karegi
- `nginx.conf` file use karein (already ready hai)
- Nginx config directly server mein setup karein

### Test .htaccess:

```bash
# CORS headers check
curl -I "https://mcp.illumemedia.app/api.php?action=test"

# HTTPS redirect check
curl -I "http://mcp.illumemedia.app/api.php?action=test"
# Should redirect to HTTPS
```

**Detailed Info:** `HTACCESS_INFO.md` file dekhein

---

## ✅ Testing After Deployment

### 1. Basic API Test
```bash
# Test endpoint
curl "https://mcp.illumemedia.app/api.php?action=test"

# Get charities
curl "https://mcp.illumemedia.app/api.php?action=get_charities&page=1&perPage=5"

# Search charities
curl "https://mcp.illumemedia.app/api.php?action=search_charities&name=Red%20Cross"
```

### 2. MCP Endpoint Test
```bash
# Health check
curl "https://mcp.illumemedia.app/mcp.php?health=1"

# MCP initialize
curl -X POST "https://mcp.illumemedia.app/mcp.php" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "initialize",
    "id": 1
  }'
```

### 3. Browser Test
- Open: `https://mcp.illumemedia.app/test.html`
- All buttons test karein
- Results verify karein

### 4. Online Tools
- **Postman**: API test karne ke liye
- **JSONLint**: JSON response validate karne ke liye
- **SSL Labs**: SSL certificate check karne ke liye

---

## 🤖 ChatGPT Integration

### Method 1: Custom GPT (Recommended)

1. **ChatGPT Plus Account Required**
2. **ChatGPT.com par jayein**
3. **"Create" > "GPT" click karein**
4. **Configure tab mein:**
   - **Name**: Charity Search API
   - **Description**: Search and retrieve charity information
   
5. **Actions section mein:**
   - **"Create new action" click karein**
   - **Authentication**: None (public API)
   - **Schema**: `openapi.yaml` file upload karein
     - Ya manually schema paste karein
   
6. **Schema URL:**
   ```
   https://mcp.illumemedia.app/openapi.yaml
   ```
   
   Ya direct API URL:
   ```
   https://mcp.illumemedia.app/api.php
   ```

7. **Save karein aur test karein**

### Method 2: OpenAI API (Programmatic)

```python
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant that can search charities using the API at https://mcp.illumemedia.app/api.php"
        },
        {
            "role": "user",
            "content": "Find charities in California"
        }
    ],
    tools=[{
        "type": "function",
        "function": {
            "name": "search_charities",
            "description": "Search for charities",
            "parameters": {
                "type": "object",
                "properties": {
                    "state": {"type": "string"},
                    "name": {"type": "string"}
                }
            }
        }
    }]
)
```

---

## 🔌 MCP Setup

### Kya hai MCP?

**MCP (Model Context Protocol)** ek protocol hai jo AI models ko external tools/data sources se connect karne ke liye use hota hai.

### MCP Endpoint Details:

**URL**: `https://mcp.illumemedia.app/mcp.php`

**Methods Supported:**
- `initialize` - Server initialization
- `tools/list` - Available tools list
- `tools/call` - Tool execution
- `ping` - Health check

### ChatGPT MCP Connector:

1. **MCP Server URL:**
   ```
   https://mcp.illumemedia.app/mcp.php
   ```

2. **Protocol**: HTTP (JSON-RPC 2.0)

3. **Test MCP:**
   ```bash
   curl -X POST "https://your-domain.com/mcp.php" \
     -H "Content-Type: application/json" \
     -d '{
       "jsonrpc": "2.0",
       "method": "tools/list",
       "id": 1
     }'
   ```

### MCP kaam karega ya nahi?

**✅ Haan, MCP kaam karega agar:**
- Server HTTPS enabled hai
- CORS headers properly set hain
- JSON-RPC 2.0 format follow ho raha hai
- Response time fast hai (< 5 seconds)

**❌ Nahi kaam karega agar:**
- HTTP only hai (HTTPS required)
- CORS errors hain
- Response format wrong hai
- Server timeout ho raha hai

### MCP Testing:

```bash
# 1. Initialize
curl -X POST "https://mcp.illumemedia.app/mcp.php" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "initialize",
    "id": 1
  }'

# 2. List Tools
curl -X POST "https://mcp.illumemedia.app/mcp.php" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/list",
    "id": 2
  }'

# 3. Call Tool
curl -X POST "https://mcp.illumemedia.app/mcp.php" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "search_charities",
      "arguments": {
        "name": "Red Cross",
        "page": 1,
        "perPage": 10
      }
    },
    "id": 3
  }'
```

---

## 🐛 Troubleshooting

### Problem: API not responding
**Solution:**
- Check PHP error logs: `/var/log/apache2/error.log` ya `/var/log/nginx/error.log`
- Check file permissions
- Verify PHP is running: `php -v`

### Problem: CORS errors
**Solution:**
- Verify CORS headers in `api.php` and `mcp.php`
- Check `.htaccess` file (if using Apache)
- Test with: `curl -H "Origin: https://chat.openai.com" https://mcp.illumemedia.app/api.php?action=test`

### Problem: SSL certificate issues
**Solution:**
- Verify SSL: `https://www.ssllabs.com/ssltest/`
- Check certificate expiry
- Ensure HTTPS redirect is working

### Problem: MCP not working
**Solution:**
- Test MCP endpoint directly
- Check JSON-RPC format
- Verify response structure
- Check server logs for errors

### Problem: Slow response times
**Solution:**
- Enable PHP OPcache
- Use caching (if possible)
- Optimize API calls
- Check server resources

### Enable Error Reporting (Development Only):

**In `api.php` or `mcp.php` (top of file):**
```php
error_reporting(E_ALL);
ini_set('display_errors', 1);
```

**Remove before production!**

---

## 📊 Monitoring & Maintenance

### 1. Log Files Check:
```bash
# Apache
tail -f /var/log/apache2/charity-api-access.log
tail -f /var/log/apache2/charity-api-error.log

# Nginx
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
```

### 2. Server Health:
```bash
# Check PHP processes
ps aux | grep php

# Check disk space
df -h

# Check memory
free -h
```

### 3. Regular Updates:
- PHP version update
- Security patches
- SSL certificate renewal

---

## 🔐 Security Best Practices

1. **HTTPS Always**: Never use HTTP in production
2. **Rate Limiting**: Implement if needed
3. **Input Validation**: Already implemented in code
4. **Error Messages**: Don't expose sensitive info
5. **Regular Backups**: Keep backups of files
6. **Firewall**: Configure server firewall
7. **Updates**: Keep PHP and server updated

---

## 📞 Support

Agar koi issue ho:
1. Check error logs
2. Test endpoints manually
3. Verify server configuration
4. Check `test.html` for browser testing

---

## ✅ Deployment Checklist

- [ ] PHP 7.4+ installed
- [ ] curl extension enabled
- [ ] Files uploaded to server
- [ ] Permissions set correctly
- [ ] SSL certificate installed
- [ ] HTTPS working
- [ ] API endpoint tested
- [ ] MCP endpoint tested
- [ ] ChatGPT integration tested
- [ ] Error logging enabled
- [ ] Monitoring setup

---

**🎉 Deployment Complete!**

Ab aap apni API ko ChatGPT aur other AI assistants ke saath use kar sakte hain!

