<?php

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

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

use Illuminate\Support\Facades\DB;

echo "=== Check Marketing Officer Assignment ===\n\n";

try {
    $userId = 30; // User ID for anuradhasampath64@gmail.com
    
    // Check user exists
    $user = DB::table('users')->find($userId);
    if (!$user) {
        echo "❌ User not found\n";
        exit;
    }
    echo "✓ User: {$user->name} ({$user->email})\n\n";
    
    // Check marketing officer assignment
    echo "Checking marketing_officer_users table...\n";
    $assignment = DB::table('marketing_officer_users')
        ->where('user_id', $userId)
        ->first();
    
    if ($assignment) {
        echo "✓ Assignment found:\n";
        echo "  - Marketing Officer ID: {$assignment->marketing_officer_id}\n";
        echo "  - Assigned at: {$assignment->created_at}\n\n";
        
        // Get marketing officer details
        $officer = DB::table('users')->find($assignment->marketing_officer_id);
        if ($officer) {
            echo "✓ Marketing Officer Details:\n";
            echo "  - Name: {$officer->name}\n";
            echo "  - Email: {$officer->email}\n";
            echo "  - Phone: " . ($officer->phone ?? 'Not set') . "\n";
            echo "  - Avatar: " . ($officer->avatar ?? 'Not set') . "\n";
            echo "  - Status: {$officer->status}\n\n";
            
            // Test the API endpoint logic
            echo "Testing API response format...\n";
            $avatarUrl = $officer->avatar 
                ? url('storage/' . $officer->avatar) 
                : null;
                
            $response = [
                'id' => $officer->id,
                'name' => $officer->name,
                'email' => $officer->email,
                'phone' => $officer->phone,
                'avatar_url' => $avatarUrl,
            ];
            
            echo json_encode($response, JSON_PRETTY_PRINT) . "\n\n";
            
            echo "=== Test Complete ===\n";
            echo "API Endpoint: GET /api/v1/admin/marketing-officer/assigned-user/{$userId}\n";
        } else {
            echo "❌ Marketing officer not found in users table\n";
        }
    } else {
        echo "❌ No marketing officer assigned to this user\n";
        echo "\nTo assign a marketing officer, run:\n";
        echo "INSERT INTO marketing_officer_users (user_id, marketing_officer_id, created_at, updated_at)\n";
        echo "VALUES ({$userId}, <officer_id>, NOW(), NOW());\n";
    }
    
} catch (\Exception $e) {
    echo "\n❌ ERROR: " . $e->getMessage() . "\n";
    echo "\nStack trace:\n";
    echo $e->getTraceAsString() . "\n";
}
