# KADSB Website - Deployment Guide

Comprehensive deployment guide for production servers.

## 🖥️ Server Requirements

### Minimum Specifications
- CPU: 2 cores
- RAM: 4 GB
- Storage: 20 GB SSD
- OS: Ubuntu 20.04 LTS or later / CentOS 8+

### Recommended Specifications
- CPU: 4 cores
- RAM: 8 GB
- Storage: 50 GB SSD
- OS: Ubuntu 22.04 LTS

## 📦 Software Requirements

- PHP 8.0+
- PostgreSQL 12+
- Apache 2.4+ or Nginx 1.18+
- Composer 2.0+
- SSL Certificate
- Git (for deployment)

## 🔧 Server Setup

### 1. Update System

```bash
sudo apt update && sudo apt upgrade -y
```

### 2. Install PHP 8.x

```bash
# Add PHP repository
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update

# Install PHP and extensions
sudo apt install -y php8.2 php8.2-fpm php8.2-pgsql php8.2-mbstring \
    php8.2-xml php8.2-curl php8.2-zip php8.2-gd php8.2-intl

# Verify installation
php -v
```

### 3. Install PostgreSQL

```bash
# Install PostgreSQL
sudo apt install -y postgresql postgresql-contrib

# Start and enable PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Verify installation
sudo -u postgres psql --version
```

### 4. Install Composer

```bash
# Download Composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
sudo mv composer.phar /usr/local/bin/composer
php -r "unlink('composer-setup.php');"

# Verify installation
composer --version
```

### 5. Install Web Server

#### Option A: Apache

```bash
# Install Apache
sudo apt install -y apache2

# Enable required modules
sudo a2enmod rewrite headers expires deflate ssl

# Start and enable Apache
sudo systemctl start apache2
sudo systemctl enable apache2
```

#### Option B: Nginx (Recommended)

```bash
# Install Nginx
sudo apt install -y nginx

# Start and enable Nginx
sudo systemctl start nginx
sudo systemctl enable nginx
```

## 🗄️ Database Setup

### 1. Secure PostgreSQL Installation

```bash
# Set PostgreSQL password
sudo -u postgres psql
ALTER USER postgres PASSWORD 'your_strong_password';
\q
```

### 2. Create Database and User

```bash
sudo -u postgres psql

CREATE DATABASE kadsb_website;
CREATE USER kadsb_user WITH ENCRYPTED PASSWORD 'your_secure_password_here';
GRANT ALL PRIVILEGES ON DATABASE kadsb_website TO kadsb_user;

# Grant schema permissions
\c kadsb_website
GRANT ALL ON SCHEMA public TO kadsb_user;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO kadsb_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO kadsb_user;

\q
```

### 3. Configure PostgreSQL Access

```bash
# Edit pg_hba.conf
sudo nano /etc/postgresql/14/main/pg_hba.conf

# Add this line for local access:
local   kadsb_website    kadsb_user                      md5
host    kadsb_website    kadsb_user    127.0.0.1/32      md5

# Restart PostgreSQL
sudo systemctl restart postgresql
```

### 4. Import Database Schema

```bash
# Test connection
psql -U kadsb_user -d kadsb_website -h localhost

# Import schema
psql -U kadsb_user -d kadsb_website -h localhost -f database/schema.sql

# Import sample data
psql -U kadsb_user -d kadsb_website -h localhost -f database/seed_services.sql
```

## 🚀 Application Deployment

### 1. Create Application Directory

```bash
# Create directory
sudo mkdir -p /var/www/kadsb
cd /var/www/kadsb

# Copy application files
# (Upload via SCP, FTP, or Git)

# Set ownership
sudo chown -R www-data:www-data /var/www/kadsb

# Set permissions
sudo find /var/www/kadsb -type f -exec chmod 644 {} \;
sudo find /var/www/kadsb -type d -exec chmod 755 {} \;

# Special permissions for writable directories
sudo chmod -R 775 /var/www/kadsb/public/uploads
sudo chmod -R 775 /var/www/kadsb/logs
```

### 2. Install Dependencies

```bash
cd /var/www/kadsb
sudo -u www-data composer install --no-dev --optimize-autoloader
```

### 3. Configure Environment

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

# Edit configuration
nano .env
```

**Important configurations:**

```ini
# Production settings
APP_ENV=production
APP_DEBUG=false
APP_URL=https://www.kadsb.com.my

# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=kadsb_website
DB_USER=kadsb_user
DB_PASS=your_database_password

