<?php
// Complete test of company user login process
require_once 'config/config.php';

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

echo "=== Testing Company User Login Process ===\n\n";

// 1. Get a company user for testing
$stmt = $db->query("SELECT cu.*, c.name as company_name, c.status as company_status FROM company_users cu INNER JOIN companies c ON cu.company_id = c.id LIMIT 1");
$test_user = $stmt->fetch();

if (!$test_user) {
    echo "❌ No company users found for testing.\n";
    exit;
}

echo "1. Found test user:\n";
echo "   Email: {$test_user['email']}\n";
echo "   Company: {$test_user['company_name']}\n";
echo "   Company Status: {$test_user['company_status']}\n";
echo "   User Status: {$test_user['status']}\n\n";

// 2. Test the login query
echo "2. Testing login query...\n";
$stmt = $db->prepare("
    SELECT cu.*, c.name as company_name, c.status as company_status 
    FROM company_users cu 
    INNER JOIN companies c ON cu.company_id = c.id 
    WHERE cu.email = ? AND cu.status = 'active'
");
$stmt->execute([$test_user['email']]);
$login_result = $stmt->fetch();

if ($login_result) {
    echo "   ✅ Login query successful\n";
    echo "   Company approved: " . ($login_result['company_status'] === 'approved' ? '✅ Yes' : '❌ No') . "\n";
} else {
    echo "   ❌ Login query failed\n";
}

// 3. Test session variables that would be set
echo "\n3. Session variables that would be set:\n";
if ($login_result && $login_result['company_status'] === 'approved') {
    echo "   \$_SESSION['user_id'] = {$login_result['id']} (company_users.id)\n";
    echo "   \$_SESSION['company_id'] = {$login_result['company_id']} (companies.id)\n";
    echo "   \$_SESSION['user_type'] = 'company'\n";
    echo "   \$_SESSION['user_email'] = '{$login_result['email']}'\n";
    echo "   \$_SESSION['company_name'] = '{$login_result['company_name']}'\n";
    echo "   \$_SESSION['user_name'] = '{$login_result['name']}'\n";
    echo "   \$_SESSION['is_primary_user'] = " . ($login_result['is_primary'] ? 'true' : 'false') . "\n";
    
    echo "\n4. ✅ Company user can login successfully!\n";
} else {
    echo "\n4. ❌ Company user cannot login - company not approved or user inactive\n";
}

// 5. Test dashboard query
echo "\n5. Testing dashboard queries...\n";
if ($login_result) {
    $company_id = $login_result['company_id'];
    
    // Test job count query
    $stmt = $db->prepare("SELECT COUNT(*) as count FROM jobs WHERE company_id = ?");
    $stmt->execute([$company_id]);
    $job_count = $stmt->fetch()['count'];
    
    echo "   Jobs for this company: $job_count\n";
    echo "   ✅ Dashboard queries will work\n";
} else {
    echo "   ❌ Cannot test dashboard queries\n";
}

echo "\n=== Test Complete ===\n";
?>