<?php
// Diagnostic — delete after use
// Captures the actual PHP error if any of the email handler code blows up.

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

header('Content-Type: text/plain');

echo "=== Step 1: Load config ===\n";
require __DIR__ . '/includes/config.php';
echo "Config loaded OK\n";
echo "EMAIL_ENCRYPTION_KEY defined: " . (defined('EMAIL_ENCRYPTION_KEY') ? 'YES' : 'NO') . "\n";
if (defined('EMAIL_ENCRYPTION_KEY')) {
    echo "Key length (hex): " . strlen(EMAIL_ENCRYPTION_KEY) . " (expect 64)\n";
}
echo "\n";

echo "=== Step 2: Load email_crypto ===\n";
require __DIR__ . '/includes/email_crypto.php';
echo "Loaded OK\n";

try {
    $enc = email_encrypt('test-password-123');
    $dec = email_decrypt($enc);
    echo "Encrypt/decrypt roundtrip: " . ($dec === 'test-password-123' ? 'OK' : 'BROKEN') . "\n";
} catch (Throwable $e) {
    echo "CRYPTO ERROR: " . $e->getMessage() . "\n";
}
echo "\n";

echo "=== Step 3: Load imap_client ===\n";
try {
    require __DIR__ . '/includes/imap_client.php';
    echo "Loaded OK\n";
    echo "imc_ext_loaded(): " . (imc_ext_loaded() ? 'YES' : 'NO') . "\n";
} catch (Throwable $e) {
    echo "LOAD ERROR: " . $e->getMessage() . "\n";
    exit;
}
echo "\n";

echo "=== Step 4: Test IMAP open against a non-existent host (should fail gracefully) ===\n";
try {
    $fake_acct = [
        'imap_host'       => 'doesnotexist.example.com',
        'imap_port'       => 993,
        'imap_encryption' => 'ssl',
        'imap_username'   => 'test',
        'imap_password'   => email_encrypt('test'),
    ];
    $result = imc_test_imap($fake_acct);
    echo "Test returned: " . ($result['ok'] ? 'OK' : 'failed') . "\n";
    echo "Message: " . $result['message'] . "\n";
} catch (Throwable $e) {
    echo "UNCAUGHT FATAL: " . $e->getMessage() . "\n";
    echo "Trace:\n" . $e->getTraceAsString() . "\n";
}
echo "\n";

echo "=== All steps completed ===\n";
echo "If you see this line, the include chain works.\n";
echo "Delete this file now.\n";