# Sirus CRM - Troubleshooting Guide

## Common Issues & Solutions

---

## 🔴 Critical Issues

### Issue: "Database connection failed"

**Symptoms:**
- White page or error message on every page
- `PDOException: could not find driver`

**Solutions:**

1. **Check PHP has MySQL extension:**
   ```bash
   php -i | grep -i pdo
   # Should show: PDO support => enabled
   ```

2. **Verify database credentials in config.php:**
   ```php
   // config.php should have:
   'db' => [
       'host' => 'localhost',
       'name' => 'sirus_crm_db',
       'user' => 'sirus_user',
       'pass' => 'your_password'
   ]
   ```

3. **Test connection manually:**
   ```bash
   mysql -h localhost -u sirus_user -p sirus_crm_db -e "SELECT 1;"
   # If fails: Check password or user permissions
   ```

4. **Check MySQL is running:**
   ```bash
   # On hosting (cPanel)
   # Go to cPanel → MySQL Databases
   # Verify database and user are listed
   
   # On local
   sudo systemctl status mysql  # Linux
   # or check XAMPP/MAMP control panel
   ```

5. **Verify database user has proper permissions:**
   ```bash
   mysql -u root -p
   SHOW GRANTS FOR 'sirus_user'@'localhost';
   # Should show: GRANT ALL PRIVILEGES ON sirus_crm_db.*
   ```

---

### Issue: "Permission denied" or "Cannot write file"

**Symptoms:**
- Cannot upload documents
- Cannot create reports/exports
- Error: `Failed to open stream`

**Solutions:**

```bash
# SSH into hosting
ssh username@yourhost.com
cd public_html/crm

# Check current permissions
ls -la

# Fix permissions
chmod 755 .
chmod 755 api/
chmod 755 uploads/
chmod 644 *.php
chmod 644 *.html
chmod 644 config.php

# Make sure uploads is writable
chmod 777 uploads/

# Verify
ls -la uploads/
# Should show: drwxrwxrwx (or 777)
```

---

### Issue: "Fatal error: Allowed memory exhausted"

**Symptoms:**
- Large reports fail to generate
- Page stops loading midway
- Error in logs: `Allowed memory size`

**Solutions:**

1. **Increase PHP memory limit (via cPanel):**
   - Go to cPanel → Select PHP Version
   - Find `memory_limit`
   - Change to `512M` or `1024M`
   - Click "Apply"

2. **Or add to .htaccess:**
   ```apache
   php_value memory_limit 512M
   php_value upload_max_filesize 50M
   php_value post_max_size 50M
   ```

3. **Or in code (.php file):**
   ```php
   ini_set('memory_limit', '512M');
   ```

---

## 🟡 Login Issues

### Issue: "Invalid credentials" - Admin can't login

**Symptoms:**
- Always shows "Invalid email or password"
- Other users can login fine

**Solutions:**

1. **Verify admin user exists:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT id, name, email, role FROM users WHERE email='admin@domain.com';"
   ```

2. **Reset admin password:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "
   UPDATE users SET password=PASSWORD('newpassword123') WHERE email='admin@domain.com';
   "
   ```

3. **Check role is correct:**
   ```bash
   # Admin should have role='Admin' (capital A)
   mysql -u sirus_user -p sirus_crm_db -e "SELECT email, role FROM users LIMIT 5;"
   ```

4. **Verify session is working:**
   - Check if `/tmp` directory exists and is writable
   - Check PHP session.save_path in phpinfo()

---

### Issue: "Client can't login" or "OTP not received"

**Symptoms:**
- Client receives "Invalid OTP" error
- Email not delivering OTP
- Client stuck on OTP screen

**Solutions:**

1. **Verify Brevo configuration:**
   - Check API key in config.php
   - Log into Brevo dashboard
   - Verify sender email is confirmed

2. **Check OTP table:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT * FROM client_otp_sessions ORDER BY created_at DESC LIMIT 5;"
   ```

3. **Test email manually:**
   ```php
   <?php
   require 'config.php';
   require 'api/brevo.php';
   
   sendOTP('test@email.com', '123456');
   ?>
   ```

4. **Check client exists in database:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT id, name, email FROM clients WHERE email='client@domain.com';"
   ```

---

## 🟡 Data Issues

### Issue: "Finance dashboard shows 0 or incorrect data"

**Symptoms:**
- Revenue shows ₹0 even though invoices exist
- Expenses not calculating
- Reports blank

**Solutions:**

1. **Check invoices exist and have correct status:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT id, amount, status FROM invoices LIMIT 10;"
   # Status should be 'paid', not 'pending'
   ```

2. **Verify payments table:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT * FROM payments LIMIT 5;"
   ```

