<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Arr;
use Tests\TestCase;

class AdminPlatformOrderIndexClearLeadFilterLinkTest 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_index_should_render_clear_lead_filter_link_when_lead_id_present(): void
    {
        $this->loginAsPlatformAdmin();

        $url = '/admin/platform-orders?' . Arr::query([
            'lead_id' => 12,
            'payment_status' => 'paid',
            'page' => 3,
        ]);

        $res = $this->get($url);
        $res->assertOk();

        $html = $res->getContent();

        $res->assertSee('清除线索筛选', false);

        preg_match_all('/href="([^"]+)"/', $html, $matches);
        $hrefs = $matches[1] ?? [];

        $clearUrls = array_values(array_filter($hrefs, fn ($u) => str_contains($u, '清除') === false && str_contains($u, '/admin/platform-orders')));

        // 在所有 href 中找一个不带 lead_id、不带 page，但仍保留 payment_status 的链接
        $found = false;
        foreach ($hrefs as $u) {
            if (!str_contains($u, '/admin/platform-orders')) {
                continue;
            }
            $parts = parse_url($u);
            parse_str($parts['query'] ?? '', $q);

            if (!isset($q['lead_id'])
                && !isset($q['page'])
                && ($q['payment_status'] ?? '') === 'paid') {
                $found = true;
                break;
            }
        }

        $this->assertTrue($found, '未找到正确的“清除线索筛选”链接（应移除 lead_id/page 并保留其它筛选）');
    }
}
