#!/bin/bash
# Email System Diagnostic

echo "=================================="
echo "🔍 Email System Diagnostic"
echo "=================================="
echo ""

# Check if MAMP/PHP is running
echo "1. Checking PHP/MAMP Status..."
if pgrep -x "httpd" > /dev/null; then
    echo "   ✅ Apache is running"
else
    echo "   ❌ Apache is NOT running - Start MAMP first!"
    exit 1
fi

echo ""
echo "2. Checking Email Configuration..."
grep -n "EMAIL_METHOD\|SMTP_HOST\|SMTP_PORT\|SMTP_USERNAME" /Applications/MAMP/htdocs/slipstream/email_config.php | head -5

echo ""
echo "3. Database Connection Test..."
# Create a simple test script
cat > /tmp/test_db.php << 'EOF'
<?php
require_once '/Applications/MAMP/htdocs/slipstream/config.php';
try {
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM airport_notification_emails");
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "   ✅ Database connection OK\n";
    echo "   📊 Total notification email records: " . $result['count'] . "\n";
    
    if ($result['count'] > 0) {
        $stmt = $pdo->query("SELECT airport_code, COUNT(*) as count FROM airport_notification_emails GROUP BY airport_code");
        $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($records as $row) {
            echo "      - " . $row['airport_code'] . ": " . $row['count'] . " recipients\n";
        }
    } else {
        echo "   ❌ NO EMAIL RECIPIENTS CONFIGURED!\n";
        echo "      Go to Admin Dashboard → Airport Email Recipients → Add emails\n";
    }
} catch (Exception $e) {
    echo "   ❌ Database error: " . $e->getMessage() . "\n";
}
?>
EOF

/Applications/MAMP/bin/php/php8.3.14/bin/php /tmp/test_db.php

echo ""
echo "4. Checking Recent Errors..."
tail -10 /Applications/MAMP/htdocs/slipstream/logs/api.log | grep -i "error\|fail" || echo "   ✅ No recent errors found"

echo ""
echo "5. Email Sending Function..."
echo "   Method: SMTP (configured)"
echo "   Host: ssl0.ovh.net:587"
echo "   From: contact@captaindecision.com"

echo ""
echo "=================================="
echo "✅ Diagnostic Complete"
echo "=================================="
