# Troubleshooting Guide

## Overview

This guide helps diagnose and resolve common issues with the Simpler Mobile App backend API and admin interface.

## Common Issues

### 1. Database Connection Problems

#### Symptoms
- "Database connection failed" errors
- 500 Internal Server Error on all endpoints
- Unable to connect to MySQL

#### Diagnosis
```bash
# Test database connection
php tests/debug.php

# Check MySQL service status
systemctl status mysql

# Test connection manually
mysql -u username -p -h localhost database_name
```

#### Solutions

**Check Configuration:**
```php
// In config/config.php
define('DB_HOST', 'localhost');     // Verify host
define('DB_NAME', 'mobile_app_db'); // Verify database name
define('DB_USER', 'your_username'); // Verify username
define('DB_PASS', 'your_password'); // Verify password
```

**Check Database Permissions:**
```sql
-- Grant proper permissions
GRANT ALL PRIVILEGES ON mobile_app_db.* TO 'your_username'@'localhost';
FLUSH PRIVILEGES;
```

**Check Firewall:**
```bash
# Allow MySQL through firewall
sudo ufw allow 3306
```

### 2. Authentication Issues

#### Symptoms
- "Invalid credentials" for valid users
- Token validation failures
- Unable to log in

#### Diagnosis
```bash
# Test authentication flow
php tests/test-auth-flow.php

# Check user exists in database
mysql -u username -p
USE mobile_app_db;
SELECT * FROM app_users WHERE invoicing_id = '12345';
```

#### Solutions

**Password Hash Issues:**
```php
// Re-hash password if needed
$newHash = password_hash('user_password', PASSWORD_DEFAULT);
// Update in database
```

**Token Issues:**
```php
// Check token generation
$payload = json_encode([
    'user_id' => $userId,
    'invoicing_id' => $invoicingId,
    'issued_at' => time(),
    'expires_at' => time() + 3600
]);

$signature = hash_hmac('sha256', base64_encode($payload), TOKEN_SECRET);
$token = base64_encode($payload) . '.' . base64_encode($signature);
```

**Session Cleanup:**
```sql
-- Clear expired sessions
DELETE FROM app_sessions WHERE expires_at < NOW();
```

### 3. API Response Issues

#### Symptoms
- Malformed JSON responses
- Missing data in responses
- Incorrect HTTP status codes

#### Diagnosis
```bash
# Test API endpoints
curl -X GET "http://localhost/api/v1/ping" -H "Content-Type: application/json"

# Check PHP error logs
tail -f /var/log/php_errors.log

# Test specific endpoint
php tests/test-api-json.php
```

#### Solutions

**Enable Error Reporting (Development only):**
```php
// At the top of index.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
```

**Check Content-Type Headers:**
```php
// Ensure proper headers
header('Content-Type: application/json');
```

**Validate JSON Output:**
```php
$response = json_encode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
    error_log('JSON encoding error: ' . json_last_error_msg());
}
```

### 4. Outage Management Issues

#### Symptoms
- Outages not displaying
- Admin interface not loading
- Cleanup not working

#### Diagnosis
```bash
# Test outage endpoints
curl -X GET "http://localhost/api/v1/outages/all"

# Test outage creation
php tests/test-create-outage.php

# Test auto-cleanup
php tests/test-auto-cleanup.php
```

#### Solutions

**Check Database Schema:**
```sql
-- Verify outages table exists
DESCRIBE outages;

-- Check for resolved_at column
SHOW COLUMNS FROM outages LIKE 'resolved_at';

-- Add column if missing
ALTER TABLE outages ADD COLUMN resolved_at DATETIME NULL;
```

**Fix Admin Interface:**
```javascript
// Check API_BASE_URL in admin interface
const API_BASE_URL = '/api/v1';

// Verify fetch requests
fetch(`${API_BASE_URL}/outages/all`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
```

### 5. Auto-Cleanup Issues

#### Symptoms
- Old outages not being deleted
- Cleanup statistics showing wrong numbers
- Manual cleanup not working

#### Diagnosis
```bash
# Test cleanup functionality
php tests/test-cleanup-simple.php

# Check cleanup stats
curl -X GET "http://localhost/api/v1/outages/cleanup/stats"

# Check for old resolved outages
mysql -u username -p -e "
USE mobile_app_db;
SELECT COUNT(*) as count, MIN(resolved_at) as oldest
FROM outages 
WHERE status = 'resolved' 
AND resolved_at < DATE_SUB(NOW(), INTERVAL 12 HOUR);"
```

