# Co-Prod AI - Installation Guide

## System Requirements

### Minimum Requirements
- **PHP:** 8.3 or higher
- **MySQL:** 8.0 or higher
- **Web Server:** Apache 2.4+ or Nginx 1.18+
- **RAM:** 2GB minimum, 4GB recommended
- **Disk Space:** 10GB minimum
- **PHP Extensions:**
  - pdo_mysql
  - mbstring
  - json
  - openssl
  - gd
  - curl
  - zip
  - xml

### Recommended Requirements
- **PHP:** 8.3+
- **MySQL:** 8.0+
- **RAM:** 8GB+
- **Disk Space:** 50GB+
- **SSD Storage** for better performance
- **Redis** for caching (optional but recommended)

---

## Installation Steps

### 1. Clone the Repository

```bash
git clone https://github.com/your-org/coprod-ai.git
cd coprod-ai
```

### 2. Install Dependencies

#### Using Composer

```bash
composer install
```

#### Manual Installation

If Composer is not available, download the required packages manually:

- PHPMailer (for email)
- Stripe PHP SDK (for payments)
- Other dependencies as needed

### 3. Configure Environment

Copy the example configuration file:

```bash
cp config/config.example.php config/config.php
```

Edit `config/config.php` and set the following values:

```php
// Environment
define('ENVIRONMENT', 'production'); // or 'development'
define('DEBUG', false);

// Base URL
define('BASE_URL', 'https://yourdomain.com');

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'coprod_ai');
define('DB_USER', 'your_db_user');
define('DB_PASS', 'your_db_password');

// Session Configuration
define('SESSION_SECURE', true);

// Stripe Configuration (if using Stripe)
define('STRIPE_PUBLISHABLE_KEY', 'your_publishable_key');
define('STRIPE_SECRET_KEY', 'your_secret_key');
define('STRIPE_WEBHOOK_SECRET', 'your_webhook_secret');

// Email Configuration
define('SMTP_HOST', 'smtp.gmail.com');
define('SMTP_PORT', 587);
define('SMTP_USERNAME', 'your_email@gmail.com');
define('SMTP_PASSWORD', 'your_app_password');
define('SMTP_ENCRYPTION', 'tls');
```

### 4. Set Up Database

#### Create Database

```sql
CREATE DATABASE coprod_ai CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

#### Import Schema

```bash
mysql -u your_user -p coprod_ai < database/schema.sql
```

Or use MySQL command line:

```sql
USE coprod_ai;
SOURCE database/schema.sql;
```

#### Create Database User (Optional)

```sql
CREATE USER 'coprod_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON coprod_ai.* TO 'coprod_user'@'localhost';
FLUSH PRIVILEGES;
```

### 5. Set File Permissions

```bash
# Make storage directories writable
chmod -R 755 storage
chmod -R 777 storage/cache
chmod -R 777 storage/logs
chmod -R 777 storage/uploads
chmod -R 777 storage/midi
chmod -R 777 storage/audio
chmod -R 777 storage/exports

# Make logs directory writable
chmod -R 777 storage/logs
```

### 6. Configure Web Server

#### Apache Configuration

Create a virtual host configuration file:

```apache
<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /var/www/coprod-ai/public
    
    <Directory /var/www/coprod-ai/public>
        AllowOverride All
        Require all granted
        
        <IfModule mod_rewrite.c>
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteRule ^(.*)$ index.php [QSA,L]
        </IfModule>
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/coprod-ai-error.log
    CustomLog ${APACHE_LOG_DIR}/coprod-ai-access.log combined
</VirtualHost>
```

Enable mod_rewrite:

```bash
sudo a2enmod rewrite
sudo systemctl restart apache2
```

#### Nginx Configuration

Create an Nginx server block:

```nginx
server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/coprod-ai/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    # Block access to sensitive files
    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

Restart Nginx:

```bash
sudo systemctl restart nginx
sudo systemctl restart php8.3-fpm
```

### 7. Enable HTTPS (SSL/TLS)

#### Using Let's Encrypt (Certbot)

```bash
sudo certbot --apache -d yourdomain.com
# or for Nginx:
sudo certbot --nginx -d yourdomain.com
```

#### Manual SSL Configuration

Place your SSL certificates in the appropriate directory and update your web server configuration.

### 8. Configure Cron Jobs

Set up cron jobs for background tasks:

```bash
# Edit crontab
crontab -e
```

Add the following jobs:

