<?php

require_once 'vendor/autoload.php';

use App\Models\User;
use App\Models\JointAccount;
use App\Models\JointAccountMember;
use Illuminate\Support\Facades\Auth;

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

echo "=== API Endpoint Test ===\n\n";

try {
    // Test with user uloubi7@gmail.com (ID 362) who has a pending invitation
    $user = User::where('email', 'uloubi7@gmail.com')->first();
    
    if (!$user) {
        echo "User uloubi7@gmail.com not found!\n";
        exit;
    }
    
    echo "Testing with user: {$user->email} (ID: {$user->id})\n\n";
    
    // Simulate authentication
    Auth::login($user);
    
    // Test the index method directly
    $controller = new \App\Http\Controllers\JointAccountController();
    $response = $controller->index();
    
    echo "API Response Status: " . $response->getStatusCode() . "\n";
    echo "API Response Data:\n";
    $data = json_decode($response->getContent(), true);
    print_r($data);
    
    echo "\n=== Manual Query Test ===\n";
    
    // Get active joint accounts where user is a member
    $activeJointAccounts = JointAccount::whereHas('members', function($query) use ($user) {
        $query->where('user_id', $user->id)->where('status', 'active');
    })
    ->with(['members.user', 'creator'])
    ->withCount('activeMembers')
    ->latest()
    ->get();
    
    echo "Active Joint Accounts Count: " . $activeJointAccounts->count() . "\n";
    
    // Get pending invitations for the user
    $pendingInvitations = JointAccount::whereHas('members', function($query) use ($user) {
        $query->where('user_id', $user->id)->where('status', 'pending');
    })
    ->with(['members.user', 'creator'])
    ->latest()
    ->get();
    
    echo "Pending Invitations Count: " . $pendingInvitations->count() . "\n";
    
    foreach ($pendingInvitations as $account) {
        echo "  - {$account->account_name} (ID: {$account->id})\n";
        $member = $account->members->where('user_id', $user->id)->first();
        if ($member) {
            echo "    Role: {$member->role}, Status: {$member->status}\n";
        }
    }
    
    echo "\n=== Test Complete ===\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
} 