#### Solutions

**Fix Missing resolved_at Column:**
```sql
-- Add the column if missing
ALTER TABLE outages ADD COLUMN resolved_at DATETIME NULL AFTER estimated_resolution;
ALTER TABLE outages ADD INDEX idx_resolved_at (resolved_at);

-- Update existing resolved outages
UPDATE outages 
SET resolved_at = updated_at 
WHERE status = 'resolved' AND resolved_at IS NULL;
```

**Manual Cleanup:**
```sql
-- Manually clean up old outages
DELETE FROM outages 
WHERE status = 'resolved' 
AND resolved_at IS NOT NULL 
AND resolved_at < DATE_SUB(NOW(), INTERVAL 12 HOUR);
```

### 6. Performance Issues

#### Symptoms
- Slow API responses
- Database timeouts
- High memory usage

#### Diagnosis
```bash
# Check slow query log
mysql -u root -p -e "SHOW VARIABLES LIKE 'slow_query_log';"

# Monitor memory usage
php tests/debug.php

# Check Apache/Nginx error logs
tail -f /var/log/apache2/error.log
```

#### Solutions

**Database Optimization:**
```sql
-- Check missing indexes
SHOW INDEX FROM outages;

-- Add indexes if missing
CREATE INDEX idx_status ON outages(status);
CREATE INDEX idx_created_at ON outages(created_at);
CREATE INDEX idx_resolved_at ON outages(resolved_at);

-- Optimize tables
OPTIMIZE TABLE outages;
OPTIMIZE TABLE app_users;
OPTIMIZE TABLE app_sessions;
```

**PHP Optimization:**
```php
// Increase memory limit if needed
ini_set('memory_limit', '256M');

// Enable OPcache
; In php.ini
opcache.enable=1
opcache.memory_consumption=128
```

### 7. Apache/Nginx Configuration Issues

#### Symptoms
- 404 errors for API endpoints
- .htaccess not working
- URL rewriting problems

#### Diagnosis
```bash
# Check if mod_rewrite is enabled (Apache)
apache2ctl -M | grep rewrite

# Test .htaccess rules
curl -v "http://localhost/api/v1/ping"

# Check virtual host configuration
cat /etc/apache2/sites-available/000-default.conf
```

#### Solutions

**Apache Configuration:**
```apache
# Enable mod_rewrite
sudo a2enmod rewrite

# Virtual host configuration
<VirtualHost *:80>
    DocumentRoot /var/www/html
    
    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
```

**Fixed .htaccess:**
```apache
RewriteEngine On

# API routes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/v1/(.*)$ api/v1/index.php [QSA,L]

# Admin routes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^admin/api/(.*)$ admin/api/index.php [QSA,L]
```

**Nginx Configuration:**
```nginx
server {
    listen 80;
    root /var/www/html;
    index index.php index.html;

    location /api/v1/ {
        try_files $uri $uri/ /api/v1/index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
```

## Debugging Tools

### 1. Debug Script
Create `debug.php` to test basic functionality:

```php
<?php
// Basic debug script
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "=== Simpler Backend Debug ===\n\n";

// Test configuration
echo "1. Configuration Test:\n";
if (file_exists('config/config.php')) {
    require_once 'config/config.php';
    echo "   ✓ Config file found\n";
    echo "   - DB Host: " . DB_HOST . "\n";
    echo "   - DB Name: " . DB_NAME . "\n";
} else {
    echo "   ✗ Config file missing\n";
}

// Test database connection
echo "\n2. Database Test:\n";
try {
    require_once 'classes/Database.php';
    $db = new Database();
    echo "   ✓ Database connection successful\n";
    
    // Test basic query
    $result = $db->fetchOne("SELECT COUNT(*) as count FROM app_users");
    echo "   - Users count: " . $result['count'] . "\n";
    
} catch (Exception $e) {
    echo "   ✗ Database connection failed: " . $e->getMessage() . "\n";
}

// Test API classes
echo "\n3. Class Loading Test:\n";
$classes = ['Auth', 'CustomerService', 'OutageService'];
foreach ($classes as $class) {
    if (file_exists("classes/{$class}.php")) {
        require_once "classes/{$class}.php";
        echo "   ✓ {$class} class loaded\n";
    } else {
        echo "   ✗ {$class} class missing\n";
    }
}

echo "\n=== Debug Complete ===\n";
?>
```

