<?php
require_once 'config/config.php';

echo "<h2>📧 Email System Test</h2>\n";

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if email_notifications table exists
    echo "<h3>1. Checking Email Notifications Table</h3>\n";
    try {
        $stmt = $db->query("DESCRIBE email_notifications");
        $columns = $stmt->fetchAll();
        echo "<p>✅ email_notifications table exists</p>\n";
        
        echo "<table border='1' cellpadding='5'>\n";
        echo "<tr><th>Column</th><th>Type</th></tr>\n";
        foreach ($columns as $col) {
            echo "<tr><td>{$col['Field']}</td><td>{$col['Type']}</td></tr>\n";
        }
        echo "</table>\n";
        
        // Check recent email logs
        $stmt = $db->query("SELECT * FROM email_notifications ORDER BY created_at DESC LIMIT 10");
        $emails = $stmt->fetchAll();
        
        echo "<h4>Recent Email Logs:</h4>\n";
        if ($emails) {
            echo "<table border='1' cellpadding='5'>\n";
            echo "<tr><th>ID</th><th>To</th><th>Subject</th><th>Status</th><th>Created</th></tr>\n";
            foreach ($emails as $email) {
                echo "<tr>";
                echo "<td>{$email['id']}</td>";
                echo "<td>{$email['to_email']}</td>";
                echo "<td>" . substr($email['subject'], 0, 50) . "...</td>";
                echo "<td>{$email['status']}</td>";
                echo "<td>{$email['created_at']}</td>";
                echo "</tr>\n";
            }
            echo "</table>\n";
        } else {
            echo "<p>No email logs found.</p>\n";
        }
        
    } catch (Exception $e) {
        echo "<p>❌ email_notifications table doesn't exist or has issues: " . $e->getMessage() . "</p>\n";
    }
    
    // Test Gmail service initialization
    echo "<h3>2. Testing Gmail Service</h3>\n";
    try {
        require_once 'includes/gmail_email_service.php';
        $gmailService = new GmailEmailService($db);
        echo "<p>✅ Gmail service initialized successfully</p>\n";
        
        // Test connection
        echo "<p>Testing Gmail SMTP connection...</p>\n";
        $test_result = $gmailService->testConnection('masandendyaluvane@gmail.com');
        
        if ($test_result) {
            echo "<div style='background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
            echo "<h4>✅ EMAIL TEST SUCCESSFUL!</h4>\n";
            echo "<p>Gmail SMTP is working correctly. Test email sent to masandendyaluvane@gmail.com</p>\n";
            echo "</div>\n";
        } else {
            echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
            echo "<h4>❌ EMAIL TEST FAILED!</h4>\n";
            echo "<p>Gmail SMTP is not working. Check configuration and logs.</p>\n";
            echo "</div>\n";
        }
        
    } catch (Exception $e) {
        echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
        echo "<h4>❌ Gmail Service Error!</h4>\n";
        echo "<p>Error: " . $e->getMessage() . "</p>\n";
        echo "</div>\n";
    }
    
    // Test approval email specifically
    echo "<h3>3. Testing Approval Email</h3>\n";
    if (isset($gmailService)) {
        $test_candidate = [
            'first_name' => 'Test',
            'last_name' => 'User', 
            'email' => 'masandendyaluvane@gmail.com' // Send to same email for testing
        ];
        
        $test_message = "Dear Test User,\n\nGreat news! Your internal employee account has been approved.\n\nYou can now:\n• Log in to your account\n• Browse and apply for internal job postings\n• Update your profile and CV\n\nWelcome to our internal recruitment portal!\n\nBest regards,\nHR Team";
        
        echo "<p>Sending test approval email...</p>\n";
        $approval_result = $gmailService->sendApprovalNotificationEmail($test_candidate, $test_message, 'approve');
        
        if ($approval_result) {
            echo "<div style='background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
            echo "<h4>✅ APPROVAL EMAIL TEST SUCCESSFUL!</h4>\n";
            echo "<p>Approval notification email sent successfully to masandendyaluvane@gmail.com</p>\n";
            echo "</div>\n";
        } else {
            echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
            echo "<h4>❌ APPROVAL EMAIL TEST FAILED!</h4>\n";
            echo "<p>Approval notification email failed to send.</p>\n";
            echo "</div>\n";
        }
    }
    
    // Check PHP error log
    echo "<h3>4. Checking PHP Error Logs</h3>\n";
    $error_log_file = ini_get('error_log');
    echo "<p><strong>PHP Error Log Location:</strong> $error_log_file</p>\n";
    
    if ($error_log_file && file_exists($error_log_file)) {
        $recent_errors = shell_exec("tail -20 \"$error_log_file\"");
        if ($recent_errors) {
            echo "<h4>Recent PHP Errors (last 20 lines):</h4>\n";
            echo "<pre style='background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto;'>";
            echo htmlspecialchars($recent_errors);
            echo "</pre>\n";
        }
    } else {
        echo "<p>Error log file not found or not accessible.</p>\n";
    }
    
} catch (Exception $e) {
    echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
    echo "<h4>❌ Fatal Error!</h4>\n";
    echo "<p>Error: " . $e->getMessage() . "</p>\n";
    echo "</div>\n";
}

?>

<style>
body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
table { width: 100%; margin: 20px 0; border-collapse: collapse; }
th, td { padding: 10px; text-align: left; border: 1px solid #ddd; }
th { background-color: #f2f2f2; }
h1, h2, h3 { color: #333; }
pre { font-size: 12px; }
</style>