<?php

namespace Tests\Tenant;

use App\Crm\SendCopyViaMail;
use App\Facades\Settings;
use App\Mail\NewEnquiryMail;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Mail;
use Mtc\Crm\Facades\Enquiries;
use Mtc\Crm\Models\EnquiryAction;
use Mtc\Crm\Models\FormAction;
use Mtc\Crm\Models\FormQuestion;
use Mtc\Crm\Models\FormSection;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Enquiry;
use Mtc\MercuryDataModels\Form;
use Mtc\MercuryDataModels\Property;
use Mtc\MercuryDataModels\PropertyCategory;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class EnquiryRepositoryTest extends TenantTestCase
{
    use UserForTenant;

    public function testShowList()
    {
        Enquiry::factory(10)->create();
        $list = Enquiries::showList(\request());
        $this->assertInstanceOf(LengthAwarePaginator::class, $list);
        $this->assertEquals(10, $list->total());
    }


    public function testShowEditUrl()
    {
        $enquiry = \Mtc\Crm\Models\Enquiry::factory()->create([
            'title' => 'foo',
            'reason_type' => 'vehicle',
            'reason_id' => 123
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->get(route('enquiries.details', $enquiry->id));
        $this->assertStringContainsString('vehicles', $response->json('reason_url'));

        $enquiry = \Mtc\Crm\Models\Enquiry::factory()->create([
            'title' => 'foo',
            'reason_type' => 'new-car',
            'reason_id' => 123
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->get(route('enquiries.details', $enquiry->id));
        $this->assertStringContainsString('new-vehicles', $response->json('reason_url'));

        $enquiry = \Mtc\Crm\Models\Enquiry::factory()->create([
            'title' => 'foo',
            'reason_type' => 'offer',
            'reason_id' => 123
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->get(route('enquiries.details', $enquiry->id));
        $this->assertStringContainsString('offers', $response->json('reason_url'));

        $enquiry = \Mtc\Crm\Models\Enquiry::factory()->create([
            'title' => 'foo',
            'reason_type' => 'valuation',
            'reason_id' => 123
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->get(route('enquiries.details', $enquiry->id));
        $this->assertStringContainsString('valuations', $response->json('reason_url'));

        $category = PropertyCategory::factory()->create(['slug' => 'foo']);
        $property = Property::factory()->create(['slug' => 'baz', 'category_id' => $category->id]);

        $enquiry = \Mtc\Crm\Models\Enquiry::factory()->create([
            'title' => 'foo',
            'reason_type' => 'property',
            'reason_id' => $property->id
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->get(route('enquiries.details', $enquiry->id));
        $this->assertStringContainsString('properties/foo/edit/' .$property->id, $response->json('reason_url'));
    }

    public function testEnquiryDealershipRecipients()
    {
        // setup
        Mail::fake();

        Settings::make([
            'tab' => 'foo-baz',
            'section' => 'lorem',
            'group' => 'ipsum',
            'name' => 'dolor',
            'type' => 'image',
            'config_key' => 'site-logo'
        ]);

        Dealership::factory()->create([
            'id' => 4,
        ]);

        $form = Form::factory()->create();
        $section = FormSection::factory()->create(['form_id' => $form->id]);

        $form_question = FormQuestion::factory()->create([
            'form_id' => $form->id,
            'form_section_id' => $section->id,
            "name" => "Dealership",
            'data' => [
                "component" => false,
                "componentName" => false,
                "meta" => null,
                "name" => "Dealership",
                "type" => "dealership_id",
                'specifies-recipient' => true,
                "field-emails-specification" => "4:recipient1@test.com"
            ],
        ]);

        FormAction::factory()->create([
            'form_id' => $form->id,
            "action_name" => "send-copy-via-mail",
            "fields" => [
                "send_to_field_location" => null,
                "send_to_both" => false,
                "recipient" => "fallback@test.com",
                "enquiry_subject" => "Vehicle Enquiry",
                "enquiry_content" => "A new vehicle enquiry has been submitted on the website."
            ],
        ]);

        $form->refresh();

        // this works with 'answer' => 4,
        // also works with string i.e. 'answer' => '4',
        $details = [
            (string)$form_question->id => [
                'id' => $form_question->id,
                'answer' => 4,
                'question' => $form_question->name,
                "type" => "dealership_id",
                'value' => 'my dealership name',
            ],
        ];

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => $details,
            'data' => [
                'questions' => [
                    (string)$form_question->id => [
                        'component' => 'TextField',
                        'componentName' => 'TextField',
                        'meta' => null,
                    ],
                ],
            ],
        ]);

        $action = EnquiryAction::factory()->create([
            'enquiry_id' => $enquiry->id,
            'action_name' => 'send-copy-via-mail',
            'data' => [
                'send_to_field_location' => null,
                'send_to_both' => false,
                'recipient' => 'fallback@test.com',
                'enquiry_subject' => 'my enquiry subject',
                'enquiry content' => 'lorem ipsum',
            ],
            'processed_at' => null,
            'attempts' => 0,
            'failed_at' => null,
        ]);

        $enquiry->refresh();

        (new SendCopyViaMail())->handle($action, $enquiry);

        Mail::assertSent(NewEnquiryMail::class, function (NewEnquiryMail $mail) {
            return $mail->assertTo('recipient1@test.com');
        });
    }

    public function testEnquiryRecipientField()
    {
        // setup
        Mail::fake();

        Settings::make([
            'tab' => 'foo-baz',
            'section' => 'lorem',
            'group' => 'ipsum',
            'name' => 'dolor',
            'type' => 'image',
            'config_key' => 'site-logo'
        ]);

        $form = Form::factory()->create();
        $section = FormSection::factory()->create(['form_id' => $form->id]);

        $form_question = FormQuestion::factory()->create([
            'form_id' => $form->id,
            'form_section_id' => $section->id,
            "name" => "Foo",
            'data' => [
                "component" => false,
                "componentName" => false,
                "meta" => null,
                "name" => "Foo",
                "type" => "foo",
            ],
        ]);

        FormAction::factory()->create([
            'form_id' => $form->id,
            "action_name" => "send-copy-via-mail",
            "fields" => [
                "send_to_field_location" => 'foo',
                "send_to_both" => false,
                "recipient" => "fallback@test.com",
                "enquiry_subject" => "Vehicle Enquiry",
                "enquiry_content" => "A new vehicle enquiry has been submitted on the website."
            ],
        ]);

        $form->refresh();

        $details = [
            (string)$form_question->id => [
                'id' => $form_question->id,
                'answer' => 'question.recipient@test.com',
                'question' => $form_question->name,
                "type" => "recipient",
                'value' => 'question.recipient@test.com',
            ],
        ];

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => $details,
            'data' => [
                'questions' => [
                    (string)$form_question->id => [
                        'component' => 'TextField',
                        'componentName' => 'TextField',
                        'meta' => null,
                    ],
                ],
            ],
        ]);

        $action = EnquiryAction::factory()->create([
            'enquiry_id' => $enquiry->id,
            'action_name' => 'send-copy-via-mail',
            'data' => [
                'send_to_field_location' => 'Foo',
                'send_to_both' => false,
                'recipient' => 'fallback@test.com',
                'enquiry_subject' => 'my enquiry subject',
                'enquiry content' => 'lorem ipsum',
            ],
            'processed_at' => null,
            'attempts' => 0,
            'failed_at' => null,
        ]);

        $enquiry->refresh();

        (new SendCopyViaMail())->handle($action, $enquiry);

        Mail::assertSent(NewEnquiryMail::class, function (NewEnquiryMail $mail) {
            return $mail->assertTo('question.recipient@test.com');
        });
    }
}
