# Sirus CRM - Deployment Guide

## Pre-Deployment Checklist

- [ ] Environment: PHP 7.4+ with MySQL 5.7+
- [ ] cPanel/hosting account with SSH access (recommended)
- [ ] Database created and accessible
- [ ] All files backed up locally
- [ ] Configuration file (config.php) prepared
- [ ] SSL certificate enabled on domain
- [ ] Email service configured (Brevo/SendGrid)

---

## Phase 1: Local Testing

### 1.1 Install Local Environment
**For Windows (XAMPP):**
```bash
# Download XAMPP from https://www.apachefriends.org/
# Extract to C:\xampp
# Start Apache & MySQL from XAMPP Control Panel
```

**For Mac (MAMP):**
```bash
# Download from https://www.mamp.info/
# Extract and install
# Start servers from MAMP Pro
```

**For Linux (Apache + MySQL):**
```bash
sudo apt-get update
sudo apt-get install apache2 php php-mysql mysql-server php-curl php-json
sudo systemctl start apache2 mysql
```

### 1.2 Set Up Local Database
```bash
# Connect to MySQL
mysql -u root -p

# Create database
CREATE DATABASE sirus_crm_local;
CREATE USER 'sirus_user'@'localhost' IDENTIFIED BY 'secure_password_123';
GRANT ALL PRIVILEGES ON sirus_crm_local.* TO 'sirus_user'@'localhost';
FLUSH PRIVILEGES;

# Exit MySQL
EXIT;
```

### 1.3 Import Schema
```bash
# From project root
mysql -u sirus_user -p sirus_crm_local < public_html/api/schema.sql
```

### 1.4 Configure Local Config
Create/update `public_html/config.php`:
```php
<?php
return [
    'db' => [
        'host' => 'localhost',
        'name' => 'sirus_crm_local',
        'user' => 'sirus_user',
        'pass' => 'secure_password_123',
        'charset' => 'utf8mb4'
    ],
    'app' => [
        'name' => 'Sirus CRM',
        'url' => 'http://localhost/sirus-crm'
    ],
    'email' => [
        'from' => 'noreply@siruscrm.local',
        'from_name' => 'Sirus CRM'
    ],
    'brevo' => [
        'api_key' => 'your_brevo_api_key_here',
        'from_email' => 'support@siruscrm.local'
    ]
];
```

### 1.5 Test Locally
```bash
# Start local server
php -S localhost:8000

# Open browser
# http://localhost:8000
```

**Test Flows:**
- [ ] Admin login (dashboard.html)
- [ ] Client login (client-login.php)
- [ ] Finance dashboard loads
- [ ] Client portal displays
- [ ] Create test invoice/expense
- [ ] Submit finance request from client
- [ ] Respond as admin

---

## Phase 2: Production Preparation

### 2.1 Get Production Database Credentials
From cPanel:
```
Host: localhost (or your.hosting.server)
Database: your_crm_db
Username: your_crm_user
Password: [generate strong password]
```

### 2.2 Create Production Config
Create `public_html/config.php` on production:
```php
<?php
return [
    'db' => [
        'host' => 'localhost',
        'name' => 'your_production_db_name',
        'user' => 'your_db_user',
        'pass' => 'your_secure_db_password',
        'charset' => 'utf8mb4'
    ],
    'app' => [
        'name' => 'Sirus CRM',
        'url' => 'https://yourdomain.com/crm'
    ],
    'email' => [
        'from' => 'noreply@yourdomain.com',
        'from_name' => 'Sirus CRM'
    ],
    'brevo' => [
        'api_key' => 'your_production_brevo_api_key',
        'from_email' => 'support@yourdomain.com'
    ]
];
```

### 2.3 Create .htaccess for Security
Create `public_html/.htaccess`:
```apache
# Enable HTTPS redirect
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Disable directory listing
Options -Indexes

# Protect sensitive files
<FilesMatch "^(config|\.env|\.git)">
    Order allow,deny
    Deny from all
</FilesMatch>

# Set proper headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-XSS-Protection "1; mode=block"
    Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>
```

---

## Phase 3: Deploy to Hosting

