<?php

namespace Tests\Feature;

use App\Models\Admin;
use App\Models\Merchant;
use App\Models\PlatformOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Arr;
use Tests\TestCase;

class AdminDashboardPlatformOrderTrend7dDateShouldLinkToFilteredOrdersTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    public function test_dashboard_platform_order_trend_7d_date_should_link_to_filtered_orders(): void
    {
        $this->loginAsPlatformAdmin();

        $merchantId = (int) Merchant::query()->value('id');
        $platformAdminId = (int) Admin::query()->where('email', 'platform.admin@demo.local')->value('id');

        $po = PlatformOrder::query()->create([
            'merchant_id' => $merchantId,
            'plan_id' => null,
            'site_subscription_id' => null,
            'created_by_admin_id' => $platformAdminId ?: null,
            'order_no' => 'PO_TREND_LINK_D3',
            'order_type' => 'new_purchase',
            'status' => 'pending',
            'payment_status' => 'paid',
            'payable_amount' => 10,
            'paid_amount' => 10,
        ]);

        PlatformOrder::query()->where('id', $po->id)->update([
            'created_at' => now()->subDays(3)->startOfDay(),
            'updated_at' => now()->subDays(3)->startOfDay(),
        ]);

        $d3 = now()->subDays(3)->format('Y-m-d');

        $res = $this->get('/admin');
        $res->assertOk();

        $expectedUrl = '/admin/platform-orders?' . Arr::query([
            'created_from' => $d3,
            'created_to' => $d3,
            'back' => '/admin',
        ]);

        $res->assertSee('data-role="platform-order-trend-7d"', false);
        $res->assertSee($expectedUrl, false);
        $res->assertDontSee('&amp;back=', false);
    }
}
