<?php

namespace Tests\Feature\Admin;

use App\Models\Order;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DashboardAndReportsTest extends TestCase
{
    use RefreshDatabase;

    private function order(array $overrides = []): Order
    {
        return Order::create(array_merge([
            'order_number' => 'NYR-'.uniqid(), 'customer_name' => 'x', 'customer_phone' => 'x',
            'shipping_address' => 'x', 'shipping_city' => 'x', 'shipping_area' => 'x',
            'subtotal' => 1000, 'shipping_charge' => 0, 'grand_total' => 1000,
            'payment_method' => 'cod', 'payment_status' => 'pending', 'order_status' => 'confirmed',
        ], $overrides));
    }

    public function test_customer_cannot_access_dashboard_or_reports(): void
    {
        $customer = $this->customer();

        $this->actingAs($customer)->get('/admin')->assertForbidden();
        $this->actingAs($customer)->get('/admin/reports')->assertForbidden();
    }

    public function test_admin_sees_dashboard_with_chart_data(): void
    {
        $this->order(['grand_total' => 1500]);

        $response = $this->actingAs($this->admin())->get('/admin');

        $response->assertOk();
        $response->assertSee('Sales — Last 30 Days');
        $response->assertSee('salesTrendChart', false);
    }

    public function test_admin_can_view_reports_with_default_and_custom_date_range(): void
    {
        $admin = $this->admin();
        $this->order(['grand_total' => 2000]);

        $this->actingAs($admin)->get('/admin/reports')->assertOk();

        $this->actingAs($admin)
            ->get('/admin/reports?from='.now()->subDays(5)->format('Y-m-d').'&to='.now()->format('Y-m-d'))
            ->assertOk();
    }

    public function test_invalid_date_range_is_rejected(): void
    {
        $response = $this->actingAs($this->admin())->get('/admin/reports?from=2026-01-10&to=2026-01-01');

        $response->assertSessionHasErrors('to');
    }

    public function test_reports_export_returns_csv_with_expected_rows(): void
    {
        $order = $this->order(['grand_total' => 2500]);

        $response = $this->actingAs($this->admin())->get('/admin/reports/export');

        $response->assertOk();
        $response->assertHeader('content-type', 'text/csv; charset=UTF-8');
        $content = $response->streamedContent();
        $this->assertStringContainsString($order->order_number, $content);
        $this->assertStringContainsString('2500', $content);
    }
}
