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

// Comprehensive test for new job notifications
$database = new Database();
$db = $database->getConnection();

echo "<h2>Comprehensive New Job Notification Test</h2>\n";

try {
    // Let's create a test scenario by finding categories with candidates
    echo "<h3>1. Finding Best Test Category</h3>\n";
    
    $stmt = $db->prepare("
        SELECT cat.id, cat.name, COUNT(DISTINCT c.id) as candidate_count,
               GROUP_CONCAT(DISTINCT CONCAT(c.first_name, ' ', c.last_name) SEPARATOR ', ') as candidates
        FROM job_categories cat
        INNER JOIN jobs j ON cat.id = j.category_id
        INNER JOIN job_applications ja ON j.id = ja.job_id
        INNER JOIN candidates c ON ja.candidate_id = c.id
        WHERE c.email IS NOT NULL AND c.email != ''
        GROUP BY cat.id, cat.name
        ORDER BY candidate_count DESC
        LIMIT 1
    ");
    $stmt->execute();
    $best_category = $stmt->fetch();
    
    if (!$best_category) {
        echo "❌ No categories with candidate applications found<br>\n";
        exit;
    }
    
    echo "🎯 Best test category: <strong>{$best_category['name']}</strong> with {$best_category['candidate_count']} candidates<br>\n";
    echo "Candidates: {$best_category['candidates']}<br>\n";
    
    // Create a test job in this category
    echo "<h3>2. Creating Test Job</h3>\n";
    
    // First, let's get a company ID
    $stmt = $db->prepare("SELECT id, name FROM companies WHERE status = 'approved' LIMIT 1");
    $stmt->execute();
    $test_company = $stmt->fetch();
    
    if (!$test_company) {
        echo "❌ No approved companies found<br>\n";
        exit;
    }
    
    // Get a company user
    $stmt = $db->prepare("SELECT id FROM company_users WHERE company_id = ? LIMIT 1");
    $stmt->execute([$test_company['id']]);
    $company_user = $stmt->fetch();
    
    if (!$company_user) {
        echo "❌ No company users found<br>\n";
        exit;
    }
    
    // Create a test job
    $test_job_title = "Test Job for Notifications - " . date('Y-m-d H:i:s');
    $stmt = $db->prepare("
        INSERT INTO jobs (
            company_id, company_user_id, category_id, title, description, location, 
            employment_type, experience_level, status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())
    ");
    
    $stmt->execute([
        $test_company['id'],
        $company_user['id'],
        $best_category['id'],
        $test_job_title,
        "This is a test job posting to verify our notification system works correctly. Candidates who have previously applied to jobs in the {$best_category['name']} category should receive notifications about this opportunity.",
        "Test Location",
        "full-time",
        "mid",
    ]);
    
    $test_job_id = $db->lastInsertId();
    echo "✅ Created test job: <strong>$test_job_title</strong> (ID: $test_job_id)<br>\n";
    
    // Now test the notification system
    echo "<h3>3. Testing Notification System</h3>\n";
    
    require_once 'includes/notification_system.php';
    $notification_system = new NotificationSystem($db);
    
    // Check eligible candidates before sending
    $stmt = $db->prepare("
        SELECT DISTINCT c.id, c.email, c.first_name, c.last_name
        FROM candidates c
        INNER JOIN job_applications ja ON c.id = ja.candidate_id
        INNER JOIN jobs prev_jobs ON ja.job_id = prev_jobs.id
        WHERE prev_jobs.category_id = ?
        AND c.id NOT IN (
            SELECT candidate_id 
            FROM job_applications 
            WHERE job_id = ?
        )
        AND c.email IS NOT NULL
        AND c.email != ''
    ");
    $stmt->execute([$best_category['id'], $test_job_id]);
    $eligible_candidates = $stmt->fetchAll();
    
    echo "📧 Found " . count($eligible_candidates) . " eligible candidates:<br>\n";
    foreach ($eligible_candidates as $candidate) {
        echo "- {$candidate['first_name']} {$candidate['last_name']} ({$candidate['email']})<br>\n";
    }
    
    if (empty($eligible_candidates)) {
        echo "⚠️ No eligible candidates found. This might mean all candidates in this category have already applied to recent jobs.<br>\n";
    }
    
    // Run the notification system
    echo "<h3>4. Sending Notifications</h3>\n";
    
    $result = $notification_system->notifyPreviousApplicants($test_job_id);
    
    if ($result) {
        echo "✅ Notification process completed successfully!<br>\n";
    } else {
        echo "❌ Notification process failed or no notifications sent<br>\n";
    }
    
    // Check results
    echo "<h3>5. Results</h3>\n";
    
    $stmt = $db->prepare("
        SELECT COUNT(*) as notification_count 
        FROM notifications 
        WHERE related_type = 'job_opportunity' 
        AND related_id = ?
    ");
    $stmt->execute([$test_job_id]);
    $notification_count = $stmt->fetch()['notification_count'];
    
    echo "📨 Created {$notification_count} in-app notifications<br>\n";
    
    // Show recent notifications
    if ($notification_count > 0) {
        echo "<h4>Recent Notifications Created:</h4>\n";
        $stmt = $db->prepare("
            SELECT n.title, n.message, c.first_name, c.last_name, n.created_at
            FROM notifications n
            LEFT JOIN candidates c ON n.user_id = c.id
            WHERE n.related_type = 'job_opportunity' 
            AND n.related_id = ?
            ORDER BY n.created_at DESC
        ");
        $stmt->execute([$test_job_id]);
        $notifications = $stmt->fetchAll();
        
        echo "<ul>\n";
        foreach ($notifications as $notification) {
            echo "<li><strong>{$notification['title']}</strong><br>\n";
            echo "To: {$notification['first_name']} {$notification['last_name']}<br>\n";
            echo "Message: " . substr($notification['message'], 0, 100) . "...<br>\n";
            echo "Created: {$notification['created_at']}<br><br></li>\n";
        }
        echo "</ul>\n";
    }
    
    // Check email logs
    $stmt = $db->prepare("
        SELECT COUNT(*) as email_count, 
               COUNT(CASE WHEN status = 'sent' THEN 1 END) as sent_count,
               COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_count
        FROM email_notifications 
        WHERE subject LIKE ? 
        AND created_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
    ");
    $stmt->execute(["%$test_job_title%"]);
    $email_stats = $stmt->fetch();
    
    echo "📧 Email attempts: {$email_stats['email_count']} total, {$email_stats['sent_count']} sent, {$email_stats['failed_count']} failed<br>\n";
    
    // Clean up - remove test job
    echo "<h3>6. Cleanup</h3>\n";
    $stmt = $db->prepare("DELETE FROM jobs WHERE id = ?");
    $stmt->execute([$test_job_id]);
    echo "🗑️ Test job removed<br>\n";
    
    echo "<h3>✅ Test Complete</h3>\n";
    echo "<div style='background: #e8f5e8; padding: 15px; border-left: 4px solid #28a745; margin: 20px 0;'>\n";
    echo "<h4>🎉 New Job Notification System Status:</h4>\n";
    
    if ($notification_count > 0) {
        echo "<p>✅ <strong>SUCCESS!</strong> The notification system is working correctly.</p>\n";
        echo "<ul>\n";
        echo "<li>✅ Database tables are properly configured</li>\n";
        echo "<li>✅ Candidate matching logic works correctly</li>\n";
        echo "<li>✅ In-app notifications are being created</li>\n";
        echo "<li>✅ Email notifications are being attempted</li>\n";
        echo "</ul>\n";
        echo "<p><strong>What happens now:</strong></p>\n";
        echo "<ul>\n";
        echo "<li>When a company posts a new <strong>ACTIVE</strong> job, the system automatically finds candidates who have previously applied to jobs in the same category</li>\n";
        echo "<li>Each eligible candidate receives both an in-app notification and an email alert</li>\n";
        echo "<li>Candidates are excluded if they have already applied to that specific job</li>\n";
        echo "<li>The system logs all email attempts for monitoring</li>\n";
        echo "</ul>\n";
    } else {
        echo "<p>⚠️ <strong>PARTIAL SUCCESS:</strong> The system is set up correctly but no notifications were sent in this test.</p>\n";
        echo "<p>This could be because:</p>\n";
        echo "<ul>\n";
        echo "<li>All candidates in the test category have already applied to recent jobs</li>\n";
        echo "<li>There are no candidates with valid email addresses in the selected category</li>\n";
        echo "</ul>\n";
        echo "<p>The system will work when there are eligible candidates for new job postings.</p>\n";
    }
    
    echo "</div>\n";
    
} catch (Exception $e) {
    echo "❌ Error during testing: " . $e->getMessage() . "<br>\n";
    echo "<pre>" . $e->getTraceAsString() . "</pre>\n";
}
?>