3. **Check date filters in query:**
   - Finance dashboard uses current month
   - If no data for current month, no results
   - Test with past months that have data

4. **Verify stored procedure or query:**
   ```bash
   # Check schema matches what code expects
   mysql -u sirus_user -p sirus_crm_db -e "DESCRIBE invoices;"
   # Should have columns: id, amount, status, paid_at, created_at
   ```

---

### Issue: "Client sees 'No data available' on finance page"

**Symptoms:**
- Client finance page empty
- Client portal doesn't show personal data
- Account summary blank

**Solutions:**

1. **Verify client_services records exist:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT * FROM client_services WHERE client_id=1 LIMIT 5;"
   ```

2. **Check invoices for this client:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT * FROM invoices WHERE client_id=1 LIMIT 5;"
   ```

3. **Verify client_id in session:**
   - Add debug code in client-finance.php:
   ```php
   echo "Client ID: " . $_SESSION['client_id'];
   ```

4. **Create test data:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "
   INSERT INTO client_services (client_id, service_id, status, total_amount, created_at)
   VALUES (1, 1, 'completed', 5000, NOW());
   "
   ```

---

## 🟡 Email Issues

### Issue: "Emails not sending" or "Email errors in logs"

**Symptoms:**
- OTP not received
- Finance request notifications not sent
- Brevo API errors in logs

**Solutions:**

1. **Test Brevo connection:**
   ```php
   <?php
   $api_key = 'your_api_key';
   $ch = curl_init('https://api.brevo.com/v3/smtp/email');
   curl_setopt($ch, CURLOPT_HTTPHEADER, ['api-key: ' . $api_key]);
   $response = curl_exec($ch);
   echo $response; // Should return valid JSON
   ?>
   ```

2. **Verify sender email is confirmed in Brevo:**
   - Log into Brevo dashboard
   - Go to Settings → Senders
   - Confirm sender email exists and is verified
   - Check no domain validation issues

3. **Check API key is correct:**
   ```php
   // In config.php
   'brevo' => [
       'api_key' => 'xkeysib-XXXXXXX', // Should start with 'xkeysib-'
   ]
   ```

4. **Review Brevo delivery logs:**
   - Log into Brevo → Transactional
   - Check for bounces or failures
   - Review spam folder

5. **Check firewall isn't blocking API:**
   ```bash
   # Test connection from server
   curl -X GET 'https://api.brevo.com/v3/account'
   # Should return 401 Unauthorized (that's OK, means API is reachable)
   ```

---

## 🟡 Performance Issues

### Issue: "Dashboard loads slowly" or "Queries timing out"

**Symptoms:**
- Pages take 10+ seconds to load
- "Gateway timeout" errors
- Periodic freezing

**Solutions:**

1. **Check database query performance:**
   ```bash
   # Enable slow query log (in MySQL config)
   SET GLOBAL slow_query_log = 'ON';
   SET GLOBAL long_query_time = 2;
   
   # View slow queries
   tail -f /var/log/mysql/slow.log
   ```

2. **Optimize common queries - add indexes:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "
   ALTER TABLE invoices ADD INDEX (client_id);
   ALTER TABLE invoices ADD INDEX (status);
   ALTER TABLE invoices ADD INDEX (created_at);
   ALTER TABLE expenses ADD INDEX (created_at);
   ALTER TABLE client_services ADD INDEX (client_id);
   "
   ```

3. **Limit data in queries:**
   - Add LIMIT to activity feeds
   - Archive old data
   - Use pagination

4. **Increase PHP/MySQL timeouts:**
   ```bash
   # Via .htaccess
   php_value max_execution_time 300
   php_value max_input_time 300
   
   # Via my.cnf (MySQL)
   connect_timeout = 28800
   wait_timeout = 28800
   ```

---

## 🟡 Export/Report Issues

### Issue: "CSV export fails" or "Export button doesn't work"

**Symptoms:**
- Click export button → nothing happens
- Browser shows download attempt but file is empty
- Error in browser console

**Solutions:**

1. **Check export API exists:**
   ```bash
   ls -la public_html/api/export.php
   # File should exist
   ```

2. **Test export endpoint directly:**
   ```
   https://yourdomain.com/crm/api/export.php?action=export_pnl&month=2026-05&format=csv
   ```

3. **Check permissions on export function:**
   ```bash
   # Verify file is readable
   chmod 644 public_html/api/export.php
   ```

4. **Check PHP output buffering:**
   ```php
   // In export.php, ensure no whitespace before headers
   // First line should be: <?php
   // No space before opening tag
   ```