# Email (Microsoft 365)
SMTP_HOST=smtp.office365.com
SMTP_PORT=587
SMTP_ENCRYPTION=tls
SMTP_USERNAME=noreply@kadsb.com.my
SMTP_PASSWORD=your_email_password
SMTP_FROM_EMAIL=noreply@kadsb.com.my

# Admin Emails
ADMIN_EMAIL=admin@kadsb.com.my
HR_EMAIL=hr@kadsb.com.my
SALES_EMAIL=sales@kadsb.com.my

# reCAPTCHA
RECAPTCHA_SITE_KEY=your_recaptcha_site_key
RECAPTCHA_SECRET_KEY=your_recaptcha_secret_key

# Security
ENCRYPTION_KEY=$(openssl rand -hex 32)
```

### 4. Secure .env File

```bash
sudo chmod 600 /var/www/kadsb/.env
sudo chown www-data:www-data /var/www/kadsb/.env
```

## 🌐 Web Server Configuration

### Apache Configuration

#### Virtual Host (HTTP)

```bash
# Create virtual host file
sudo nano /etc/apache2/sites-available/kadsb.conf
```

Add configuration:

```apache
<VirtualHost *:80>
    ServerName www.kadsb.com.my
    ServerAlias kadsb.com.my

    DocumentRoot /var/www/kadsb/public

    <Directory /var/www/kadsb/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Logging
    ErrorLog ${APACHE_LOG_DIR}/kadsb_error.log
    CustomLog ${APACHE_LOG_DIR}/kadsb_access.log combined

    # Security Headers
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
</VirtualHost>
```

Enable site:

```bash
sudo a2ensite kadsb.conf
sudo systemctl reload apache2
```

### Nginx Configuration (Recommended)

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

Add configuration:

```nginx
server {
    listen 80;
    listen [::]:80;

    server_name www.kadsb.com.my kadsb.com.my;
    root /var/www/kadsb/public;

    index index.html index.php;

    # Logging
    access_log /var/log/nginx/kadsb_access.log;
    error_log /var/log/nginx/kadsb_error.log;

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

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

    # API routes
    location ~ ^/api/ {
        try_files $uri /api.php?$query_string;

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

    # PHP files
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # Deny access to sensitive files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    location ~ \.(env|md|sql|log|sh)$ {
        deny all;
        access_log off;
        log_not_found off;
    }

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

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml;
}
```

Enable site:

```bash
sudo ln -s /etc/nginx/sites-available/kadsb /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

## 🔒 SSL Certificate Setup

### Using Let's Encrypt (Free)

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

# For Apache
sudo apt install -y python3-certbot-apache
sudo certbot --apache -d www.kadsb.com.my -d kadsb.com.my

# For Nginx
sudo apt install -y python3-certbot-nginx
sudo certbot --nginx -d www.kadsb.com.my -d kadsb.com.my

# Auto-renewal
sudo certbot renew --dry-run
```

### Manual SSL Certificate

If using a purchased SSL certificate:

#### For Apache

```bash
sudo nano /etc/apache2/sites-available/kadsb-ssl.conf
```

```apache
<VirtualHost *:443>
    ServerName www.kadsb.com.my
    ServerAlias kadsb.com.my

    DocumentRoot /var/www/kadsb/public

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/kadsb.crt
    SSLCertificateKeyFile /etc/ssl/private/kadsb.key
    SSLCertificateChainFile /etc/ssl/certs/kadsb-chain.crt

    # ... rest of configuration
</VirtualHost>
```

#### For Nginx

Add to existing server block:

```nginx
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    ssl_certificate /etc/ssl/certs/kadsb.crt;
    ssl_certificate_key /etc/ssl/private/kadsb.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # ... rest of configuration
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name www.kadsb.com.my kadsb.com.my;
    return 301 https://$server_name$request_uri;
}
```

## 🔥 Firewall Configuration

```bash
# UFW (Ubuntu Firewall)
sudo ufw allow OpenSSH
sudo ufw allow 'Apache Full'  # or 'Nginx Full'
sudo ufw allow 5432/tcp  # PostgreSQL (if remote access needed)
sudo ufw enable

# Check status
sudo ufw status
```

## 📧 Email Configuration

### Microsoft 365 SMTP Setup

1. **Create dedicated email account**
   - Login to Microsoft 365 Admin Center
   - Create: noreply@kadsb.com.my

2. **Enable SMTP AUTH**
   - Go to Settings > Mail flow
   - Enable SMTP AUTH for the account

3. **Test SMTP connection**

```bash
# Install mail utilities
sudo apt install -y mailutils

