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

echo "<h1>🔐 Testing Internal Candidate Approval Notifications</h1>\n";

try {
    $database = new Database();
    $db = $database->getConnection();
    
    echo "<h2>1. Current Internal Candidates</h2>\n";
    
    // Get internal candidates
    $stmt = $db->prepare("
        SELECT id, first_name, last_name, email, hr_approval_status, employee_code
        FROM candidates 
        WHERE candidate_type = 'internal' 
        ORDER BY id DESC
        LIMIT 5
    ");
    $stmt->execute();
    $candidates = $stmt->fetchAll();
    
    if (empty($candidates)) {
        echo "<p style='color: #dc3545;'>❌ No internal candidates found for testing.</p>\n";
        exit;
    }
    
    echo "<table border='1' cellpadding='8' cellspacing='0' style='border-collapse: collapse; width: 100%;'>\n";
    echo "<tr style='background: #f8f9fa;'>\n";
    echo "<th>ID</th><th>Name</th><th>Email</th><th>Status</th><th>Employee Code</th>\n";
    echo "</tr>\n";
    
    foreach ($candidates as $candidate) {
        $statusColor = [
            'pending' => '#ffc107',
            'approved' => '#28a745', 
            'rejected' => '#dc3545'
        ][$candidate['hr_approval_status']] ?? '#6c757d';
        
        echo "<tr>\n";
        echo "<td>{$candidate['id']}</td>\n";
        echo "<td>" . htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']) . "</td>\n";
        echo "<td>" . htmlspecialchars($candidate['email']) . "</td>\n";
        echo "<td style='color: $statusColor; font-weight: bold;'>" . strtoupper($candidate['hr_approval_status']) . "</td>\n";
        echo "<td>" . htmlspecialchars($candidate['employee_code']) . "</td>\n";
        echo "</tr>\n";
    }
    echo "</table>\n";
    
    echo "<h2>2. Testing Gmail Service</h2>\n";
    
    require_once 'includes/gmail_email_service.php';
    $gmailService = new GmailEmailService($db);
    
    // Test with first candidate
    $testCandidate = $candidates[0];
    
    echo "<h3>Testing Approval Email</h3>\n";
    echo "<p><strong>Test Candidate:</strong> {$testCandidate['first_name']} {$testCandidate['last_name']} ({$testCandidate['email']})</p>\n";
    
    $mockCandidateData = [
        'first_name' => $testCandidate['first_name'],
        'last_name' => $testCandidate['last_name'], 
        'email' => 'masandendyaluvane@gmail.com' // Send to test email
    ];
    
    // Test approval notification
    $approvalMessage = "Dear {$testCandidate['first_name']},\n\n";
    $approvalMessage .= "Great news! Your internal candidate account has been approved by HR.\n\n";
    $approvalMessage .= "You can now:\n";
    $approvalMessage .= "• Log in to your account\n";
    $approvalMessage .= "• Browse and apply for internal job postings\n";
    $approvalMessage .= "• Update your profile and CV\n\n";
    $approvalMessage .= "Welcome to our internal recruitment portal!\n\n";
    $approvalMessage .= "Best regards,\nHR Team";
    
    echo "<p>Sending approval notification to masandendyaluvane@gmail.com...</p>\n";
    
    $approvalResult = $gmailService->sendApprovalNotificationEmail($mockCandidateData, $approvalMessage, 'approve');
    
    if ($approvalResult) {
        echo "<div style='background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin: 15px 0;'>\n";
        echo "<h4>✅ Approval Email Test Successful!</h4>\n";
        echo "<p>Gmail notification sent successfully with beautiful HTML formatting.</p>\n";
        echo "<p><strong>Subject:</strong> 🎉 Internal Account Approved - Welcome to the Recruitment Portal!</p>\n";
        echo "</div>\n";
    } else {
        echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin: 15px 0;'>\n";
        echo "<h4>❌ Approval Email Test Failed</h4>\n";
        echo "<p>There was an issue sending the approval notification.</p>\n";
        echo "</div>\n";
    }
    
    echo "<h3>Testing Rejection Email</h3>\n";
    
    $rejectionMessage = "Dear {$testCandidate['first_name']},\n\n";
    $rejectionMessage .= "We have reviewed your internal candidate account application.\n\n";
    $rejectionMessage .= "Unfortunately, we need additional information or there are requirements that need to be addressed before approval.\n\n";
    $rejectionMessage .= "Additional details: Missing required documentation and employee verification.\n\n";
    $rejectionMessage .= "Please contact HR for more information on next steps.\n\n";
    $rejectionMessage .= "Best regards,\nHR Team";
    
    echo "<p>Sending rejection notification to masandendyaluvane@gmail.com...</p>\n";
    
    $rejectionResult = $gmailService->sendApprovalNotificationEmail($mockCandidateData, $rejectionMessage, 'reject');
    
    if ($rejectionResult) {
        echo "<div style='background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin: 15px 0;'>\n";
        echo "<h4>✅ Rejection Email Test Successful!</h4>\n";
        echo "<p>Gmail notification sent successfully with proper formatting.</p>\n";
        echo "<p><strong>Subject:</strong> ⚠️ Internal Account Application - Update Required</p>\n";
        echo "</div>\n";
    } else {
        echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin: 15px 0;'>\n";
        echo "<h4>❌ Rejection Email Test Failed</h4>\n";
        echo "<p>There was an issue sending the rejection notification.</p>\n";
        echo "</div>\n";
    }
    
    echo "<h2>3. Recent Email Activity</h2>\n";
    
    // Show recent email logs
    $stmt = $db->prepare("SELECT * FROM email_notifications ORDER BY created_at DESC LIMIT 5");
    $stmt->execute();
    $logs = $stmt->fetchAll();
    
    if ($logs) {
        echo "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse; width: 100%;'>\n";
        echo "<tr style='background: #f8f9fa;'><th>To</th><th>Subject</th><th>Status</th><th>Time</th></tr>\n";
        foreach ($logs as $log) {
            $statusColor = $log['status'] === 'sent' ? '#28a745' : ($log['status'] === 'failed' ? '#dc3545' : '#ffc107');
            echo "<tr>";
            echo "<td>" . htmlspecialchars($log['to_email']) . "</td>";
            echo "<td>" . htmlspecialchars(substr($log['subject'], 0, 50)) . "...</td>";
            echo "<td style='color: $statusColor; font-weight: bold;'>" . strtoupper($log['status']) . "</td>";
            echo "<td>" . $log['created_at'] . "</td>";
            echo "</tr>\n";
        }
        echo "</table>\n";
    }
    
    if ($approvalResult && $rejectionResult) {
        echo "<h2>🎯 TEST SUMMARY</h2>\n";
        echo "<div style='background: linear-gradient(135deg, #28a745 0%, #20c997 100%); color: white; padding: 25px; border-radius: 10px; text-align: center;'>\n";
        echo "<h3>🎉 All Tests Passed!</h3>\n";
        echo "<p style='font-size: 18px; margin: 15px 0;'>Approval email notifications are working perfectly!</p>\n";
        echo "<p><strong>What this means:</strong></p>\n";
        echo "<ul style='text-align: left; display: inline-block;'>>\n";
        echo "<li>✅ Internal candidates get email notifications when approved</li>\n";
        echo "<li>✅ Beautiful HTML email templates with professional formatting</li>\n";
        echo "<li>✅ Different emails for approvals vs rejections</li>\n";
        echo "<li>✅ Gmail SMTP integration working correctly</li>\n";
        echo "<li>✅ Complete integration with admin approval workflow</li>\n";
        echo "</ul>\n";
        echo "<p style='font-size: 16px; margin-top: 20px;'><strong>Ready for production use!</strong></p>\n";
        echo "</div>\n";
        
        echo "<h3>📧 How It Works</h3>\n";
        echo "<ol>\n";
        echo "<li>Admin goes to Internal Candidates page</li>\n";
        echo "<li>Clicks Approve or Reject for pending candidates</li>\n";
        echo "<li>System creates in-app notification</li>\n";
        echo "<li>System sends beautiful Gmail notification to candidate</li>\n";
        echo "<li>Candidate receives professional email with next steps</li>\n";
        echo "</ol>\n";
    }
    
} catch (Exception $e) {
    echo "<div style='background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px;'>\n";
    echo "<h3>❌ Test Error</h3>\n";
    echo "<p>" . htmlspecialchars($e->getMessage()) . "</p>\n";
    echo "</div>\n";
}

// Auto-cleanup after showing results
echo "<script>\n";
echo "setTimeout(function() {\n";
echo "    if (confirm('Approval email tests complete! Clean up test file?')) {\n";
echo "        fetch('?cleanup=1').then(() => {\n";
echo "            document.body.innerHTML = '<h2>✅ Tests completed and cleaned up!</h2><p>Approval email notifications are working correctly.</p>';\n";
echo "        });\n";
echo "    }\n";
echo "}, 8000);\n";
echo "</script>\n";

if (isset($_GET['cleanup'])) {
    unlink(__FILE__);
    exit('Test file cleaned up successfully');
}

echo "<style>\n";
echo "body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif; margin: 20px; line-height: 1.6; color: #333; }\n";
echo "h1, h2, h3 { color: #2c3e50; }\n";
echo "table { border-collapse: collapse; width: 100%; margin: 15px 0; }\n";
echo "th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }\n";
echo "th { background-color: #f2f2f2; }\n";
echo "ul { padding-left: 20px; }\n";
echo "</style>\n";
?>