<?php

namespace Tests\Feature;

use App\Filament\Widgets\AssociationsDashboardStatsOverview;
use App\Models\Association;
use App\Models\Center;
use App\Models\City;
use App\Models\Order;
use App\Models\State;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class FamiliesCountReportTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();

        // Create necessary states and cities first
        $state = State::create(['name' => 'Test State']);
        $city = City::create(['name' => 'Test City', 'state_id' => $state->id]);

        // Store for later use
        $this->state = $state;
        $this->city = $city;
    }

    /**
     * Test that families count in reports uses actual centers data instead of manual entry
     */
    public function test_families_count_uses_centers_data_instead_of_manual_entry()
    {
        // Create an association
        $association = Association::factory()->create();
        $user = User::factory()->create();

        // Create centers with actual families count from statistics
        $center1 = Center::create([
            'name' => ['en' => 'Center 1', 'ar' => 'مركز 1'],
            'city_id' => $this->city->id,
            'families_count' => 100, // Actual count from statistics
        ]);

        $center2 = Center::create([
            'name' => ['en' => 'Center 2', 'ar' => 'مركز 2'],
            'city_id' => $this->city->id,
            'families_count' => 150, // Actual count from statistics
        ]);

        // Create an accepted order with MANUAL entry that differs from actual centers count
        $order = Order::create([
            'type' => Order::TYPE_STATION,
            'status' => Order::STATUS_ACCEPTED,
            'association_id' => $association->id,
            'state_id' => $this->state->id,
            'city_id' => $this->city->id,
            'number_of_families' => 300, // Manual entry by association (incorrect)
            'water_source' => [Order::WATER_SOURCE_GOVERNMENT],
            'water_distance' => 5.0,
            'order_justifications' => 'Test justification',
            'created_by' => $user->id,
            'lat' => 24.7136,
            'lng' => 46.6753,
        ]);

        // Attach centers to the order
        $order->centers()->attach([$center1->id, $center2->id]);

        // Calculate actual families count from centers (this should be used in reports)
        $actualFamiliesFromCenters = $order->calculateTotalFamilies(); // Should be 250 (100 + 150)
        $manualFamiliesEntry = $order->number_of_families; // This is 300 (incorrect)

        // Verify the calculation method works correctly
        $this->assertEquals(250, $actualFamiliesFromCenters);
        $this->assertEquals(300, $manualFamiliesEntry);
        $this->assertNotEquals($actualFamiliesFromCenters, $manualFamiliesEntry);

        // Test the widget behavior - this should use actual families count, not manual entry
        $widget = new AssociationsDashboardStatsOverview;
        $stats = $widget->getStats();

        // The families count stat should show actual families count from centers (250), not manual entry (300)
        $familiesCountStat = $stats[0]; // First stat is families count

        // Extract the numerical value from the formatted stat
        $displayedCount = (int) str_replace(',', '', $familiesCountStat->getValue());

        // This should be 250 (from centers) not 300 (manual entry)
        $this->assertEquals(250, $displayedCount,
            'Families count in dashboard should use actual families count from centers, not manual association entry');
    }

    /**
     * Test calculateTotalFamilies method works correctly
     */
    public function test_calculate_total_families_method()
    {
        $association = Association::factory()->create();
        $user = User::factory()->create();

        // Create centers
        $center1 = Center::create([
            'name' => ['en' => 'Center 1'],
            'city_id' => $this->city->id,
            'families_count' => 75,
        ]);

        $center2 = Center::create([
            'name' => ['en' => 'Center 2'],
            'city_id' => $this->city->id,
            'families_count' => 125,
        ]);

        // Create order
        $order = Order::create([
            'type' => Order::TYPE_STATION,
            'association_id' => $association->id,
            'state_id' => $this->state->id,
            'city_id' => $this->city->id,
            'number_of_families' => 999, // Manual entry (different from centers)
            'water_source' => [Order::WATER_SOURCE_GOVERNMENT],
            'water_distance' => 3.0,
            'order_justifications' => 'Test',
            'created_by' => $user->id,
            'lat' => 24.0,
            'lng' => 46.0,
        ]);

        // Initially no centers attached
        $this->assertEquals(0, $order->calculateTotalFamilies());

        // Attach one center
        $order->centers()->attach($center1->id);
        $this->assertEquals(75, $order->calculateTotalFamilies());

        // Attach second center
        $order->centers()->attach($center2->id);
        $this->assertEquals(200, $order->calculateTotalFamilies()); // 75 + 125

        // Manual entry should remain unchanged
        $this->assertEquals(999, $order->number_of_families);
    }

    /**
     * Test with multiple orders to ensure proper aggregation
     */
    public function test_multiple_orders_families_count_aggregation()
    {
        $association1 = Association::factory()->create();
        $association2 = Association::factory()->create();
        $user = User::factory()->create();

        // Create centers
        $center1 = Center::create([
            'name' => ['en' => 'Center A'],
            'city_id' => $this->city->id,
            'families_count' => 50,
        ]);

        $center2 = Center::create([
            'name' => ['en' => 'Center B'],
            'city_id' => $this->city->id,
            'families_count' => 80,
        ]);

        $center3 = Center::create([
            'name' => ['en' => 'Center C'],
            'city_id' => $this->city->id,
            'families_count' => 70,
        ]);

        // Create accepted orders
        $order1 = Order::create([
            'type' => Order::TYPE_STATION,
            'status' => Order::STATUS_ACCEPTED,
            'association_id' => $association1->id,
            'state_id' => $this->state->id,
            'city_id' => $this->city->id,
            'number_of_families' => 1000, // Manual entry (ignore this)
            'water_source' => [Order::WATER_SOURCE_GOVERNMENT],
            'water_distance' => 2.0,
            'order_justifications' => 'Test 1',
            'created_by' => $user->id,
            'lat' => 24.0,
            'lng' => 46.0,
        ]);

        $order2 = Order::create([
            'type' => Order::TYPE_TANKER,
            'status' => Order::STATUS_ACCEPTED,
            'association_id' => $association2->id,
            'state_id' => $this->state->id,
            'city_id' => $this->city->id,
            'number_of_families' => 2000, // Manual entry (ignore this)
            'water_source' => [Order::WATER_SOURCE_PRIVATE],
            'water_distance' => 4.0,
            'order_justifications' => 'Test 2',
            'created_by' => $user->id,
            'lat' => 25.0,
            'lng' => 47.0,
        ]);

        // Attach centers
        $order1->centers()->attach([$center1->id, $center2->id]); // 50 + 80 = 130
        $order2->centers()->attach([$center3->id]); // 70

        // Total families from centers should be 200 (130 + 70)
        // Manual entries sum to 3000 (1000 + 2000) but should be ignored

        $widget = new AssociationsDashboardStatsOverview;
        $stats = $widget->getStats();
        $familiesCountStat = $stats[0];
        $displayedCount = (int) str_replace(',', '', $familiesCountStat->getValue());

        $this->assertEquals(200, $displayedCount,
            'Total families count should be sum of centers data (200), not manual entries (3000)');
    }
}