```cron
# Process generation queue every 5 minutes
*/5 * * * * php /var/www/coprod-ai/artisan queue:work >> /dev/null 2>&1

# Clean up old cache files daily at midnight
0 0 * * * php /var/www/coprod-ai/artisan cache:clear >> /dev/null 2>&1

# Backup database daily at 2 AM
0 2 * * * /path/to/backup-script.sh >> /dev/null 2>&1

# Generate daily challenges at midnight
0 0 * * * php /var/www/coprod-ai/artisan challenges:generate >> /dev/null 2>&1

# Analyze producer DNA weekly
0 0 * * 0 php /var/www/coprod-ai/artisan producer-dna:analyze >> /dev/null 2>&1
```

### 9. Set Up Redis (Optional but Recommended)

#### Install Redis

```bash
sudo apt-get update
sudo apt-get install redis-server
```

#### Configure Redis

Edit `/etc/redis/redis.conf`:

```conf
bind 127.0.0.1
port 6379
maxmemory 256mb
maxmemory-policy allkeys-lru
```

#### Start Redis

```bash
sudo systemctl start redis
sudo systemctl enable redis
```

### 10. Configure Stripe (Optional)

If using Stripe for payments:

1. Create a Stripe account at https://stripe.com
2. Get your API keys from the Stripe Dashboard
3. Add your keys to `config/config.php`
4. Set up webhook endpoints in Stripe Dashboard:
   - `https://yourdomain.com/api/subscription/webhook`

### 11. Test Installation

#### Check PHP Version

```bash
php -v
```

#### Check Database Connection

Create a test file `test_db.php`:

```php
<?php
require_once 'config/config.php';

try {
    $db = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME,
        DB_USER,
        DB_PASS
    );
    echo "Database connection successful!";
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
}
```

Run the test:

```bash
php test_db.php
```

#### Test Web Server

Visit `http://yourdomain.com` in your browser. You should see the application.

---

## Development Setup

### Local Development with XAMPP/WAMP

1. Install XAMPP or WAMP
2. Start Apache and MySQL
3. Copy project files to `htdocs` folder
4. Import database schema using phpMyAdmin
5. Configure `config/config.php` for local environment
6. Access at `http://localhost/coprod-ai`

### Using Docker

Create a `docker-compose.yml` file:

```yaml
version: '3.8'

services:
  web:
    image: php:8.3-apache
    ports:
      - "8080:80"
    volumes:
      - .:/var/www/html
    depends_on:
      - db
    environment:
      - DB_HOST=db
      - DB_NAME=coprod_ai
      - DB_USER=root
      - DB_PASS=root

  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: coprod_ai
    ports:
      - "3306:3306"
    volumes:
      - ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql

  redis:
    image: redis:alpine
    ports:
      - "6379:6379"
```

Run with Docker Compose:

```bash
docker-compose up -d
```

---

## Troubleshooting

### Database Connection Issues

**Problem:** "SQLSTATE[HY000] [2002] Connection refused"

**Solution:**
- Check MySQL is running: `sudo systemctl status mysql`
- Verify DB_HOST, DB_NAME, DB_USER, DB_PASS in config
- Check firewall settings

### Permission Issues

**Problem:** "Permission denied" when writing to storage

**Solution:**
```bash
sudo chown -R www-data:www-data storage
sudo chmod -R 775 storage
```

### Session Issues

**Problem:** Sessions not persisting

**Solution:**
- Check session.save_path in php.ini
- Ensure storage directory is writable
- Verify session cookie settings

### Mod Rewrite Not Working

**Problem:** URLs returning 404 errors

**Solution:**
```bash
sudo a2enmod rewrite
sudo systemctl restart apache2
```

Check `.htaccess` file exists in public directory.

### Email Not Sending

**Problem:** Emails not being delivered

**Solution:**
- Verify SMTP credentials
- Check if port 587 is blocked by firewall
- Use app-specific password for Gmail
- Check spam folder

### WebSocket Connection Issues

**Problem:** WebSocket not connecting

**Solution:**
- Verify WebSocket server is running
- Check firewall allows WebSocket connections
- Ensure correct WebSocket URL in client code

---

## Security Checklist

After installation, ensure the following security measures are in place:

- [ ] Change default database passwords
- [ ] Enable HTTPS with valid SSL certificate
- [ ] Set ENVIRONMENT to 'production'
- [ ] Set DEBUG to false
- [ ] Configure proper file permissions
- [ ] Enable firewall rules
- [ ] Set up regular database backups
- [ ] Configure rate limiting
- [ ] Enable CSRF protection
- [ ] Implement password complexity requirements
- [ ] Set up 2FA for admin accounts
- [ ] Regularly update PHP and dependencies
- [ ] Monitor error logs for suspicious activity
- [ ] Implement IP whitelisting for admin access (optional)

