# دليل النشر — Deployment Guide
## DigitalOcean Production Setup

---

## 1. المتطلبات

### Droplet الموصى به
```
Plan:       Premium Intel — 2 vCPU, 8GB RAM, 160GB NVMe SSD
Region:     Frankfurt (أقرب لأفريقيا)
OS:         Ubuntu 22.04 LTS
Cost:       ~$48/شهر
```

### الخدمات الإضافية
```
Managed MySQL 8:      $15/شهر  (منفصل عن الـ Droplet)
Spaces Storage:        $5/شهر  (للرفع والصور)
Weekly Backups:       $9.60/شهر (إجباري)
──────────────────────────────
Total:               ~$77.60/شهر
```

---

## 2. إعداد السيرفر

### تثبيت PHP 8.1
```bash
apt update && apt upgrade -y
add-apt-repository ppa:ondrej/php -y
apt install -y php8.1-fpm php8.1-mysql php8.1-mbstring \
  php8.1-curl php8.1-json php8.1-zip php8.1-gd php8.1-xml \
  php8.1-intl php8.1-redis
```

### تثبيت Nginx
```bash
apt install -y nginx certbot python3-certbot-nginx
```

### إعداد PHP-FPM
```ini
; /etc/php/8.1/fpm/pool.d/sudanna.conf
[sudanna]
user = www-data
group = www-data
listen = /run/php/php8.1-fpm-sudanna.sock
pm = dynamic
pm.max_children = 20
pm.start_servers = 5
pm.min_spare_servers = 3
pm.max_spare_servers = 10
pm.max_requests = 1000
php_admin_value[memory_limit] = 256M
php_admin_value[max_execution_time] = 30
php_admin_value[upload_max_filesize] = 10M
```

---

## 3. إعداد Nginx

```nginx
# /etc/nginx/sites-available/sudanna
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;
    root /var/www/sudanna;
    index index.html index.php;
    charset utf-8;

    # SSL
    ssl_certificate     /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "strict-origin-when-cross-origin";

    # Main location
    location / {
        try_files $uri $uri/ /index.html;
    }

    # PHP
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.1-fpm-sudanna.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_read_timeout 30;
        include fastcgi_params;
    }

    # Static files
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # Block sensitive files
    location ~* \.(sql|log|env|git)$ { deny all; }
    location ~ /engine/ { deny all; }
    location ~ /config\.php { deny all; }

    # API rate limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m;
    location /api/ {
        limit_req zone=api burst=10 nodelay;
        try_files $uri $uri/ =404;
    }
}
```

```bash
ln -s /etc/nginx/sites-available/sudanna /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx
```

---

## 4. نشر الكود

```bash
# رفع الملفات
rsync -avz --exclude '.git' /local/sudanna/ root@server:/var/www/sudanna/

# الصلاحيات
chown -R www-data:www-data /var/www/sudanna
find /var/www/sudanna -type f -name "*.php" -exec chmod 644 {} \;
find /var/www/sudanna -type d -exec chmod 755 {} \;
chmod 600 /var/www/sudanna/config.php

# إعداد uploads directory
mkdir -p /var/www/sudanna/uploads/{proofs,profiles,documents}
chown -R www-data:www-data /var/www/sudanna/uploads
```

---

## 5. إعداد MySQL

```bash
# إنشاء قاعدة البيانات
mysql -u root -p << 'SQL'
CREATE DATABASE saiadmin_sudb999
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

CREATE USER 'sudanna_user'@'localhost'
  IDENTIFIED BY 'StrongPassword123!';

GRANT ALL PRIVILEGES ON saiadmin_sudb999.*
  TO 'sudanna_user'@'localhost';

FLUSH PRIVILEGES;
SQL

# تشغيل المخطط والـ migrations
mysql -u sudanna_user -p saiadmin_sudb999 \
  < /var/www/sudanna/sudanna_v22_schema_complete.sql

mysql -u sudanna_user -p saiadmin_sudb999 \
  < /var/www/sudanna/migration_fix.sql

mysql -u sudanna_user -p saiadmin_sudb999 \
  < /var/www/sudanna/seed.sql
```

---

## 6. إعداد config.php