### 3.1 Upload Files via FTP/SFTP
```bash
# Using SFTP (recommended)
sftp your_sftp_username@your.hosting.server

# Navigate to public_html
cd public_html

# Upload all files
put -r .

# Exit
exit
```

### 3.2 Upload via cPanel File Manager
1. Log in to cPanel
2. Open File Manager
3. Navigate to `public_html`
4. Upload all files from `Sirus CRM/public_html`

### 3.3 Set File Permissions
```bash
# Via SSH
ssh your_ssh_username@your.hosting.server

# Navigate to public_html
cd ~/public/html/crm

# Set directory permissions
find . -type d -exec chmod 755 {} \;

# Set file permissions
find . -type f -exec chmod 644 {} \;

# Make upload directories writable
chmod -R 775 public_html/uploads/
chmod -R 775 public_html/api/

# Exit SSH
exit
```

### 3.4 Deploy Database Schema
```bash
# Option 1: Via phpMyAdmin (cPanel)
1. Log in to cPanel
2. Open phpMyAdmin
3. Create new database
4. Go to Import tab
5. Upload public_html/api/schema.sql
6. Click Import

# Option 2: Via SSH
ssh your_ssh_username@your.hosting.server
mysql -u your_db_user -p your_db_name < ~/public_html/api/schema.sql
exit
```

### 3.5 Configure Email Service

**For Brevo Integration:**
1. Sign up at https://www.brevo.com/
2. Get API key from Settings → SMTP & API
3. Update `config.php` with API key
4. Create sender email in Brevo dashboard

**For SendGrid (alternative):**
1. Sign up at https://sendgrid.com/
2. Get API key
3. Update email config in `config.php`

---

## Phase 4: Post-Deployment Configuration

### 4.1 Verify Database Connection
Create temporary test file: `public_html/test-db.php`
```php
<?php
require 'api/db.php';
try {
    $stmt = $pdo->query("SELECT 1");
    echo "✅ Database connection successful!";
} catch (Exception $e) {
    echo "❌ Database error: " . $e->getMessage();
}
?>
```

Visit: `https://yourdomain.com/crm/test-db.php`

Then delete the file.

### 4.2 Initialize Sample Data (Optional)
```php
// Create test admin user
INSERT INTO users (name, email, password, role) VALUES 
('Admin', 'admin@siruscrm.com', PASSWORD('admin123'), 'Admin');

// Create test client
INSERT INTO clients (name, email, password) VALUES 
('Test Client', 'client@test.com', PASSWORD('client123'));

// Create sample service
INSERT INTO services (name, base_price, tax_rate) VALUES 
('GST Compliance', 5000, 18),
('ITR Filing', 3000, 18),
('Company Registration', 8000, 18);
```

### 4.3 Create Admin User via Admin Panel
1. Visit `https://yourdomain.com/crm/login.php`
2. Run initial admin setup script (if included)
3. Or manually insert via phpMyAdmin

### 4.4 Test All Core Features
- [ ] Admin login
- [ ] Client login
- [ ] Create invoice
- [ ] Add expense
- [ ] Create campaign
- [ ] Submit finance request
- [ ] Respond to request
- [ ] Download CSV export

---

## Phase 5: Security Hardening

### 5.1 Change Permissions on Sensitive Files
```bash
ssh your_ssh_username@your.hosting.server
cd ~/public_html/crm

# Make config read-only
chmod 400 config.php

# Exit
exit
```

### 5.2 Enable HTTPS/SSL
**Via cPanel AutoSSL:**
1. Go to cPanel
2. AutoSSL
3. Click "Run AutoSSL"

**Or use Certbot for Let's Encrypt:**
```bash
ssh your_ssh_username@your.hosting.server
certbot certonly --webroot -w /home/user/public_html/crm -d yourdomain.com
```

### 5.3 Set Up Database Backups
**cPanel Automated Backups:**
1. cPanel → Backups
2. Set backup frequency
3. Enable email notifications

**Manual MySQL Backup:**
```bash
mysqldump -u user -p database_name > backup_$(date +%Y%m%d).sql
```

### 5.4 Configure Error Logging
Update `public_html/api/db.php`:
```php
// Log errors to file instead of displaying
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/home/username/logs/php_errors.log');
```

---

