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

echo "<h1>🔍 Testing Internal Candidate Approval Email Notifications</h1>";

$database = new Database();
$db = $database->getConnection();

// Get a sample internal candidate
$stmt = $db->prepare("
    SELECT id, first_name, last_name, email, hr_approval_status, company_id 
    FROM candidates 
    WHERE candidate_type = 'internal' 
    LIMIT 1
");
$stmt->execute();
$candidate = $stmt->fetch();

if (!$candidate) {
    echo "<div style='color: red;'>❌ No internal candidates found in database</div>";
    exit;
}

echo "<h2>📋 Test Candidate Information</h2>";
echo "<table border='1' style='border-collapse: collapse;'>";
echo "<tr><th>Field</th><th>Value</th></tr>";
echo "<tr><td>ID</td><td>{$candidate['id']}</td></tr>";
echo "<tr><td>Name</td><td>{$candidate['first_name']} {$candidate['last_name']}</td></tr>";
echo "<tr><td>Email</td><td>{$candidate['email']}</td></tr>";
echo "<tr><td>Current Status</td><td>{$candidate['hr_approval_status']}</td></tr>";
echo "<tr><td>Company ID</td><td>{$candidate['company_id']}</td></tr>";
echo "</table>";

// Test Gmail service initialization
echo "<h2>📧 Testing Gmail Service</h2>";
try {
    require_once 'includes/gmail_email_service.php';
    $gmailService = new GmailEmailService($db);
    echo "<div style='color: green;'>✅ Gmail service initialized successfully</div>";
    
    // Test sending approval email
    echo "<h3>Testing Approval Email</h3>";
    $email_message = "Dear {$candidate['first_name']},\n\nYour internal account has been approved!\n\nBest regards,\nHR Team";
    
    $result = $gmailService->sendApprovalNotificationEmail($candidate, $email_message, 'approve');
    
    if ($result) {
        echo "<div style='color: green; background: #d4edda; padding: 10px; border-radius: 5px;'>";
        echo "✅ <strong>Approval email sent successfully!</strong><br>";
        echo "📧 Sent to: {$candidate['email']}<br>";
        echo "📅 Time: " . date('Y-m-d H:i:s') . "<br>";
        echo "</div>";
    } else {
        echo "<div style='color: red; background: #f8d7da; padding: 10px; border-radius: 5px;'>";
        echo "❌ <strong>Failed to send approval email</strong><br>";
        echo "📧 Target: {$candidate['email']}<br>";
        echo "Check error logs for details";
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<div style='color: red;'>❌ Gmail service error: " . $e->getMessage() . "</div>";
}

// Test notification creation
echo "<h2>🔔 Testing In-App Notification</h2>";
try {
    $notification_stmt = $db->prepare("
        INSERT INTO notifications (user_id, user_type, title, message, type, created_at) 
        VALUES (?, 'candidate', ?, ?, ?, NOW())
    ");
    
    $title = 'Test Account Approval';
    $message = 'Your internal employee account has been approved for testing purposes.';
    $type = 'success';
    
    $notification_result = $notification_stmt->execute([$candidate['id'], $title, $message, $type]);
    
    if ($notification_result) {
        echo "<div style='color: green;'>✅ In-app notification created successfully</div>";
    } else {
        echo "<div style='color: red;'>❌ Failed to create in-app notification</div>";
    }
    
} catch (Exception $e) {
    echo "<div style='color: red;'>❌ Notification error: " . $e->getMessage() . "</div>";
}

// Check recent email logs
echo "<h2>📋 Recent Email Activity (Last 10 entries)</h2>";
$email_stmt = $db->prepare("
    SELECT recipient_email, subject, status, created_at 
    FROM email_logs 
    ORDER BY created_at DESC 
    LIMIT 10
");
$email_stmt->execute();
$email_logs = $email_stmt->fetchAll();

if ($email_logs) {
    echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
    echo "<tr style='background: #f8f9fa;'><th>Recipient</th><th>Subject</th><th>Status</th><th>Time</th></tr>";
    foreach ($email_logs as $log) {
        $status_color = $log['status'] === 'sent' ? '#28a745' : '#dc3545';
        echo "<tr>";
        echo "<td>{$log['recipient_email']}</td>";
        echo "<td>" . substr($log['subject'], 0, 50) . "...</td>";
        echo "<td style='color: {$status_color}; font-weight: bold;'>" . strtoupper($log['status']) . "</td>";
        echo "<td>{$log['created_at']}</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "<div style='color: orange;'>⚠️ No email logs found</div>";
}

echo "<h2>🔧 Troubleshooting Tips</h2>";
echo "<ul>";
echo "<li><strong>If emails aren't being sent:</strong> Check SMTP configuration in gmail_email_service.php</li>";
echo "<li><strong>If notifications aren't created:</strong> Check database permissions and table structure</li>";
echo "<li><strong>If approval process doesn't trigger:</strong> Check internal-employees.php and internal-candidates.php</li>";
echo "<li><strong>Check error logs in:</strong> recruit/error_log, recruit/company/error_log, recruit/admin/error_log</li>";
echo "</ul>";

echo "<style>
body { font-family: Arial, sans-serif; margin: 20px; }
table { margin: 10px 0; }
th, td { padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
h1, h2, h3 { color: #333; }
</style>";
?>