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

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

echo "<h2>✅ Final Job Visibility Test - Comprehensive Validation</h2>\n";

// Test all internal candidates
$stmt = $db->query("SELECT id, first_name, last_name, company_id FROM candidates WHERE candidate_type = 'internal'");
$internal_candidates = $stmt->fetchAll();

foreach ($internal_candidates as $candidate) {
    echo "<h3>Testing: {$candidate['first_name']} {$candidate['last_name']} (Company ID: {$candidate['company_id']})</h3>\n";
    
    // Simulate the exact filtering from jobs.php
    $where_conditions = ["j.status = 'active'", "j.status != 'closed'", "c.status = 'approved'"];
    $where_conditions[] = "(j.deadline IS NULL OR j.deadline >= CURDATE())";
    $where_conditions[] = "(
        (j.job_visibility IN ('internal', 'both') AND j.company_id = ?) OR 
        (j.job_visibility IN ('external', 'both') AND j.company_id != ?)
    )";
    $params = [$candidate['company_id'], $candidate['company_id']];
    
    $where_clause = "WHERE " . implode(" AND ", $where_conditions);
    
    $query = "
        SELECT j.id, j.title, j.job_visibility, j.company_id, c.name as company_name
        FROM jobs j 
        JOIN companies c ON j.company_id = c.id 
        $where_clause
        ORDER BY j.company_id, j.job_visibility
    ";
    
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $visible_jobs = $stmt->fetchAll();
    
    // Categorize jobs
    $own_internal_both = [];
    $other_external_both = [];
    $issues = [];
    
    foreach ($visible_jobs as $job) {
        if ($job['company_id'] == $candidate['company_id']) {
            if (in_array($job['job_visibility'], ['internal', 'both'])) {
                $own_internal_both[] = $job;
            } else {
                $issues[] = $job; // This should not happen
            }
        } else {
            if (in_array($job['job_visibility'], ['external', 'both'])) {
                $other_external_both[] = $job;
            } else {
                $issues[] = $job; // This should not happen
            }
        }
    }
    
    echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
    echo "<h4>📊 Results Summary:</h4>\n";
    echo "<p><strong>✅ Own company (internal/both):</strong> " . count($own_internal_both) . " jobs</p>\n";
    echo "<p><strong>✅ Other companies (external/both):</strong> " . count($other_external_both) . " jobs</p>\n";
    echo "<p><strong>❌ Issues (shouldn't appear):</strong> " . count($issues) . " jobs</p>\n";
    echo "<p><strong>📈 Total visible:</strong> " . count($visible_jobs) . " jobs</p>\n";
    echo "</div>\n";
    
    if (!empty($own_internal_both)) {
        echo "<h5>✅ Internal/Both jobs from own company:</h5>\n";
        echo "<ul>\n";
        foreach ($own_internal_both as $job) {
            echo "<li>{$job['title']} ({$job['job_visibility']})</li>\n";
        }
        echo "</ul>\n";
    }
    
    if (!empty($other_external_both)) {
        echo "<h5>✅ External/Both jobs from other companies:</h5>\n";
        echo "<ul>\n";
        foreach ($other_external_both as $job) {
            echo "<li>{$job['title']} ({$job['job_visibility']}) - {$job['company_name']}</li>\n";
        }
        echo "</ul>\n";
    }
    
    if (!empty($issues)) {
        echo "<h5>❌ ISSUES FOUND:</h5>\n";
        echo "<ul>\n";
        foreach ($issues as $job) {
            echo "<li style='color: red;'>{$job['title']} ({$job['job_visibility']}) - {$job['company_name']}</li>\n";
        }
        echo "</ul>\n";
    }
    
    // Check for blocked jobs (external-only from own company)
    $stmt = $db->prepare("
        SELECT j.id, j.title, j.job_visibility, j.company_id, c.name as company_name
        FROM jobs j 
        JOIN companies c ON j.company_id = c.id 
        WHERE j.status = 'active' AND c.status = 'approved' 
        AND (j.deadline IS NULL OR j.deadline >= CURDATE())
        AND j.job_visibility = 'external' AND j.company_id = ?
    ");
    $stmt->execute([$candidate['company_id']]);
    $blocked_jobs = $stmt->fetchAll();
    
    if (!empty($blocked_jobs)) {
        echo "<h5>🚫 Correctly blocked (external-only from own company):</h5>\n";
        echo "<ul style='color: #d32f2f;'>\n";
        foreach ($blocked_jobs as $job) {
            echo "<li>{$job['title']} (external) - {$job['company_name']}</li>\n";
        }
        echo "</ul>\n";
    }
    
    echo "<hr>\n";
}

