<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

class DonorFinancialPortfolioCalculationTest extends TestCase
{
    /**
     * Test that percentage calculation works with string inputs
     * This test validates the fix for the type conversion issue
     */
    public function test_allocation_calculation_with_string_percentage(): void
    {
        // Simulate the values that would come from the form
        $approvedPrice = 1000.0; // float from database
        $percentage = '15.5'; // string from form input

        // Apply the same type casting fix we implemented
        $percentage = (float) ($percentage ?? 0);
        $approvedPrice = (float) ($approvedPrice ?? 0);

        // Calculate amount the same way as in the code
        $amount = ($approvedPrice * $percentage) / 100;

        // Expected result: 1000 * 15.5 / 100 = 155
        $this->assertEquals(155.0, $amount);
    }

    /**
     * Test edge cases for the calculation
     */
    public function test_allocation_calculation_edge_cases(): void
    {
        // Test with null values
        $approvedPrice = (float) (null ?? 0);
        $percentage = (float) (null ?? 0);
        $amount = ($approvedPrice * $percentage) / 100;
        $this->assertEquals(0.0, $amount);

        // Test with empty string
        $approvedPrice = (float) (1000.0 ?? 0);
        $percentage = (float) ('' ?? 0);
        $amount = ($approvedPrice * $percentage) / 100;
        $this->assertEquals(0.0, $amount);

        // Test with zero values
        $approvedPrice = (float) (0 ?? 0);
        $percentage = (float) (50.0 ?? 0);
        $amount = ($approvedPrice * $percentage) / 100;
        $this->assertEquals(0.0, $amount);
    }

    /**
     * Test percentage to amount conversion with various string inputs
     */
    public function test_percentage_string_conversion(): void
    {
        $testCases = [
            ['1000', '10', 100.0],      // Both strings
            [1000.0, '25.5', 255.0],   // Mixed types
            ['500.50', '33.33', 166.663],  // Decimal strings
        ];

        foreach ($testCases as [$price, $percent, $expected]) {
            $approvedPrice = (float) ($price ?? 0);
            $percentage = (float) ($percent ?? 0);
            $amount = ($approvedPrice * $percentage) / 100;

            $this->assertEqualsWithDelta($expected, $amount, 0.001,
                "Failed for price: $price, percentage: $percent");
        }
    }
}
