<?php
/**
 * Email Diagnostic Script
 * File: check-email-setup.php (ROOT)
 * Run this to diagnose email issues
 */

require_once 'app/Core/init.php';

echo "<h2>Email Configuration Check</h2>";
echo "<pre>";

// 1. Check email constants
echo "=== EMAIL CONFIGURATION ===\n";
echo "MAIL_HOST: " . (defined('MAIL_HOST') ? MAIL_HOST : 'NOT DEFINED') . "\n";
echo "MAIL_PORT: " . (defined('MAIL_PORT') ? MAIL_PORT : 'NOT DEFINED') . "\n";
echo "MAIL_USERNAME: " . (defined('MAIL_USERNAME') ? MAIL_USERNAME : 'NOT DEFINED') . "\n";
echo "MAIL_PASSWORD: " . (defined('MAIL_PASSWORD') ? (MAIL_PASSWORD ? '***SET***' : 'EMPTY') : 'NOT DEFINED') . "\n";
echo "MAIL_FROM_EMAIL: " . (defined('MAIL_FROM_EMAIL') ? MAIL_FROM_EMAIL : 'NOT DEFINED') . "\n";
echo "MAIL_FROM_NAME: " . (defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : 'NOT DEFINED') . "\n\n";

// 2. Check email templates
echo "=== EMAIL TEMPLATES ===\n";
$template_dir = ROOT_PATH . "/templates/email";
echo "Template directory: {$template_dir}\n";
echo "Directory exists: " . (is_dir($template_dir) ? 'YES' : 'NO') . "\n\n";

if (is_dir($template_dir)) {
    echo "Required templates:\n";
    $required_templates = [
        'order-confirmation.php',
        'order-notification-vendor.php'
    ];
    
    foreach ($required_templates as $template) {
        $path = $template_dir . '/' . $template;
        echo "  - {$template}: " . (file_exists($path) ? '✓ EXISTS' : '✗ MISSING') . "\n";
    }
    echo "\n";
    
    echo "All templates in directory:\n";
    $files = scandir($template_dir);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            echo "  - {$file}\n";
        }
    }
} else {
    echo "⚠️  Templates directory does not exist!\n";
    echo "Create it at: {$template_dir}\n";
}

echo "\n=== MAILER CLASS ===\n";
echo "Mailer class exists: " . (class_exists('Mailer') ? 'YES' : 'NO') . "\n";

if (class_exists('Mailer')) {
    $mailer = new Mailer();
    echo "Mailer instantiated: YES\n";
    
    echo "\nAvailable methods:\n";
    $methods = get_class_methods($mailer);
    foreach ($methods as $method) {
        if (strpos($method, 'send') !== false) {
            echo "  - {$method}\n";
        }
    }
}

// 3. Test order data fetch
echo "\n=== DATABASE CHECK ===\n";
try {
    $db = Database::getInstance();
    echo "Database connection: ✓ OK\n";
    
    $sql = "SELECT o.id, o.order_number, 
            CONCAT(c.first_name, ' ', c.last_name) as customer_name,
            u_c.email as customer_email,
            v.business_name as vendor_name,
            u_v.email as vendor_email
            FROM orders o
            JOIN customers c ON o.customer_id = c.id
            JOIN users u_c ON c.user_id = u_c.id
            JOIN vendors v ON o.vendor_id = v.id
            JOIN users u_v ON v.user_id = u_v.id
            ORDER BY o.id DESC LIMIT 1";
    
    $order = $db->fetch($sql);
    
    if ($order) {
        echo "Latest order found: ✓ YES\n";
        echo "  Order #: {$order['order_number']}\n";
        echo "  Customer: {$order['customer_name']} ({$order['customer_email']})\n";
        echo "  Vendor: {$order['vendor_name']} ({$order['vendor_email']})\n";
    } else {
        echo "No orders found in database\n";
    }
} catch (Exception $e) {
    echo "Database error: " . $e->getMessage() . "\n";
}

// 4. Test email sending
echo "\n=== EMAIL TEST ===\n";
echo "To test email sending, uncomment the code below and set a test email:\n";
echo "/*\n";
echo "\$test_email = 'adsegzy@gmail.com';\n";
echo "\$mailer = new Mailer();\n";
echo "\$result = \$mailer->sendTestEmail(\$test_email);\n";
echo "echo 'Test email sent: ' . (\$result ? 'SUCCESS' : 'FAILED') . \"\\n\";\n";
echo "*/\n";

echo "\n=== RECOMMENDATIONS ===\n";

$issues = [];

if (!defined('MAIL_HOST') || empty(MAIL_HOST)) {
    $issues[] = "Set MAIL_HOST in your config file";
}

if (!is_dir($template_dir)) {
    $issues[] = "Create email templates directory: {$template_dir}";
}

if (is_dir($template_dir)) {
    if (!file_exists($template_dir . '/order-confirmation.php')) {
        $issues[] = "Create order-confirmation.php template";
    }
    if (!file_exists($template_dir . '/order-notification-vendor.php')) {
        $issues[] = "Create order-notification-vendor.php template";
    }
}

if (empty($issues)) {
    echo "✓ No issues found! Email system should work.\n";
    echo "\nIf emails still don't send:\n";
    echo "1. Check spam folder\n";
    echo "2. Verify SMTP credentials are correct\n";
    echo "3. Check server error logs: tail -f /var/log/apache2/error.log\n";
    echo "4. Test with: \$mailer->sendTestEmail('your-email@example.com')\n";
} else {
    echo "⚠️  Issues found:\n";
    foreach ($issues as $i => $issue) {
        echo ($i + 1) . ". {$issue}\n";
    }
}

echo "</pre>";
