# SureRightStay Portal API - Deployment Guide

## 📋 Table of Contents

1. [Prerequisites](#prerequisites)
2. [Server Requirements](#server-requirements)
3. [Pre-Deployment Checklist](#pre-deployment-checklist)
4. [Deployment Steps](#deployment-steps)
5. [Post-Deployment Configuration](#post-deployment-configuration)
6. [SSL/HTTPS Setup](#sslhttps-setup)
7. [Performance Optimization](#performance-optimization)
8. [Backup Strategy](#backup-strategy)
9. [Monitoring & Logging](#monitoring--logging)
10. [Troubleshooting](#troubleshooting)

---

## 🔧 Prerequisites

Before deploying, ensure you have:

- [ ] Server access (SSH) with sudo privileges
- [ ] Domain name configured and pointing to server
- [ ] SSL certificate (Let's Encrypt recommended)
- [ ] Database credentials
- [ ] SMTP email credentials
- [ ] Git repository access

---

## 💻 Server Requirements

### Minimum Requirements

- **OS:** Ubuntu 20.04 LTS or higher (recommended) / CentOS 8+
- **PHP:** 8.2 or higher
- **Web Server:** Nginx 1.18+ or Apache 2.4+
- **Database:** MySQL 8.0+ or MariaDB 10.5+
- **Memory:** 2GB RAM minimum (4GB recommended)
- **Storage:** 20GB minimum
- **CPU:** 2 cores minimum

### Required PHP Extensions

```bash
php8.2-cli
php8.2-fpm
php8.2-mysql
php8.2-mbstring
php8.2-xml
php8.2-bcmath
php8.2-curl
php8.2-zip
php8.2-gd
php8.2-intl
php8.2-redis (optional, for caching)
```

### Additional Software

- Composer 2.x
- Node.js 18+ and NPM
- Redis (optional, for caching and queues)
- Supervisor (for queue workers)
- Certbot (for SSL certificates)

---

## ✅ Pre-Deployment Checklist

### Code Preparation

- [ ] All code committed to Git repository
- [ ] `.env.example` file is up to date
- [ ] Database migrations tested
- [ ] Dependencies updated (`composer update`, `npm update`)
- [ ] Code linted and formatted
- [ ] Tests passing

### Environment Configuration

- [ ] Production `.env` file prepared
- [ ] `APP_ENV=production`
- [ ] `APP_DEBUG=false`
- [ ] Strong `APP_KEY` generated
- [ ] Database credentials configured
- [ ] Mail configuration set
- [ ] JWT secret generated

### Security

- [ ] All sensitive data removed from repository
- [ ] `.env` file in `.gitignore`
- [ ] Strong database passwords
- [ ] Firewall rules configured
- [ ] SSH key-based authentication enabled

---

## 🚀 Deployment Steps

### Step 1: Server Setup (Ubuntu 20.04+)

```bash
# Update system packages
sudo apt update && sudo apt upgrade -y

# Install PHP 8.2 and extensions
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
sudo apt install -y php8.2 php8.2-fpm php8.2-cli php8.2-mysql \
    php8.2-mbstring php8.2-xml php8.2-bcmath php8.2-curl \
    php8.2-zip php8.2-gd php8.2-intl

# Install Nginx
sudo apt install -y nginx

# Install MySQL
sudo apt install -y mysql-server
sudo mysql_secure_installation

# Install Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

# Install Node.js and NPM
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs

# Install Redis (optional)
sudo apt install -y redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server

# Install Supervisor
sudo apt install -y supervisor
sudo systemctl enable supervisor
sudo systemctl start supervisor
```

### Step 2: Create Database

```bash
# Login to MySQL
sudo mysql -u root -p

# Create database and user
CREATE DATABASE srs_portal CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'srs_user'@'localhost' IDENTIFIED BY 'strong_password_here';
GRANT ALL PRIVILEGES ON srs_portal.* TO 'srs_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

### Step 3: Clone and Setup Application

```bash
# Create application directory
sudo mkdir -p /var/www/srs-portal
cd /var/www/srs-portal

# Clone repository
sudo git clone <your-repository-url> .

# Set ownership
sudo chown -R www-data:www-data /var/www/srs-portal
sudo chmod -R 755 /var/www/srs-portal

# Install PHP dependencies
sudo -u www-data composer install --optimize-autoloader --no-dev

# Install Node dependencies and build assets
npm install
npm run build

# Create .env file
sudo cp .env.example .env
sudo nano .env  # Edit with production settings
```

### Step 4: Configure Environment (.env)

```env
APP_NAME=SRS
APP_ENV=production
APP_KEY=base64:GENERATE_NEW_KEY_HERE
APP_DEBUG=false
APP_URL=https://yourdomain.com

LOG_CHANNEL=stack
LOG_LEVEL=error

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=srs_portal
DB_USERNAME=srs_user
DB_PASSWORD=your_strong_password

BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis

CACHE_STORE=redis
SESSION_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@example.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@yourdomain.com
MAIL_FROM_NAME="${APP_NAME}"

JWT_SECRET=GENERATE_STRONG_JWT_SECRET
```

### Step 5: Generate Keys and Run Migrations

```bash
# Generate application key
sudo -u www-data php artisan key:generate

# Generate JWT secret
sudo -u www-data php artisan jwt:secret

# Run migrations
sudo -u www-data php artisan migrate --force

# (Optional) Seed database with initial data
sudo -u www-data php artisan db:seed --force

# Clear and cache configuration
sudo -u www-data php artisan config:cache
sudo -u www-data php artisan route:cache
sudo -u www-data php artisan view:cache

# Create storage link
sudo -u www-data php artisan storage:link
```

### Step 6: Set Permissions

```bash
# Set correct permissions
sudo chown -R www-data:www-data /var/www/srs-portal
sudo chmod -R 755 /var/www/srs-portal
sudo chmod -R 775 /var/www/srs-portal/storage
sudo chmod -R 775 /var/www/srs-portal/bootstrap/cache
```

### Step 7: Configure Nginx

```bash
# Create Nginx configuration
sudo nano /etc/nginx/sites-available/srs-portal
```

**Nginx Configuration:**

```nginx
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    root /var/www/srs-portal/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

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

    location ~ /\.(?!well-known).* {
        deny all;
    }

    # Increase upload size limits
    client_max_body_size 20M;
}
```

```bash
# Enable site
sudo ln -s /etc/nginx/sites-available/srs-portal /etc/nginx/sites-enabled/

# Test Nginx configuration
sudo nginx -t

# Restart Nginx
sudo systemctl restart nginx
```

### Step 8: Configure Queue Workers (Supervisor)

```bash
# Create supervisor configuration
sudo nano /etc/supervisor/conf.d/srs-worker.conf
```

**Supervisor Configuration:**

```ini
[program:srs-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/srs-portal/artisan queue:work redis --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/srs-portal/storage/logs/worker.log
stopwaitsecs=3600
```

```bash
# Update supervisor
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start srs-worker:*
```

### Step 9: Configure Cron Jobs

```bash
# Edit crontab
sudo crontab -e -u www-data

# Add Laravel scheduler
* * * * * cd /var/www/srs-portal && php artisan schedule:run >> /dev/null 2>&1
```

---

## 🔒 SSL/HTTPS Setup

### Using Let's Encrypt (Certbot)

```bash
# Install Certbot
sudo apt install -y certbot python3-certbot-nginx

# Obtain SSL certificate
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

# Test auto-renewal
sudo certbot renew --dry-run
```

Certbot will automatically update your Nginx configuration for HTTPS.

---

## ⚡ Performance Optimization

### 1. Enable OPcache

```bash
# Edit PHP configuration
sudo nano /etc/php/8.2/fpm/php.ini

# Add/update these settings:
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.fast_shutdown=1

# Restart PHP-FPM
sudo systemctl restart php8.2-fpm
```

### 2. Configure Redis for Caching

```bash
# Edit Redis configuration
sudo nano /etc/redis/redis.conf

# Update settings:
maxmemory 256mb
maxmemory-policy allkeys-lru

# Restart Redis
sudo systemctl restart redis-server
```

### 3. Database Optimization

```sql
-- Add indexes to frequently queried columns
ALTER TABLE property_data ADD INDEX idx_listing_status (listing_status);
ALTER TABLE property_data ADD INDEX idx_state_area (state_id, area_id);
ALTER TABLE property_data ADD INDEX idx_price (price);
ALTER TABLE property_data ADD INDEX idx_created_by (created_by);
```

### 4. Enable Gzip Compression (Nginx)

Add to your Nginx server block:

```nginx
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml+rss application/json;
```

---

## 💾 Backup Strategy

### 1. Database Backup Script

```bash
# Create backup directory
sudo mkdir -p /var/backups/srs-portal

# Create backup script
sudo nano /usr/local/bin/srs-backup.sh
```

**Backup Script:**

```bash
#!/bin/bash

BACKUP_DIR="/var/backups/srs-portal"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="srs_portal"
DB_USER="srs_user"
DB_PASS="your_password"

# Database backup
mysqldump -u $DB_USER -p$DB_PASS $DB_NAME | gzip > $BACKUP_DIR/db_$DATE.sql.gz

# Application files backup
tar -czf $BACKUP_DIR/files_$DATE.tar.gz /var/www/srs-portal/storage

# Delete backups older than 7 days
find $BACKUP_DIR -type f -mtime +7 -delete

echo "Backup completed: $DATE"
```

```bash
# Make executable
sudo chmod +x /usr/local/bin/srs-backup.sh

# Add to crontab (daily at 2 AM)
sudo crontab -e
0 2 * * * /usr/local/bin/srs-backup.sh >> /var/log/srs-backup.log 2>&1
```

### 2. Automated Cloud Backup (Optional)

Consider using:
- AWS S3
- Google Cloud Storage
- DigitalOcean Spaces
- Backblaze B2

---

## 📊 Monitoring & Logging

### 1. Application Logs

```bash
# View Laravel logs
sudo tail -f /var/www/srs-portal/storage/logs/laravel.log

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

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

# View PHP-FPM logs
sudo tail -f /var/log/php8.2-fpm.log
```

### 2. Log Rotation

```bash
# Create log rotation config
sudo nano /etc/logrotate.d/srs-portal
```

```
/var/www/srs-portal/storage/logs/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
    sharedscripts
}
```

### 3. Monitoring Tools (Recommended)

- **New Relic** - Application performance monitoring
- **Sentry** - Error tracking
- **UptimeRobot** - Uptime monitoring
- **Grafana + Prometheus** - Metrics and dashboards

---

## 🔥 Troubleshooting

### Issue: 500 Internal Server Error

```bash
# Check Laravel logs
sudo tail -100 /var/www/srs-portal/storage/logs/laravel.log

# Check Nginx error logs
sudo tail -100 /var/log/nginx/error.log

# Check permissions
sudo chown -R www-data:www-data /var/www/srs-portal
sudo chmod -R 775 /var/www/srs-portal/storage
```

### Issue: Database Connection Failed

```bash
# Test database connection
mysql -u srs_user -p srs_portal

# Check .env database credentials
sudo nano /var/www/srs-portal/.env

# Clear config cache
sudo -u www-data php artisan config:clear
```

### Issue: Queue Jobs Not Processing

```bash
# Check supervisor status
sudo supervisorctl status

# Restart queue workers
sudo supervisorctl restart srs-worker:*

# Check worker logs
sudo tail -f /var/www/srs-portal/storage/logs/worker.log
```

### Issue: High Memory Usage

```bash
# Check PHP memory limit
php -i | grep memory_limit

# Increase if needed
sudo nano /etc/php/8.2/fpm/php.ini
# memory_limit = 512M

# Restart PHP-FPM
sudo systemctl restart php8.2-fpm
```

### Issue: Slow Performance

```bash
# Clear all caches
sudo -u www-data php artisan cache:clear
sudo -u www-data php artisan config:clear
sudo -u www-data php artisan route:clear
sudo -u www-data php artisan view:clear

# Rebuild caches
sudo -u www-data php artisan config:cache
sudo -u www-data php artisan route:cache
sudo -u www-data php artisan view:cache

# Optimize autoloader
sudo -u www-data composer dump-autoload --optimize
```

---

## 🔄 Deployment Updates

### Zero-Downtime Deployment Process

```bash
# 1. Enable maintenance mode
sudo -u www-data php artisan down

# 2. Pull latest code
sudo -u www-data git pull origin main

# 3. Update dependencies
sudo -u www-data composer install --no-dev --optimize-autoloader
npm install && npm run build

# 4. Run migrations
sudo -u www-data php artisan migrate --force

# 5. Clear and rebuild caches
sudo -u www-data php artisan cache:clear
sudo -u www-data php artisan config:cache
sudo -u www-data php artisan route:cache
sudo -u www-data php artisan view:cache

# 6. Restart services
sudo supervisorctl restart srs-worker:*
sudo systemctl reload php8.2-fpm

# 7. Disable maintenance mode
sudo -u www-data php artisan up
```

---

## 📞 Support

For deployment issues or questions:
- **Email:** admin@surerightstay.com
- **Documentation:** See API_DOCUMENTATION.md
- **Emergency:** Contact system administrator

---

**Last Updated:** February 15, 2026  
**Deployment Version:** 1.0