### 2. API Testing Script
```bash
#!/bin/bash
# api-test.sh - Quick API endpoint testing

BASE_URL="http://localhost/api/v1"

echo "=== API Endpoint Testing ==="

# Test ping endpoint
echo "1. Testing ping endpoint..."
curl -s -o /dev/null -w "%{http_code}" "$BASE_URL/ping"
echo

# Test outages endpoint
echo "2. Testing outages endpoint..."
curl -s -o /dev/null -w "%{http_code}" "$BASE_URL/outages"
echo

# Test auth endpoint
echo "3. Testing auth endpoint..."
curl -s -o /dev/null -w "%{http_code}" -X POST "$BASE_URL/auth/check-customer" \
  -H "Content-Type: application/json" \
  -d '{"invoicing_id":"test","phone":"test"}'
echo

echo "=== Testing Complete ==="
```

### 3. Log Monitoring
```bash
# Monitor all logs
tail -f /var/log/apache2/error.log /var/log/php_errors.log

# Monitor MySQL logs
tail -f /var/log/mysql/error.log

# Monitor application logs
tail -f logs/app.log
```

## Error Codes Reference

### Authentication Errors
- `INVALID_CREDENTIALS` - Wrong invoicing_id or password
- `CUSTOMER_NOT_FOUND` - Customer doesn't exist in system
- `INVALID_TOKEN` - Token expired or malformed
- `TOKEN_EXPIRED` - Token has expired
- `ACCOUNT_LOCKED` - Too many failed login attempts

### System Errors
- `SYSTEM_ERROR` - General server error
- `DATABASE_ERROR` - Database connection or query error
- `VALIDATION_ERROR` - Input validation failed
- `API_ERROR` - External API (Azotel) error
- `PERMISSION_DENIED` - Insufficient permissions

### Outage Errors
- `OUTAGE_NOT_FOUND` - Requested outage doesn't exist
- `INVALID_STATUS` - Invalid outage status provided
- `CLEANUP_ERROR` - Auto-cleanup operation failed

## Performance Monitoring

### Database Performance
```sql
-- Check slow queries
SELECT * FROM mysql.slow_log ORDER BY start_time DESC LIMIT 10;

-- Check table sizes
SELECT 
  table_name AS "Table",
  ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES 
WHERE table_schema = 'mobile_app_db'
ORDER BY (data_length + index_length) DESC;

-- Check index usage
SELECT 
  table_name,
  index_name,
  cardinality
FROM information_schema.statistics 
WHERE table_schema = 'mobile_app_db';
```

### Application Performance
```php
// Add timing to debug performance
$start = microtime(true);

// Your code here

$time = microtime(true) - $start;
error_log("Operation took: " . round($time * 1000, 2) . "ms");
```

## Security Checklist

### Production Security
- [ ] Disable error display (`display_errors = 0`)
- [ ] Enable error logging (`log_errors = 1`)
- [ ] Use HTTPS for all requests
- [ ] Implement rate limiting
- [ ] Validate all inputs
- [ ] Use prepared statements
- [ ] Keep software updated
- [ ] Regular security audits

### Database Security
- [ ] Use strong passwords
- [ ] Limit database user permissions
- [ ] Enable SSL for database connections
- [ ] Regular backups
- [ ] Monitor for suspicious activity

## Getting Help

### Log Files to Check
1. `/var/log/apache2/error.log` - Apache errors
2. `/var/log/php_errors.log` - PHP errors
3. `/var/log/mysql/error.log` - MySQL errors
4. Application logs in `logs/` directory

### Information to Provide
When seeking help, include:
1. Error messages (full stack trace)
2. Steps to reproduce the issue
3. Environment details (PHP version, MySQL version)
4. Recent changes made to the system
5. Log file excerpts

### Testing Commands
```bash
# Quick system check
php -v && mysql --version && apache2 -v

# Test API endpoints
curl -X GET "http://localhost/api/v1/ping"

# Test database connection
php tests/debug.php

# Check file permissions
ls -la config/ classes/ api/
```

This troubleshooting guide should help resolve most common issues with the Simpler Mobile App backend. For persistent issues, enable debug mode and check the detailed error logs for more specific information.
