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

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

echo "<h2>🐛 Debug Job Visibility Issue</h2>\n";

// Simulate internal candidate login
$_SESSION['user_type'] = 'candidate';
$_SESSION['user_id'] = 13; // Sisanda from SANPC (company ID 8)

echo "<h3>1. Simulating Internal Candidate: Sisanda (Company ID: 8)</h3>\n";

// Get candidate info
$stmt = $db->prepare("SELECT * FROM candidates WHERE id = ?");
$stmt->execute([13]);
$candidate = $stmt->fetch();

if ($candidate) {
    echo "<p><strong>Candidate:</strong> {$candidate['first_name']} {$candidate['last_name']}</p>\n";
    echo "<p><strong>Email:</strong> {$candidate['email']}</p>\n";
    echo "<p><strong>Type:</strong> {$candidate['candidate_type']}</p>\n";
    echo "<p><strong>Company ID:</strong> {$candidate['company_id']}</p>\n";
} else {
    echo "<p>❌ Candidate not found</p>\n";
    exit;
}

// 2. Test the current filtering logic from jobs.php
echo "<h3>2. Current Filtering Logic Test</h3>\n";

// Get candidate type and company_id (from jobs.php logic)
$stmt = $db->prepare("SELECT candidate_type, company_id FROM candidates WHERE id = ?");
$stmt->execute([13]);
$candidate_data = $stmt->fetch();

echo "<p><strong>Retrieved candidate data:</strong></p>\n";
echo "<ul>\n";
echo "<li>Type: {$candidate_data['candidate_type']}</li>\n";
echo "<li>Company ID: {$candidate_data['company_id']}</li>\n";
echo "</ul>\n";

if ($candidate_data && $candidate_data['candidate_type'] === 'internal') {
    // Current logic 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_data['company_id'], $candidate_data['company_id']];
    
    $where_clause = "WHERE " . implode(" AND ", $where_conditions);
    
    echo "<h4>Generated WHERE clause:</h4>\n";
    echo "<pre>" . htmlspecialchars($where_clause) . "</pre>\n";
    echo "<p><strong>Parameters:</strong> [" . implode(', ', $params) . "]</p>\n";
    
    // Execute the query
    $query = "
        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 = {$candidate_data['company_id']}) THEN 'Own company - internal/both'
                   WHEN (j.job_visibility IN ('external', 'both') AND j.company_id != {$candidate_data['company_id']}) THEN 'Other company - external/both'
                   ELSE 'Should not show'
               END as visibility_reason
        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();
    
    echo "<h4>Jobs that internal candidate CAN see (" . count($visible_jobs) . " jobs):</h4>\n";
    echo "<table border='1' cellpadding='5'>\n";
    echo "<tr><th>ID</th><th>Title</th><th>Visibility</th><th>Company</th><th>Reason</th></tr>\n";
    
    foreach ($visible_jobs as $job) {
        $color = '';
        if (strpos($job['visibility_reason'], 'Own company') !== false) {
            $color = 'style="background-color: #e3f2fd;"'; // Blue for own company
        } else {
            $color = 'style="background-color: #f3e5f5;"'; // Purple for other companies
        }
        
        echo "<tr $color>";
        echo "<td>{$job['id']}</td>";
        echo "<td>" . substr($job['title'], 0, 40) . "...</td>";
        echo "<td>{$job['job_visibility']}</td>";
        echo "<td>{$job['company_name']} (ID: {$job['company_id']})</td>";
        echo "<td style='font-size: 12px;'>{$job['visibility_reason']}</td>";
        echo "</tr>\n";
    }
    echo "</table>\n";
}

// 3. Check what jobs they should NOT see
echo "<h3>3. Jobs They Should NOT See</h3>\n";

$stmt = $db->query("
    SELECT j.id, j.title, j.job_visibility, j.company_id, c.name as company_name
    FROM jobs j 
    LEFT 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
    ORDER BY j.title
");
$blocked_jobs = $stmt->fetchAll();

echo "<h4>External-only jobs from their company (should be blocked):</h4>\n";
if ($blocked_jobs) {
    echo "<table border='1' cellpadding='5' style='background-color: #ffebee;'>\n";
    echo "<tr><th>ID</th><th>Title</th><th>Visibility</th><th>Company</th></tr>\n";
    foreach ($blocked_jobs as $job) {
        echo "<tr>";
        echo "<td>{$job['id']}</td>";
        echo "<td>" . substr($job['title'], 0, 40) . "...</td>";
        echo "<td>{$job['job_visibility']}</td>";
        echo "<td>{$job['company_name']} (ID: {$job['company_id']})</td>";
        echo "</tr>\n";
    }
    echo "</table>\n";
} else {
    echo "<p>✅ No external-only jobs from their company found (good!)</p>\n";
}

// 4. Test if the issue is in the logic
echo "<h3>4. Logic Verification</h3>\n";

// Check all jobs and see what the logic says
$stmt = $db->query("
    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 'SHOULD SHOW - Own company internal/both'
               WHEN j.job_visibility IN ('external', 'both') AND j.company_id != 8 THEN 'SHOULD SHOW - Other company external/both'
               WHEN j.job_visibility = 'external' AND j.company_id = 8 THEN 'SHOULD HIDE - Own company external-only'
               ELSE 'OTHER'
           END as expected_visibility
    FROM jobs j 
    LEFT 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())
    ORDER BY j.company_id, j.job_visibility
");
$all_jobs_test = $stmt->fetchAll();

echo "<h4>Expected Visibility for All Jobs:</h4>\n";
echo "<table border='1' cellpadding='5'>\n";
echo "<tr><th>ID</th><th>Title</th><th>Visibility</th><th>Company</th><th>Expected</th></tr>\n";

foreach ($all_jobs_test as $job) {
    $color = '';
    if (strpos($job['expected_visibility'], 'SHOULD SHOW') !== false) {
        $color = 'style="background-color: #e8f5e8;"'; // Green for should show
    } elseif (strpos($job['expected_visibility'], 'SHOULD HIDE') !== false) {
        $color = 'style="background-color: #ffebee;"'; // Red for should hide
    }
    
    echo "<tr $color>";
    echo "<td>{$job['id']}</td>";
    echo "<td>" . substr($job['title'], 0, 30) . "...</td>";
    echo "<td>{$job['job_visibility']}</td>";
    echo "<td>{$job['company_name']} ({$job['company_id']})</td>";
    echo "<td style='font-size: 12px;'>{$job['expected_visibility']}</td>";
    echo "</tr>\n";
}
echo "</table>\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; }
pre { background: #f5f5f5; padding: 10px; border-radius: 4px; }
</style>