<?php

require __DIR__.'/vendor/autoload.php';

use App\Models\User;
use Illuminate\Support\Facades\DB;

$app = require_once __DIR__.'/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

echo "=== Checking User ID 5 and Marketing Officer Assignment ===\n\n";

$userId = 5;
$marketingOfficerEmail = 'anuradhasampath999@gmail.com';

// Get marketing officer
$marketingOfficer = DB::table('users')->where('email', $marketingOfficerEmail)->first();

if (!$marketingOfficer) {
    echo "❌ Marketing officer not found: $marketingOfficerEmail\n";
    exit;
}

echo "Marketing Officer:\n";
echo "  ID: {$marketingOfficer->id}\n";
echo "  Name: {$marketingOfficer->name}\n";
echo "  Email: {$marketingOfficer->email}\n\n";

// Check if user exists
$user = DB::table('users')->where('id', $userId)->first();

if (!$user) {
    echo "❌ User ID {$userId} does NOT exist in the database!\n\n";
    
    // Show all users
    echo "=== All Users in Database ===\n";
    $allUsers = DB::table('users')->orderBy('id')->get(['id', 'name', 'email', 'first_name', 'last_name']);
    foreach ($allUsers as $u) {
        echo "  ID: {$u->id}, Name: {$u->name}, Email: {$u->email}\n";
    }
    exit;
}

echo "✓ User ID {$userId} exists:\n";
echo "  Name: {$user->name}\n";
echo "  Email: {$user->email}\n";
echo "  First Name: {$user->first_name}\n";
echo "  Last Name: {$user->last_name}\n\n";

// Check assignment
$assignment = DB::table('marketing_officer_users')
    ->where('marketing_officer_id', $marketingOfficer->id)
    ->where('user_id', $userId)
    ->first();

if ($assignment) {
    echo "✓ User is ASSIGNED to marketing officer\n";
    echo "  Assigned at: {$assignment->created_at}\n\n";
} else {
    echo "❌ User is NOT assigned to marketing officer\n\n";
    
    // Show all assignments for this marketing officer
    echo "Marketing Officer's Assignments:\n";
    $assignments = DB::table('marketing_officer_users')
        ->join('users', 'marketing_officer_users.user_id', '=', 'users.id')
        ->where('marketing_officer_users.marketing_officer_id', $marketingOfficer->id)
        ->get(['users.id', 'users.name', 'users.email']);
    
    if ($assignments->isEmpty()) {
        echo "  No users assigned yet.\n";
    } else {
        foreach ($assignments as $a) {
            echo "  - User ID: {$a->id}, Name: {$a->name}, Email: {$a->email}\n";
        }
    }
}

echo "\n=== Subscription Info ===\n";
$subscription = DB::table('immigo_pro_subscriptions')->where('user_id', $userId)->first();
if ($subscription) {
    echo "✓ User has subscription:\n";
    echo "  Subscription ID: {$subscription->id}\n";
    echo "  Package: {$subscription->package_name}\n";
    echo "  Status: {$subscription->status}\n";
} else {
    echo "⚠️  User has NO subscription yet\n";
}
