<?php

namespace Tests\Feature;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\User;
use App\Filament\Resources\Orders\OrderResource;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DumpEditOrderTest extends TestCase
{
    use RefreshDatabase;

    public function test_dump_edit_order_page()
    {
        // 1. Create Admin
        $admin = User::create([
            'name' => 'Admin User',
            'email' => 'admin@sawdabazar.com',
            'password' => bcrypt('password123'),
            'role' => 'admin',
        ]);

        // 2. Create Product
        $product = Product::create([
            'name' => 'Copper Yoga Mat',
            'slug' => 'copper-yoga-mat',
            'sku' => 'CYM-001',
            'price' => 155.47,
            'quantity' => 10,
        ]);

        // 3. Create Order
        $order = Order::create([
            'order_number' => 'SB-TEST-001',
            'customer_name' => 'John Doe',
            'customer_phone' => '01712345678',
            'shipping_address' => 'Uttara, Dhaka',
            'subtotal' => 155.47,
            'shipping_cost' => 80.00,
            'grand_total' => 235.47,
            'payment_method' => 'cod',
            'payment_status' => 'pending',
            'status' => 'pending',
        ]);

        // 4. Create 2 Order Items (so count > 1 for drag handles!)
        OrderItem::create([
            'order_id' => $order->id,
            'product_id' => $product->id,
            'product_name' => 'Copper Yoga Mat',
            'product_sku' => 'CYM-001',
            'price' => 155.47,
            'quantity' => 1,
            'sort_order' => 1,
        ]);

        OrderItem::create([
            'order_id' => $order->id,
            'product_id' => $product->id,
            'product_name' => 'Alpine Tumbler',
            'product_sku' => 'APT-002',
            'price' => 318.51,
            'quantity' => 1,
            'sort_order' => 2,
        ]);

        // 5. Hit Edit Page
        $this->actingAs($admin);
        $url = OrderResource::getUrl('edit', ['record' => $order->id]);
        $response = $this->get($url);

        $response->assertStatus(200);

        // 6. Save HTML to scratch directory to inspect
        $html = $response->getContent();
        @file_put_contents(__DIR__ . '/../../storage/logs/edit_order_dump.html', $html);
        
        // Output confirmation
        echo "\nHTML DUMPED TO storage/logs/edit_order_dump.html\n";
    }

    /**
     * Test that order totals are calculated dynamically via Livewire when editing an order.
     */
    public function test_order_totals_are_calculated_dynamically()
    {
        $admin = User::create([
            'name' => 'Admin User',
            'email' => 'admin@sawdabazar.com',
            'password' => bcrypt('password123'),
            'role' => 'admin',
        ]);

        $product1 = Product::create([
            'name' => 'Product 1',
            'slug' => 'product-1',
            'sku' => 'P1',
            'price' => 100.00,
            'quantity' => 10,
        ]);

        $this->actingAs($admin);
        \Livewire\Livewire::actingAs($admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        // Load Edit Order page component for a new/empty order structure
        $order = Order::create([
            'order_number' => 'SB-TEST-002',
            'customer_name' => 'John Doe',
            'customer_phone' => '01712345678',
            'shipping_address' => 'Uttara, Dhaka',
            'subtotal' => 0.00,
            'shipping_cost' => 80.00,
            'grand_total' => 80.00,
            'payment_method' => 'cod',
            'payment_status' => 'pending',
            'status' => 'pending',
        ]);

        \Livewire\Livewire::test(\App\Filament\Resources\Orders\Pages\EditOrder::class, [
            'record' => $order->getKey(),
        ])
            ->assertFormSet([
                'subtotal' => '0.00',
                'grand_total' => '80.00',
            ])
            ->fillForm([
                'items' => [
                    [
                        'product_id' => $product1->id,
                        'quantity' => 2,
                        'price' => 100.00,
                    ]
                ],
                'shipping_cost' => 150.00,
                'discount_type' => 'percentage',
                'discount_value' => 10.00,
                'tax' => 15.00,
            ])
            ->assertFormSet([
                'subtotal' => 200.00,
                'shipping_cost' => 150.00,
                'discount_type' => 'percentage',
                'discount_value' => 10.00,
                'discount' => 20.00,
                'tax' => 15.00,
                'grand_total' => 345.00,
            ])
            ->fillForm([
                'discount_type' => 'fixed',
                'discount_value' => 25.00,
            ])
            ->assertFormSet([
                'discount' => 25.00,
                'grand_total' => 340.00,
            ]);
    }

    public function test_exchange_order_totals_are_calculated_dynamically()
    {
        $admin = User::create([
            'name' => 'Admin User',
            'email' => 'admin@sawdabazar.com',
            'password' => bcrypt('password123'),
            'role' => 'admin',
        ]);

        $product1 = Product::create([
            'name' => 'Product 1',
            'slug' => 'product-1',
            'sku' => 'P1',
            'price' => 1000.00,
            'quantity' => 10,
        ]);

        $parentOrder = Order::create([
            'order_number' => 'SB-PARENT',
            'customer_name' => 'John Doe',
            'customer_phone' => '01712345678',
            'shipping_address' => 'Uttara, Dhaka',
            'subtotal' => 1000.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1080.00,
            'status' => 'delivered',
        ]);

        $parentItem = $parentOrder->items()->create([
            'product_id' => $product1->id,
            'product_name' => 'Product 1',
            'product_sku' => 'P1',
            'price' => 1000.00,
            'quantity' => 1,
        ]);

        $exchangeOrder = Order::create([
            'order_number' => 'SB-EXCHANGE',
            'customer_name' => 'John Doe',
            'customer_phone' => '01712345678',
            'shipping_address' => 'Uttara, Dhaka',
            'subtotal' => 0.00,
            'discount' => 1000.00,
            'shipping_cost' => 80.00,
            'grand_total' => 80.00,
            'status' => 'pending',
            'is_exchange' => true,
            'parent_order_id' => $parentOrder->id,
        ]);

        $returnRequest = \App\Models\ReturnRequest::create([
            'order_id' => $parentOrder->id,
            'user_id' => $admin->id,
            'status' => 'completed',
            'type' => 'return',
            'reason' => 'size_issue',
            'exchange_order_id' => $exchangeOrder->id,
        ]);

        $returnRequest->items()->create([
            'order_item_id' => $parentItem->id,
            'quantity' => 1,
            'price' => 1000.00,
        ]);

        $this->actingAs($admin);
        \Livewire\Livewire::actingAs($admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        \Livewire\Livewire::test(\App\Filament\Resources\Orders\Pages\EditOrder::class, [
            'record' => $exchangeOrder->getKey(),
        ])
            ->assertFormSet([
                'subtotal' => '0.00',
                'discount' => '1000.00',
                'grand_total' => '80.00',
            ])
            ->fillForm([
                'items' => [
                    [
                        'product_id' => $product1->id,
                        'quantity' => 1,
                        'price' => 1000.00,
                    ]
                ],
                'shipping_cost' => 80.00,
                'discount_value' => 50.00,
            ])
            ->assertFormSet([
                'subtotal' => 1000.00,
                'discount' => 1050.00,
                'grand_total' => 30.00,
            ])
            ->fillForm([
                'items' => [
                    [
                        'product_id' => $product1->id,
                        'quantity' => 2,
                        'price' => 1000.00,
                    ]
                ],
                'shipping_cost' => 100.00,
                'discount_value' => 200.00,
            ])
            ->assertFormSet([
                'subtotal' => 2000.00,
                'discount' => 1200.00,
                'grand_total' => 900.00,
            ]);
    }

    public function test_exchange_order_displays_parent_and_child_order_links()
    {
        $admin = User::create([
            'name' => 'Admin User',
            'email' => 'admin@sawdabazar.com',
            'password' => bcrypt('password123'),
            'role' => 'admin',
        ]);

        $parentOrder = Order::create([
            'order_number' => 'SB-PARENT-LINK',
            'customer_name' => 'John Doe',
            'customer_phone' => '01712345678',
            'shipping_address' => 'Uttara, Dhaka',
            'subtotal' => 1000.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1080.00,
            'status' => 'delivered',
        ]);

        $exchangeOrder = Order::create([
            'order_number' => 'SB-EXCHANGE-LINK',
            'customer_name' => 'John Doe',
            'customer_phone' => '01712345678',
            'shipping_address' => 'Uttara, Dhaka',
            'subtotal' => 1000.00,
            'shipping_cost' => 80.00,
            'grand_total' => 1080.00,
            'status' => 'pending',
            'is_exchange' => true,
            'parent_order_id' => $parentOrder->id,
        ]);

        $this->actingAs($admin);
        \Livewire\Livewire::actingAs($admin);
        \Filament\Facades\Filament::setCurrentPanel(\Filament\Facades\Filament::getPanel('admin'));

        // 1. Mount exchange order edit page, verify it shows the parent order link
        \Livewire\Livewire::test(\App\Filament\Resources\Orders\Pages\EditOrder::class, [
            'record' => $exchangeOrder->getKey(),
        ])
            ->assertSee($parentOrder->order_number);

        // 2. Mount parent order edit page, verify it shows the child (exchange) order link
        \Livewire\Livewire::test(\App\Filament\Resources\Orders\Pages\EditOrder::class, [
            'record' => $parentOrder->getKey(),
        ])
            ->assertSee($exchangeOrder->order_number);
    }
}
