# cPanel Deployment Guide for Laravel API

## Prerequisites
- Shared cPanel hosting account
- PHP 8.2 or higher
- MySQL/MariaDB database
- SSH access (recommended) or File Manager access
- Composer access (or ability to run composer commands)

## Step 1: Prepare Local Project

### 1.1 Exclude unnecessary files
Create or update `.gitignore` to exclude development files:
```
/node_modules
/vendor
/.idea
/.vscode
/.dockerignore
/Dockerfile
/compose.yaml
/docker
/tests
/phpunit.xml
/.phpunit.result.cache
```

### 1.2 Optimize for production
```bash
# Clear caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

# Optimize for production
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
```

## Step 2: Upload Files to cPanel

### Option A: Using File Manager
1. Compress project excluding `vendor` and `node_modules`:
   ```bash
   # On Windows (PowerShell)
   Compress-Archive -Path @('app','bootstrap','config','database','public','resources','routes','storage','vendor','artisan','composer.json','composer.lock','.env.example') -DestinationPath laravel-api.zip
   ```

2. Upload to cPanel:
   - Login to cPanel
   - Go to File Manager
   - Navigate to `public_html` or subdirectory
   - Upload and extract the zip file

### Option B: Using Git (Recommended)
```bash
# On cPanel server via SSH
cd ~/public_html
git clone https://your-repo-url.git .
```

### Option C: Using FTP/SFTP
- Upload all files except `vendor` and `node_modules`
- Use FileZilla or similar FTP client

## Step 3: Install Dependencies

### 3.1 Install Composer dependencies
```bash
# Via SSH
cd ~/public_html
composer install --optimize-autoloader --no-dev

# If composer is not available globally
php ~/composer.phar install --optimize-autoloader --no-dev
```

### 3.2 Set permissions
```bash
cd ~/public_html

# Set storage and cache directories writable
chmod -R 755 storage
chmod -R 755 bootstrap/cache

# Some hosts require 777 (less secure)
# chmod -R 777 storage
# chmod -R 777 bootstrap/cache
```

## Step 4: Configure Environment

### 4.1 Copy environment file
```bash
cp .env.example .env
```

### 4.2 Edit .env file
```bash
nano .env
```

Update these settings:
```env
APP_NAME="Your API Name"
APP_ENV=production
APP_KEY=base64:your-generated-key
APP_DEBUG=false
APP_URL=https://your-domain.com

LOG_CHANNEL=stack
LOG_LEVEL=error

# Database
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

# Cache
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
```

### 4.3 Generate application key
```bash
php artisan key:generate
```

## Step 5: Database Setup

### 5.1 Create database via cPanel
1. Login to cPanel
2. Go to "MySQL Databases"
3. Create new database
4. Create database user and password
5. Add user to database with all privileges

### 5.2 Run migrations
```bash
php artisan migrate --force
```

### 5.3 Seed database (optional)
```bash
php artisan db:seed --force
```

## Step 6: Configure Public Directory

### 6.1 Move files to public_html structure
cPanel typically requires the `public` directory contents to be in `public_html`:

**Option A: Move public contents (Recommended)**
```bash
# Move public contents to parent directory
mv public/* ./
mv public/.* ./
rmdir public
```

**Option B: Update server configuration**
If you can edit `.htaccess` or server config, keep structure and point domain to `public` directory.

### 6.2 Update index.php path
If you moved files, edit `index.php`:
```php
require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
```

Change to:
```php
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
```

## Step 7: Configure .htaccess

Create or update `.htaccess` in the public directory:
```apache
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

# Security headers
<IfModule mod_headers.c>
    Header set X-XSS-Protection "1; mode=block"
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
</IfModule>

# Disable directory browsing
Options -Indexes
```

## Step 8: Final Configuration

### 8.1 Set proper file permissions
```bash
# Set all files to 644
find . -type f -exec chmod 644 {} \;

# Set all directories to 755
find . -type d -exec chmod 755 {} \;

# Ensure storage and bootstrap/cache are writable
chmod -R 755 storage bootstrap/cache
```

### 8.2 Clear and cache again
```bash
php artisan cache:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### 8.3 Test the application
Visit your domain and test:
- Health endpoint: `https://your-domain.com/api/v1/health`
- Mock Nafath endpoint: `https://your-domain.com/api/v1/auth/nafath/mock/start`

## Step 9: SSL Configuration (Optional but Recommended)

### 9.1 Enable SSL via cPanel
1. Go to "SSL/TLS Status"
2. Enable AutoSSL for your domain

### 9.2 Force HTTPS
Add to `.htaccess`:
```apache
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```

## Step 10: Ongoing Maintenance

### 10.1 Deployment workflow
For future updates:
```bash
# Pull latest changes
git pull origin main

# Install/update dependencies
composer install --optimize-autoloader --no-dev

# Run migrations
php artisan migrate --force

# Clear and cache
php artisan cache:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### 10.2 Monitor logs
```bash
tail -f storage/logs/laravel.log
```

### 10.3 Backup regularly
- Use cPanel backup tool
- Export database regularly
- Keep off-site backups

## Troubleshooting

### 500 Internal Server Error
- Check `storage/logs/laravel.log`
- Verify file permissions
- Ensure `.env` exists and is configured
- Check PHP version (requires 8.2+)

### Database Connection Error
- Verify database credentials in `.env`
- Ensure database user has proper privileges
- Check if MySQL service is running

### Permission Denied
- Ensure storage and bootstrap/cache are writable
- Try `chmod -R 755 storage bootstrap/cache`

### Composer Not Found
- Use cPanel terminal with composer installed
- Or upload `vendor` directory from local development

### Routes Not Working
- Clear route cache: `php artisan route:clear`
- Check `.htaccess` configuration
- Ensure mod_rewrite is enabled

## cPanel-Specific Tips

### Select PHP Version
1. Go to "Select PHP Version"
2. Choose PHP 8.2 or higher
3. Enable required extensions: `mbstring`, `openssl`, `pdo`, `tokenizer`, `xml`, `ctype`, `json`, `bcmath`

### Cron Jobs (Optional)
For scheduled tasks:
1. Go to "Cron Jobs"
2. Add cron: `* * * * * cd /home/youruser/public_html && php artisan schedule:run >> /dev/null 2>&1`

### Queue Workers (Optional)
If using queues:
1. Go to "Cron Jobs"
2. Add: `* * * * * cd /home/youruser/public_html && php artisan queue:work --stop-when-empty`

## Security Recommendations

1. **Disable debug mode**: Set `APP_DEBUG=false` in `.env`
2. **Restrict access**: Use IP whitelisting for admin routes
3. **Regular updates**: Keep Laravel and dependencies updated
4. **Strong passwords**: Use strong database passwords
5. **SSL enabled**: Always use HTTPS in production
6. **Firewall**: Configure cPanel firewall or ModSecurity
7. **Backup**: Regular automated backups

## Performance Optimization

1. **Enable OPcache**: Ensure OPcache is enabled in PHP settings
2. **Database optimization**: Add indexes to frequently queried columns
3. **CDN**: Use CDN for static assets if applicable
4. **Gzip compression**: Enable in `.htaccess`
5. **HTTP/2**: Enable if supported by host

## Support Resources

- Laravel Documentation: https://laravel.com/docs/deployment
- cPanel Documentation: https://docs.cpanel.net/
- PHP Compatibility: Ensure PHP 8.2+ is available on your host