---

## Performance Optimization

### Enable OPcache

Edit `php.ini`:

```ini
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
```

### Enable Gzip Compression

Add to Apache configuration:

```apache
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
```

### Configure MySQL Performance

Edit `my.cnf`:

```ini
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
query_cache_size = 64M
max_connections = 200
```

### Use CDN for Static Assets

Configure CDN for CSS, JS, and images to reduce server load.

---

## Cronjob Setup

The platform includes a cronjob script for scheduled maintenance tasks. Set up the following cron jobs:

### Recommended Cron Schedule

```bash
# Run all tasks daily at midnight
0 0 * * * /usr/bin/php /path/to/coprod-ai/cronjob.php all >> /var/log/coprod-ai-cron.log 2>&1

# Or run individual tasks at different intervals
# Check subscriptions every hour
0 * * * * /usr/bin/php /path/to/coprod-ai/cronjob.php subscriptions >> /var/log/coprod-ai-cron.log 2>&1

# Process withdrawals every 30 minutes
*/30 * * * * /usr/bin/php /path/to/coprod-ai/cronjob.php withdrawals >> /var/log/coprod-ai-cron.log 2>&1

# Update exchange rates daily at 6 AM
0 6 * * * /usr/bin/php /path/to/coprod-ai/cronjob.php rates >> /var/log/coprod-ai-cron.log 2>&1

# Cleanup old data weekly on Sunday at 3 AM
0 3 * * 0 /usr/bin/php /path/to/coprod-ai/cronjob.php cleanup >> /var/log/coprod-ai-cron.log 2>&1
```

### Available Tasks

- `all`: Run all maintenance tasks
- `subscriptions`: Check and expire subscriptions
- `withdrawals`: Process pending withdrawals via PawaPay API
- `rates`: Update currency exchange rates from ExchangeRate-API
- `cleanup`: Clean up old temporary data

### Environment Variables

Add the following to your environment or `.env` file:

```bash
PAWAPAY_TOKEN=your_pawapay_token_here
EXCHANGERATE_API_KEY=your_exchangerate_api_key_here
```

### cPanel Cron Setup

If using cPanel:

1. Go to **Cron Jobs** in cPanel
2. Add a new cron job with the command:
   ```
   php /home/youruser/public_html/coprod-ai/cronjob.php all
   ```
3. Set the schedule as needed (e.g., Once a day)

---

## Backup Strategy

### Database Backup

Create a backup script:

```bash
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backups/mysql"
mkdir -p $BACKUP_DIR

mysqldump -u root -p coprod_ai > $BACKUP_DIR/coprod_ai_$DATE.sql

# Keep only last 7 days
find $BACKUP_DIR -name "coprod_ai_*.sql" -mtime +7 -delete
```

### File Backup

```bash
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backups/files"
mkdir -p $BACKUP_DIR

tar -czf $BACKUP_DIR/coprod_ai_files_$DATE.tar.gz /var/www/coprod-ai/storage

# Keep only last 7 days
find $BACKUP_DIR -name "coprod_ai_files_*.tar.gz" -mtime +7 -delete
```

---

## Monitoring

### Enable Error Logging

Ensure error logging is enabled in `php.ini`:

```ini
log_errors = On
error_log = /var/www/coprod-ai/storage/logs/error.log
```

### Monitor Server Resources

Use tools like:
- htop
- iostat
- netstat
- Apache/Nginx status pages

### Set Up Uptime Monitoring

Use services like:
- UptimeRobot
- Pingdom
- StatusCake

---

## Update Process

### Update Code

```bash
git pull origin main
composer install
```

### Update Database

```bash
# Run any new migrations
php artisan migrate
```

### Clear Cache

```bash
php artisan cache:clear
```

### Restart Services

```bash
sudo systemctl restart apache2
sudo systemctl restart redis
```

---

## Support

For installation support:
- Documentation: https://docs.coprod.ai
- Issues: https://github.com/your-org/coprod-ai/issues
- Email: support@coprod.ai

---

## Next Steps

After installation:

1. Create admin account
2. Configure payment gateway (if needed)
3. Set up email templates
4. Configure WebSocket server
5. Test all features
6. Set up monitoring
7. Configure backups
8. Go live!

---

Installation Guide version: 1.0.0
Last updated: June 2026
