<?php

require_once 'vendor/autoload.php';

use App\Models\User;
use App\Models\JointAccount;
use App\Models\JointAccountTransaction;
use App\Models\JointAccountApproval;

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

echo "=== Testing Two-Stage Approval Workflow ===\n\n";

try {
    // Find the ZIKO TEAM joint account
    $jointAccount = JointAccount::where('account_name', 'ZIKO TEAM')->first();
    
    if (!$jointAccount) {
        echo "ZIKO TEAM joint account not found.\n";
        exit;
    }
    
    echo "Joint Account: {$jointAccount->account_name}\n";
    echo "Active Members: " . $jointAccount->activeMembers()->count() . "\n";
    echo "Required Approvals: " . $jointAccount->getRequiredApprovals() . "\n\n";
    
    // Find a pending withdrawal transaction with fewer approvals
    $pendingTransaction = JointAccountTransaction::where('joint_account_id', $jointAccount->id)
        ->where('transaction_type', 'withdrawal')
        ->where('status', 'pending')
        ->with(['initiator', 'approvals.approver'])
        ->get()
        ->filter(function($transaction) use ($jointAccount) {
            return $transaction->getApprovalCount() < $jointAccount->getRequiredApprovals();
        })
        ->first();
    
    if (!$pendingTransaction) {
        echo "No pending withdrawal transactions found. Creating a test transaction...\n";
        
        // Create a test transaction
        $pendingTransaction = JointAccountTransaction::create([
            'joint_account_id' => $jointAccount->id,
            'initiated_by' => $jointAccount->activeMembers()->first()->user_id,
            'transaction_type' => 'withdrawal',
            'amount' => 100.00,
            'description' => 'Test transaction for two-stage approval workflow',
            'reference' => 'TEST' . time() . rand(1000, 9999),
            'status' => 'pending'
        ]);
        
        echo "Created test transaction ID: {$pendingTransaction->id}\n";
    }
    
    echo "Found pending transaction:\n";
    echo "ID: {$pendingTransaction->id}\n";
    echo "Amount: \${$pendingTransaction->amount}\n";
    echo "Status: {$pendingTransaction->status}\n";
    echo "Current Approvals: " . $pendingTransaction->getApprovalCount() . "\n";
    echo "Required Approvals: " . $jointAccount->getRequiredApprovals() . "\n";
    echo "Is Fully Approved: " . ($pendingTransaction->isFullyApproved() ? 'Yes' : 'No') . "\n\n";
    
    // Get active members who haven't approved yet
    $activeMembers = $jointAccount->activeMembers()->with('user')->get();
    $membersToApprove = $activeMembers->filter(function($member) use ($pendingTransaction) {
        return !$pendingTransaction->hasUserApproved($member->user);
    });
    
    echo "Members who can still approve:\n";
    foreach ($membersToApprove as $member) {
        echo "- {$member->user->name} ({$member->user->email})\n";
    }
    echo "\n";
    
    // Stage 1: Simulate member approvals
    echo "=== STAGE 1: Member Approvals ===\n";
    foreach ($membersToApprove as $member) {
        echo "Simulating approval by: {$member->user->name}\n";
        
        // Create approval record
        JointAccountApproval::create([
            'joint_account_transaction_id' => $pendingTransaction->id,
            'approver_id' => $member->user->id,
            'action' => 'approved',
            'comment' => 'Member approval for two-stage workflow',
            'action_at' => now()
        ]);
        
        echo "Approval record created.\n";
        
        // Refresh transaction
        $pendingTransaction->refresh();
        
        echo "After approval:\n";
        echo "Current Approvals: " . $pendingTransaction->getApprovalCount() . "\n";
        echo "Required Approvals: " . $jointAccount->getRequiredApprovals() . "\n";
        echo "Is Fully Approved: " . ($pendingTransaction->isFullyApproved() ? 'Yes' : 'No') . "\n";
        echo "Status: {$pendingTransaction->status}\n";
        
                 // Check if all members have approved
         if ($pendingTransaction->isFullyApproved()) {
             echo "\n🟢 All members have approved! Testing status change to 'processing'...\n";
             
             // Manually trigger the status change to 'processing'
             $pendingTransaction->update([
                 'status' => 'processing',
                 'approval_data' => array_merge($pendingTransaction->approval_data ?? [], [
                     'member_consensus_reached_at' => now(),
                     'member_approvals' => $pendingTransaction->approvals()->where('action', 'approved')->with('approver')->get()
                 ])
             ]);
             
             $pendingTransaction->refresh();
             
             if ($pendingTransaction->status === 'processing') {
                 echo "✅ SUCCESS: Transaction status changed to 'processing'!\n";
                 echo "Status: {$pendingTransaction->status}\n";
                 echo "Member consensus reached at: " . ($pendingTransaction->approval_data['member_consensus_reached_at'] ?? 'Not set') . "\n";
             } else {
                 echo "❌ FAILED: Transaction status not changed to 'processing'.\n";
                 echo "Current status: {$pendingTransaction->status}\n";
             }
             break;
        } else {
            echo "\n🟡 Transaction not yet fully approved. Need more member approvals.\n\n";
        }
    }
    
    // Stage 2: Admin final approval
    if ($pendingTransaction->status === 'processing') {
        echo "\n=== STAGE 2: Admin Final Approval ===\n";
        
        // Find an admin user
        $adminUser = User::whereHas('roles', function($query) {
            $query->where('role', 'admin');
        })->first();
        
        if (!$adminUser) {
            echo "No admin user found. Creating test admin...\n";
            $adminUser = User::create([
                'name' => 'Test Admin',
                'email' => 'admin@test.com',
                'password' => bcrypt('password'),
                'verification_status' => 'verified'
            ]);
            
            // Add admin role
            \App\Models\Role::create([
                'user_id' => $adminUser->id,
                'role' => 'admin'
            ]);
        }
        
        echo "Using admin: {$adminUser->name} ({$adminUser->email})\n";
        echo "Is Admin: " . ($adminUser->isAdmin() ? 'Yes' : 'No') . "\n\n";
        
        echo "Testing admin final approval...\n";
        
        // Simulate the admin approval process
        $controller = new \App\Http\Controllers\JointAccountTransactionController();
        $reflection = new ReflectionClass($controller);
        $processTransactionMethod = $reflection->getMethod('processTransaction');
        $processTransactionMethod->setAccessible(true);
        
        // Process the transaction (admin final approval)
        $processTransactionMethod->invoke($controller, $pendingTransaction);
        
        // Add admin approval record
        JointAccountApproval::create([
            'joint_account_transaction_id' => $pendingTransaction->id,
            'approver_id' => $adminUser->id,
            'action' => 'approved',
            'comment' => 'Admin final approval',
            'action_at' => now()
        ]);
        
        $pendingTransaction->refresh();
        
        echo "After admin final approval:\n";
        echo "Status: {$pendingTransaction->status}\n";
        echo "Completed At: " . ($pendingTransaction->completed_at ? $pendingTransaction->completed_at : 'Not set') . "\n";
        echo "Total Approvals: " . $pendingTransaction->approvals->count() . "\n";
        
        if ($pendingTransaction->status === 'completed') {
            echo "✅ SUCCESS: Transaction completed after admin final approval!\n";
        } else {
            echo "❌ FAILED: Transaction not completed after admin approval.\n";
        }
        
        // Show all approvals
        echo "\nAll Approvals:\n";
        foreach ($pendingTransaction->approvals as $approval) {
            $type = $approval->approver->isAdmin() ? 'ADMIN' : 'MEMBER';
            echo "- {$approval->approver->name} ({$type}): {$approval->action}\n";
            if ($approval->comment) {
                echo "  Comment: {$approval->comment}\n";
            }
        }
    }
    
    echo "\n=== Test Complete ===\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    echo "Stack trace: " . $e->getTraceAsString() . "\n";
} 