<?php

namespace Tests\Feature;

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

class ToolsAndContactTest extends TestCase
{
    use RefreshDatabase;

    public function test_calculator_pages_render(): void
    {
        foreach (['budget', 'debt-payoff', 'compound-growth', 'emergency-fund', 'wealth-goals', 'loan-cost', 'retirement', 'values-clarification'] as $tool) {
            $this->get("/tools/{$tool}")->assertOk();
        }

        $this->get('/tools/budget')->assertSee('Budget Builder')->assertSee('Add item')->assertSee('How it works');
        $this->get('/tools/debt-payoff')
            ->assertSee('Minimum payments still matter')
            ->assertSee('Interest changes the answer')
            ->assertSee('Save before you leave')
            ->assertSee('Set a goal')
            ->assertSee('beforeunload');
        $this->get('/tools/retirement')->assertSee('How it works')->assertSee('Quick guide', false);
        $this->get('/tools/not-a-tool')->assertNotFound();
    }

    public function test_debt_education_page_covers_updated_guidance(): void
    {
        $this->get('/debt')
            ->assertOk()
            ->assertSee('Unmanaged debt can quietly cancel your investments')
            ->assertSee('Save first')
            ->assertSee('Clear toxic debt')
            ->assertSee('The real cost is not only interest')
            ->assertSee('Avoid the traps that restart the cycle')
            ->assertSee('Borrowing to invest before the repayment plan is stable.');
    }

    public function test_budget_tool_pdf_and_save(): void
    {
        // PDF endpoint accepts the budget payload schema.
        $this->post('/tools/budget/pdf', [
            'currency' => 'KES',
            'highlight' => ['value' => 'KES 10,000', 'label' => 'Left to allocate this month'],
            'sections' => [
                ['title' => 'Income', 'rows' => [['Monthly take-home', 'KES 80,000']]],
            ],
            'note' => 'Set up standing orders.',
        ])->assertOk()->assertHeader('content-type', 'application/pdf');

        // Saving creates a tool_result + lead for guests.
        $this->postJson('/tools/budget/save', [
            'email' => 'budgeter@example.com',
            'label' => 'Monthly budget',
            'inputs' => ['income' => 80000, 'cats' => ['housing' => 18000]],
            'outputs' => ['remaining' => 10000, 'savingsRate' => 11],
        ])->assertOk()->assertJson(['saved' => true]);

        $this->assertDatabaseHas('tool_results', ['tool' => 'budget', 'label' => 'Monthly budget']);
        $this->assertDatabaseHas('leads', ['email' => 'budgeter@example.com', 'source' => 'tool:budget']);
    }

    public function test_guest_saves_tool_plan_with_email_and_lead_is_created(): void
    {
        $this->postJson('/tools/debt-payoff/save', [
            'email' => 'saver@example.com',
            'label' => 'My plan',
            'inputs' => ['debts' => [], 'strategy' => 'snowball', 'extra' => 2000],
            'outputs' => ['months' => 14],
        ])->assertOk()->assertJson(['saved' => true]);

        $this->assertDatabaseHas('tool_results', ['tool' => 'debt-payoff', 'label' => 'My plan']);
        $this->assertDatabaseHas('leads', ['email' => 'saver@example.com', 'source' => 'tool:debt-payoff']);
    }

    public function test_authenticated_user_saves_plan_without_email(): void
    {
        $user = User::factory()->create();

        $this->actingAs($user)->postJson('/tools/emergency-fund/save', [
            'inputs' => ['expenses' => 40000, 'months' => 6],
            'outputs' => ['target' => 240000],
        ])->assertOk();

        $this->assertDatabaseHas('tool_results', ['tool' => 'emergency-fund', 'user_id' => $user->id]);
        $this->assertDatabaseCount('leads', 0);
    }

    public function test_coaching_and_speaking_pages_render(): void
    {
        $this->get('/coaching')->assertOk()->assertSee('What is coaching');
        $this->get('/speaking')->assertOk()->assertSee('Send booking request');
    }

    public function test_speaker_booking_creates_inquiry(): void
    {
        $this->post('/contact', [
            'type' => 'speaking',
            'name' => 'Event Organiser',
            'email' => 'events@company.co.ke',
            'organization' => 'Acme Ltd',
            'message' => "SPEAKER BOOKING REQUEST\nEvent: Annual Summit\nFormat: Keynote",
        ])->assertRedirect();

        $this->assertDatabaseHas('inquiries', ['type' => 'speaking', 'email' => 'events@company.co.ke']);
    }

    public function test_contact_form_stores_inquiry(): void
    {
        $this->post('/contact', [
            'type' => 'corporate',
            'name' => 'Jane HR',
            'email' => 'jane@company.co.ke',
            'organization' => 'Acme Ltd',
            'message' => 'We would like a staff wellness programme.',
        ])->assertRedirect();

        $this->assertDatabaseHas('inquiries', [
            'type' => 'corporate',
            'email' => 'jane@company.co.ke',
            'status' => 'new',
        ]);
    }

    public function test_contact_form_rejects_invalid_type(): void
    {
        $this->from('/contact')->post('/contact', [
            'type' => 'hacking',
            'name' => 'X',
            'email' => 'x@x.com',
            'message' => 'hi',
        ])->assertSessionHasErrors('type');
    }
}
