<?php

namespace Tests\Feature;

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

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

        $res = $this->get('/admin/platform-orders?merchant_id=1&plan_id=2&back=/admin&page=2');
        $res->assertOk();

        $html = (string) $res->getContent();

        $re = '/<a[^>]*data-role="po-summary-link-total-orders"[^>]*href="([^"]+)"/u';
        $this->assertMatchesRegularExpression($re, $html);
        preg_match($re, $html, $m);

        $rawHref = (string) ($m[1] ?? '');
        $this->assertStringNotContainsString('&amp;back=', $rawHref);

        $href = html_entity_decode($rawHref);
        $query = parse_url($href, PHP_URL_QUERY) ?: '';
        parse_str($query, $q);

        $this->assertSame('1', (string) ($q['merchant_id'] ?? ''));
        $this->assertSame('2', (string) ($q['plan_id'] ?? ''));
        $this->assertSame('/admin', (string) ($q['back'] ?? ''));
        $this->assertArrayNotHasKey('page', $q);
    }
}