// Overall system validation
echo "<h3>🎯 System Validation Summary</h3>\n";

// Count all active jobs by visibility and company
$stmt = $db->query("
    SELECT 
        c.name as company_name,
        j.job_visibility,
        COUNT(*) as count
    FROM jobs j
    JOIN companies c ON j.company_id = c.id
    WHERE j.status = 'active' AND c.status = 'approved' 
    AND (j.deadline IS NULL OR j.deadline >= CURDATE())
    GROUP BY c.name, j.job_visibility
    ORDER BY c.name, j.job_visibility
");
$job_stats = $stmt->fetchAll();

echo "<h4>📈 Active Jobs by Company & Visibility:</h4>\n";
echo "<table border='1' cellpadding='5'>\n";
echo "<tr><th>Company</th><th>Visibility</th><th>Count</th><th>Internal Candidates Can See?</th></tr>\n";

foreach ($job_stats as $stat) {
    $can_see = '';
    $color = '';
    
    // For SANPC internal candidates
    if ($stat['company_name'] === 'SANPC') {
        if ($stat['job_visibility'] === 'internal' || $stat['job_visibility'] === 'both') {
            $can_see = '✅ YES - Own company internal/both';
            $color = 'style="background-color: #e3f2fd;"';
        } else {
            $can_see = '❌ NO - Own company external-only';
            $color = 'style="background-color: #ffebee;"';
        }
    } else {
        if ($stat['job_visibility'] === 'external' || $stat['job_visibility'] === 'both') {
            $can_see = '✅ YES - Other company external/both';
            $color = 'style="background-color: #f3e5f5;"';
        } else {
            $can_see = '❌ NO - Other company internal-only';
            $color = 'style="background-color: #fff3cd;"';
        }
    }
    
    echo "<tr $color>";
    echo "<td>{$stat['company_name']}</td>";
    echo "<td>{$stat['job_visibility']}</td>";
    echo "<td>{$stat['count']}</td>";
    echo "<td style='font-size: 12px;'>$can_see</td>";
    echo "</tr>\n";
}
echo "</table>\n";

echo "<div style='background: #e8f5e8; color: #2e7d32; padding: 15px; border-radius: 5px; margin: 20px 0;'>\n";
echo "<h4>✅ Job Visibility System Working Correctly!</h4>\n";
echo "<p><strong>Internal candidates can see:</strong></p>\n";
echo "<ul>\n";
echo "<li>✅ Internal and 'both' visibility jobs from their own company</li>\n";
echo "<li>✅ External and 'both' visibility jobs from other companies</li>\n";
echo "</ul>\n";
echo "<p><strong>Internal candidates CANNOT see:</strong></p>\n";
echo "<ul>\n";
echo "<li>❌ External-only jobs from their own company</li>\n";
echo "</ul>\n";
echo "<p>This ensures that internal employees don't see positions meant only for external candidates at their own company.</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: 8px; text-align: left; border: 1px solid #ddd; font-size: 12px; }
th { background-color: #f2f2f2; }
h1, h2, h3, h4, h5 { color: #333; }
ul { margin: 10px 0; }
li { margin: 5px 0; }
</style>