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

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

echo "<h2>🧪 Create Test Scenario for Job Visibility</h2>\n";

// Create some test jobs with different visibilities for SANPC (company ID: 8)
echo "<h3>1. Creating Test Jobs for SANPC (Company ID: 8)</h3>\n";

$test_jobs = [
    [
        'title' => 'SANPC Internal Job - IT Manager',
        'description' => 'Internal promotion opportunity for existing SANPC employees only.',
        'visibility' => 'internal',
        'company_id' => 8,
        'deadline' => '2025-09-15'
    ],
    [
        'title' => 'SANPC Both Job - Project Manager',  
        'description' => 'Open to both internal employees and external candidates.',
        'visibility' => 'both',
        'company_id' => 8,
        'deadline' => '2025-09-15'
    ],
    [
        'title' => 'SANPC External Only - Sales Representative',
        'description' => 'External candidates only - not for current SANPC employees.',
        'visibility' => 'external', 
        'company_id' => 8,
        'deadline' => '2025-09-15'
    ]
];

foreach ($test_jobs as $job) {
    // Check if job already exists
    $stmt = $db->prepare("SELECT id FROM jobs WHERE title = ?");
    $stmt->execute([$job['title']]);
    
    if (!$stmt->fetch()) {
        $stmt = $db->prepare("
            INSERT INTO jobs (
                company_id, title, description, requirements, location,
                employment_type, salary_min, salary_max, experience_level,
                job_visibility, deadline, status, created_at
            ) VALUES (
                ?, ?, ?, 'Bachelor degree required', 'Cape Town',
                'full-time', 50000, 80000, 'mid',
                ?, ?, 'active', NOW()
            )
        ");
        
        $result = $stmt->execute([
            $job['company_id'],
            $job['title'], 
            $job['description'],
            $job['visibility'],
            $job['deadline']
        ]);
        
        if ($result) {
            $new_id = $db->lastInsertId();
            echo "<p>✅ Created: {$job['title']} (ID: $new_id, Visibility: {$job['visibility']})</p>\n";
        }
    } else {
        echo "<p>ℹ️ Already exists: {$job['title']}</p>\n";
    }
}

// 2. Test the visibility for internal candidates
echo "<h3>2. Test Visibility for Internal SANPC Candidates</h3>\n";

// Get all SANPC internal candidates
$stmt = $db->prepare("SELECT id, first_name, last_name FROM candidates WHERE candidate_type = 'internal' AND company_id = 8");
$stmt->execute();
$internal_candidates = $stmt->fetchAll();

if ($internal_candidates) {
    foreach ($internal_candidates as $candidate) {
        echo "<h4>Testing for {$candidate['first_name']} {$candidate['last_name']} (ID: {$candidate['id']})</h4>\n";
        
        // Test the filtering query from jobs.php
        $stmt = $db->prepare("
            SELECT j.id, j.title, j.job_visibility, j.company_id, c.name as company_name,
                   CASE 
                       WHEN (j.job_visibility IN ('internal', 'both') AND j.company_id = 8) THEN 'Own company - should see'
                       WHEN (j.job_visibility IN ('external', 'both') AND j.company_id != 8) THEN 'Other company - should see'
                       WHEN (j.job_visibility = 'external' AND j.company_id = 8) THEN 'Own company external - should NOT see'
                       ELSE 'Other'
                   END as visibility_rule
            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 IN ('internal', 'both') AND j.company_id = ?) OR 
                (j.job_visibility IN ('external', 'both') AND j.company_id != ?)
            )
            ORDER BY j.company_id, j.job_visibility
        ");
        
        $stmt->execute([$candidate['id'], $candidate['id']]); // This is wrong - should be company_id
        $visible_jobs = $stmt->fetchAll();
        
        echo "<p><strong>Jobs they can see:</strong> " . count($visible_jobs) . "</p>\n";
        
        echo "<table border='1' cellpadding='5'>\n";
        echo "<tr><th>Title</th><th>Visibility</th><th>Company</th><th>Rule</th></tr>\n";
        
        foreach ($visible_jobs as $job) {
            $color = '';
            if (strpos($job['visibility_rule'], 'should see') !== false) {
                $color = 'style="background-color: #e8f5e8;"';
            } else {
                $color = 'style="background-color: #ffebee;"';
            }
            
            echo "<tr $color>";
            echo "<td>" . substr($job['title'], 0, 40) . "...</td>";
            echo "<td>{$job['job_visibility']}</td>";
            echo "<td>{$job['company_name']}</td>";
            echo "<td style='font-size: 12px;'>{$job['visibility_rule']}</td>";
            echo "</tr>\n";
        }
        echo "</table>\n";
        
        // Check what they should NOT see
        $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 = 8
        ");
        $stmt->execute();
        $blocked_jobs = $stmt->fetchAll();
        
        if ($blocked_jobs) {
            echo "<p><strong>❌ Jobs they should NOT see (external-only from own company):</strong></p>\n";
            echo "<table border='1' cellpadding='5' style='background-color: #ffebee;'>\n";
            echo "<tr><th>Title</th><th>Visibility</th><th>Company</th></tr>\n";
            foreach ($blocked_jobs as $job) {
                echo "<tr>";
                echo "<td>" . substr($job['title'], 0, 40) . "...</td>";
                echo "<td>{$job['job_visibility']}</td>";
                echo "<td>{$job['company_name']}</td>";
                echo "</tr>\n";
            }
            echo "</table>\n";
        }
        
        echo "<hr>\n";
    }
} else {
    echo "<p>No internal candidates found for SANPC</p>\n";
}

// 3. Summary
echo "<h3>3. Expected Behavior Summary</h3>\n";
echo "<div style='background: #e3f2fd; color: #1565c0; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
echo "<h4>🎯 For SANPC Internal Employees:</h4>\n";
echo "<p><strong>They SHOULD see:</strong></p>\n";
echo "<ul>\n";
echo "<li>✅ <strong>Internal jobs</strong> from SANPC (their company)</li>\n";
echo "<li>✅ <strong>'Both' jobs</strong> from SANPC (their company)</li>\n";
echo "<li>✅ <strong>External jobs</strong> from OTHER companies (not SANPC)</li>\n";
echo "<li>✅ <strong>'Both' jobs</strong> from OTHER companies (not SANPC)</li>\n";
echo "</ul>\n";
echo "<p><strong>They should NOT see:</strong></p>\n";
echo "<ul>\n";
echo "<li>❌ <strong>External-only jobs</strong> from SANPC (their own company)</li>\n";
echo "</ul>\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; }
th { background-color: #f2f2f2; }
h1, h2, h3, h4 { color: #333; }
</style>