5. **Enable output buffering if headers fail:**
   ```php
   ob_clean();
   header('Content-Type: text/csv');
   header('Content-Disposition: attachment; filename=report.csv');
   echo $csv_data;
   exit;
   ```

---

## 🟡 Security/Access Issues

### Issue: "Permission denied" or "Unauthorized access"

**Symptoms:**
- Pages show "Unauthorized" message
- Admin can't access certain pages
- Client sees admin pages accidentally

**Solutions:**

1. **Verify session variables:**
   ```php
   // Add debug in any page
   var_dump($_SESSION);
   ```

2. **Check session files exist:**
   ```bash
   ls -la /var/lib/php/sessions/
   # Should see session files
   ```

3. **Verify user role in database:**
   ```bash
   mysql -u sirus_user -p sirus_crm_db -e "SELECT email, role FROM users;"
   # Should be 'Admin' or 'Team' or specific roles
   ```

4. **Check session timeout:**
   ```php
   // In config.php
   'auth' => [
       'session_timeout' => 3600, // 1 hour
   ]
   ```

5. **Clear sessions and login again:**
   ```bash
   rm -rf /var/lib/php/sessions/*
   # User should login fresh
   ```

---

## 🔴 Server/Hosting Issues

### Issue: "503 Service Unavailable" or Server Errors

**Symptoms:**
- Whole site down
- "Service Temporarily Unavailable"
- White page with error

**Solutions:**

1. **Check MySQL is running:**
   ```bash
   # cPanel: Go to cPanel → MySQL Databases
   # Or via SSH:
   systemctl status mysql
   
   # If down:
   systemctl restart mysql
   ```

2. **Check Apache/web server:**
   ```bash
   systemctl status apache2
   
   # If down:
   systemctl restart apache2
   ```

3. **Check disk space:**
   ```bash
   df -h
   # If 95%+ full: delete old backups or logs
   ```

4. **Check CPU/Memory:**
   ```bash
   top
   # If very high: Kill heavy processes or upgrade plan
   ```

5. **Check .htaccess for errors:**
   ```bash
   # Try disabling temporarily
   mv .htaccess .htaccess.bak
   # If site works, fix .htaccess syntax
   mv .htaccess.bak .htaccess
   ```

---

## 📋 Log File Locations

**PHP Errors:**
```
/home/username/logs/php_errors.log
or
/var/log/php-fpm/www-error.log
```

**MySQL Errors:**
```
/var/log/mysql/error.log
or
/var/log/mysql.log
```

**Apache Errors:**
```
/var/log/apache2/error.log
```

**Check logs:**
```bash
# View last 20 lines
tail -20 /home/username/logs/php_errors.log

# View live (follow mode)
tail -f /home/username/logs/php_errors.log

# Search for errors
grep -i "error" /home/username/logs/php_errors.log

# Count errors
wc -l /home/username/logs/php_errors.log
```

---

## 🛠️ Diagnostic Commands

**Check PHP version:**
```bash
php -v
```

**Check PHP modules:**
```bash
php -m | grep -i pdo
php -m | grep -i curl
php -m | grep -i mysql
```

**Check MySQL version:**
```bash
mysql --version
```

**Check file permissions:**
```bash
ls -la public_html/config.php
ls -la public_html/uploads/
```

**Check domain DNS:**
```bash
nslookup yourdomain.com
dig yourdomain.com
```

**Test SSL:**
```bash
openssl s_client -connect yourdomain.com:443
```

---

## 📞 When to Contact Support

Contact your hosting provider if:
- [ ] MySQL server won't start
- [ ] Disk space is full
- [ ] Server CPU/memory critically high
- [ ] Cannot connect to server via SSH/FTP
- [ ] SSL certificate issues
- [ ] Email service down

Contact Brevo/SendGrid support if:
- [ ] Email delivery consistently failing
- [ ] API returning 5xx errors
- [ ] Account flagged for spam

---

## 💡 Prevention Tips

1. **Regular backups:**
   ```bash
   mysqldump -u sirus_user -p sirus_crm_db > backup_$(date +%Y%m%d).sql
   ```

2. **Monitor logs weekly:**
   ```bash
   tail -100 /home/username/logs/php_errors.log
   ```

3. **Check disk space monthly:**
   ```bash
   df -h
   du -sh ~/public_html/crm
   ```

4. **Test functionality:**
   - Login monthly as admin and client
   - Try core features (create invoice, export report)
   - Verify emails are sending

5. **Keep backups of config.php:**
   - Store locally
   - Never commit to git

---

**Last Updated:** May 2, 2026
**Version:** 1.0
**Support:** Check error logs first, then consult this guide