# Test email
echo "Test email from KADSB" | mail -s "Test" your-email@example.com
```

## 🧪 Post-Deployment Testing

### 1. Test Website Access

```bash
curl -I https://www.kadsb.com.my
```

Expected: HTTP 200 OK

### 2. Test API Endpoints

```bash
# Test CSRF token
curl https://www.kadsb.com.my/api.php?route=csrf

# Test services endpoint
curl https://www.kadsb.com.my/api.php?route=service&action=all
```

### 3. Test Database Connection

```bash
psql -U kadsb_user -d kadsb_website -h localhost -c "SELECT COUNT(*) FROM services;"
```

### 4. Test Email Sending

Submit a test contact form through the website.

### 5. Check Logs

```bash
# Application logs
tail -f /var/www/kadsb/logs/error.log

# Apache logs
tail -f /var/log/apache2/kadsb_error.log

# Nginx logs
tail -f /var/log/nginx/kadsb_error.log

# PostgreSQL logs
sudo tail -f /var/log/postgresql/postgresql-14-main.log
```

## 🔄 Backup Strategy

### 1. Database Backup

```bash
# Create backup script
sudo nano /usr/local/bin/backup-kadsb-db.sh
```

```bash
#!/bin/bash
BACKUP_DIR="/backup/kadsb"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="kadsb_db_$DATE.sql"

mkdir -p $BACKUP_DIR
pg_dump -U kadsb_user -h localhost kadsb_website > $BACKUP_DIR/$BACKUP_FILE
gzip $BACKUP_DIR/$BACKUP_FILE

# Keep only last 30 days
find $BACKUP_DIR -name "*.gz" -mtime +30 -delete

echo "Backup completed: $BACKUP_FILE.gz"
```

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

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

### 2. File Backup

```bash
# Backup uploads directory
tar -czf /backup/kadsb/uploads_$(date +%Y%m%d).tar.gz /var/www/kadsb/public/uploads
```

## 📊 Monitoring

### 1. Setup Log Rotation

```bash
sudo nano /etc/logrotate.d/kadsb
```

```
/var/www/kadsb/logs/*.log {
    daily
    rotate 30
    compress
    delaycompress
    notifempty
    create 0640 www-data www-data
    sharedscripts
}
```

### 2. Monitor System Resources

```bash
# Install monitoring tools
sudo apt install -y htop iotop nethogs

# Check disk usage
df -h

# Check memory
free -h

# Monitor in real-time
htop
```

## 🚨 Troubleshooting

### Common Issues

#### 1. 500 Internal Server Error
- Check PHP error logs
- Verify file permissions
- Check .htaccess syntax (Apache)

#### 2. Database Connection Failed
- Verify PostgreSQL is running
- Check credentials in .env
- Test connection manually

#### 3. Email Not Sending
- Check SMTP credentials
- Verify firewall allows port 587
- Check email logs in database

#### 4. File Upload Fails
- Check uploads/ directory permissions
- Verify PHP upload settings
- Check disk space

## 📈 Performance Tuning

### PHP-FPM Optimization

```bash
sudo nano /etc/php/8.2/fpm/pool.d/www.conf
```

```ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
```

### PostgreSQL Tuning

```bash
sudo nano /etc/postgresql/14/main/postgresql.conf
```

```ini
shared_buffers = 256MB
effective_cache_size = 1GB
maintenance_work_mem = 64MB
checkpoint_completion_target = 0.9
wal_buffers = 16MB
default_statistics_target = 100
```

## 🔐 Security Hardening

```bash
# Disable directory listing
# (Already configured in .htaccess/nginx.conf)

# Hide PHP version
sudo nano /etc/php/8.2/fpm/php.ini
expose_php = Off

# Disable dangerous PHP functions
disable_functions = exec,passthru,shell_exec,system,proc_open,popen

# Restart services
sudo systemctl restart php8.2-fpm
sudo systemctl restart nginx  # or apache2
```

## ✅ Deployment Checklist

- [ ] Server setup complete
- [ ] PHP and extensions installed
- [ ] PostgreSQL installed and configured
- [ ] Database created and schema imported
- [ ] Application files deployed
- [ ] Composer dependencies installed
- [ ] .env configured with production values
- [ ] Web server configured (Apache/Nginx)
- [ ] SSL certificate installed
- [ ] Firewall configured
- [ ] Email tested and working
- [ ] All forms tested
- [ ] Backup system configured
- [ ] Monitoring setup
- [ ] Security hardening applied
- [ ] DNS configured
- [ ] Analytics configured
- [ ] Performance optimized

---

**Deployment completed! Website ready for production use.**