```php
<?php
// Database
define('DB_HOST', '127.0.0.1');     // أو Managed MySQL endpoint
define('DB_PORT', 3306);
define('DB_NAME', 'saiadmin_sudb999');
define('DB_USER', 'sudanna_user');
define('DB_PASS', 'StrongPassword123!');

// Site
define('SITE_URL',   'https://yourdomain.com/s26');
define('UPLOAD_DIR', '/var/www/sudanna/uploads');
define('APP_ENV',    'production');

// AI Keys
define('GEMINI_API_KEY', 'AIzaSy...');
define('CLAUDE_API_KEY', 'sk-ant-...');
define('OPENAI_API_KEY', 'sk-...');

// Pricing (admin-controlled via platform_settings)
define('USD_TO_SDG_RATE',    4100);
define('SUB_PLUS_PRICE_SDG', 20000);
define('SUB_PRO_PRICE_SDG',  50000);

// Security
define('CSRF_SECRET',   bin2hex(random_bytes(32)));
define('SESSION_SECRET', bin2hex(random_bytes(32)));
define('WEBHOOK_SECRET', 'your_payment_webhook_secret');

// Limits
define('AI_DAILY_LIMIT_FREE', 20);
define('AI_DAILY_LIMIT_PLUS', 60);
define('AI_DAILY_LIMIT_PRO',  200);
```

---

## 7. SSL (Let's Encrypt)

```bash
certbot --nginx -d yourdomain.com -d www.yourdomain.com
# Auto-renewal:
crontab -e
# 0 12 * * * /usr/bin/certbot renew --quiet
```

---

## 8. Cron Jobs

```bash
crontab -e -u www-data
```

```
# تنظيف الـ cache كل 5 دقائق
*/5 * * * * php /var/www/sudanna/cron/clear_expired_cache.php

# تجديد رصيد وثائق الاشتراك (أول كل شهر)
0 0 1 * * php /var/www/sudanna/cron/renew_subscription_credits.php

# تقرير KPI اليومي
0 8 * * * php /var/www/sudanna/cron/daily_kpi.php

# تنظيف الـ rate limits القديمة
0 2 * * * php /var/www/sudanna/cron/cleanup_rate_limits.php

# backup قاعدة البيانات
0 3 * * * mysqldump -u sudanna_user -pPASSWORD saiadmin_sudb999 | gzip > /backups/db_$(date +\%Y\%m\%d).sql.gz
```

---

## 9. التحقق من النشر

```bash
# 1. PHP validation
for f in $(find /var/www/sudanna -name '*.php'); do
  php8.1 -l $f 2>&1 | grep -v 'No syntax'
done
# → يجب أن يكون فارغاً (0 أخطاء)

# 2. Go-live check
php /var/www/sudanna/go_live_proof.php
# → ✅ 184 PHP files valid | DB connected | All engines loaded

# 3. API check
curl https://yourdomain.com/api/public/pricing.php
# → {"rate":4100,"plans":{...}}

# 4. Database check
mysql -u sudanna_user -p saiadmin_sudb999 \
  -e "SELECT COUNT(*) FROM subscription_plans;"
# → 4 (free, plus, pro, corp)
```

---

## 10. Firewall

```bash
ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS
ufw deny 3306/tcp   # MySQL (internal only)
ufw enable
```

---

## 11. Monitoring

```bash
# CPU/RAM
apt install -y htop netdata

# Nginx logs
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

# PHP errors
tail -f /var/log/php8.1-fpm.log
```

---

## 12. Backup & Recovery

```bash
# Daily DB backup (automated)
mysqldump saiadmin_sudb999 | gzip > /backups/db_$(date +%Y%m%d).sql.gz

# Restore
gunzip < /backups/db_20260428.sql.gz | mysql saiadmin_sudb999

# Files backup to DigitalOcean Spaces
s3cmd sync /var/www/sudanna/uploads/ s3://sudanna-backups/uploads/
```

---

## Checklist الإطلاق

- [ ] PHP 8.1 مثبَّت و 0 parse errors
- [ ] MySQL: schema + migration + seed مُطبَّق
- [ ] config.php: جميع المفاتيح محدَّثة
- [ ] Nginx: SSL يعمل
- [ ] `/api/public/pricing.php` يُعيد JSON صحيح
- [ ] `go_live_proof.php` يمر بنجاح
- [ ] Admin login يعمل
- [ ] أول سؤال عبر visitor_ask يُجيب
- [ ] Cron jobs مُفعَّلة
- [ ] Firewall مُفعَّل
- [ ] Backups تعمل