## Phase 6: Monitoring & Maintenance

### 6.1 Set Up Monitoring
- [ ] Monitor disk space (cPanel)
- [ ] Monitor database size
- [ ] Monitor email delivery (Brevo/SendGrid dashboard)
- [ ] Check error logs weekly

### 6.2 Regular Maintenance Tasks
```bash
# Weekly: Check error logs
tail -f /home/username/logs/php_errors.log

# Monthly: Archive old activity logs
DELETE FROM activity_log WHERE created_at < DATE_SUB(NOW(), INTERVAL 90 DAY);

# Monthly: Backup database
mysqldump -u user -p database > backup_$(date +%Y%m%d).sql

# Quarterly: Update PHP/MySQL if available
```

### 6.3 Monitoring Dashboard
Access admin panel:
- [ ] Finance Dashboard: `https://yourdomain.com/crm/finance.php`
- [ ] Admin Hub: `https://yourdomain.com/crm/admin-hub.php`
- [ ] Client Requests: `https://yourdomain.com/crm/admin-client-requests.php`

---

## Troubleshooting

### Database Connection Error
**Error:** "Database connection failed"

**Solutions:**
```bash
# 1. Verify credentials in config.php
# 2. Check database exists
mysql -u user -p -e "SHOW DATABASES LIKE 'crm_db';"

# 3. Check user permissions
SHOW GRANTS FOR 'user'@'localhost';

# 4. Check MySQL is running
systemctl status mysql
```

### File Permissions Error
**Error:** "Permission denied" or "Cannot write"

**Solution:**
```bash
# Fix permissions
chmod 755 public_html/
chmod 644 public_html/*
chmod 775 public_html/uploads/
chmod 775 public_html/api/
```

### Email Not Sending
**Error:** "Failed to send email"

**Solutions:**
1. Verify Brevo API key in config.php
2. Check sender email is verified in Brevo
3. Check PHP mail() is enabled: `php -i | grep mail`
4. Review Brevo dashboard for bounce/spam

### Login Issues
**Error:** "Invalid credentials"

**Solutions:**
```bash
# Verify user exists
mysql -u user -p database -e "SELECT * FROM users WHERE email='admin@test.com';"

# Reset password via phpMyAdmin (if needed)
UPDATE users SET password=PASSWORD('newpass123') WHERE email='admin@test.com';
```

### Slow Performance
**Solutions:**
1. Enable MySQL query cache
2. Add database indexes to frequently queried fields
3. Implement caching (Redis/Memcached)
4. Optimize images and assets
5. Enable gzip compression in .htaccess

---

## Rollback Plan

If issues occur in production:

```bash
# 1. Stop accepting new requests
# Edit .htaccess to show maintenance page

# 2. Restore from backup
mysql -u user -p database < backup_YYYYMMDD.sql

# 3. Revert code
git revert [commit_hash]
# or manually restore previous version

# 4. Clear caches
php -r "apc_clear_cache();"

# 5. Test thoroughly
# Run test-db.php and test all core functions

# 6. Resume service
# Remove maintenance page from .htaccess
```

---

## Post-Launch Support

**Critical Files to Monitor:**
- `/logs/php_errors.log`
- `/api/db.php` - Database connection
- `/config.php` - Configuration

**Support Contacts:**
- Hosting Provider: [Your hosting support]
- Database Issues: Check MySQL logs
- Email Issues: Brevo dashboard
- Code Issues: Check application logs

**First 48 Hours Checklist:**
- [ ] Monitor for errors
- [ ] Verify all users can login
- [ ] Test payment/invoice workflows
- [ ] Check email delivery
- [ ] Monitor database performance
- [ ] Verify all reports generate correctly

---

## Success Criteria

✅ System is considered successfully deployed when:
1. Admin can log in and access all dashboards
2. Clients can log in and view finances
3. Invoices/expenses can be created and managed
4. Finance requests can be submitted and responded to
5. Reports export correctly (CSV)
6. Emails are sent and delivered
7. Real-time data updates work (30-60s polling)
8. No error logs in last 24 hours
9. Database backups are automated
10. SSL/HTTPS is working

---

**Need Help?** Check logs at: `/home/username/logs/php_errors.log`
