<?php

namespace Tests\Feature;

use App\Models\Branch;
use App\Models\MessageTemplate;
use App\Models\SchoolClass;
use App\Models\Student;
use App\Models\User;
use App\Support\SiblingDiscount;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * Sibling fee-discount policy, trilingual WhatsApp bodies, and CRM template CRUD.
 */
class FinanceCrmTest extends TestCase
{
    use RefreshDatabase;

    private Branch $branch;
    private SchoolClass $class;

    protected function setUp(): void
    {
        parent::setUp();
        $this->branch = Branch::create(['name' => 'Main', 'code' => 'MC', 'is_active' => true]);
        $this->class = SchoolClass::create(['name' => 'Grade 3 - A', 'branch_id' => $this->branch->id, 'level' => 3, 'section' => 'A']);
        $this->actingAs(User::create(['name' => 'Admin', 'email' => 'a@t.local', 'password' => bcrypt('x'), 'role' => 'super-admin', 'is_active' => true]));
    }

    public function test_sibling_discount_frees_one_child_in_a_family_of_three(): void
    {
        // Three siblings share one father → a qualifying household (min 3).
        $ids = [];
        foreach ([1, 2, 3] as $i) {
            $ids[] = Student::create([
                'branch_id' => $this->branch->id, 'class_id' => $this->class->id,
                'first_name' => 'Child', 'last_name' => "Karimi", 'gender' => 'male',
                'admission_number' => "ADM-$i", 'status' => 'active',
                'father_name' => 'Ahmad Karimi', 'father_mobile' => '0788112233',
            ])->id;
        }
        // A lone child in a different family must NOT qualify.
        $lone = Student::create([
            'branch_id' => $this->branch->id, 'class_id' => $this->class->id,
            'first_name' => 'Solo', 'last_name' => 'Noori', 'gender' => 'female',
            'admission_number' => 'ADM-9', 'status' => 'active', 'father_mobile' => '0700000000',
        ])->id;

        $discounts = SiblingDiscount::forAll();

        $family = array_intersect_key($discounts, array_flip($ids));
        $this->assertCount(1, $family, 'Exactly one child should be free in free_one mode.');
        $free = reset($family);
        $this->assertSame(100, $free['percent']);
        $this->assertSame('free', $free['reason']);
        $this->assertSame(3, $free['family_size']);
        $this->assertArrayNotHasKey($lone, $discounts);
    }

    public function test_message_template_stacks_three_languages(): void
    {
        $tpl = MessageTemplate::create([
            'name' => 'Arrival', 'body_fa' => 'سلام فارسی', 'body_ps' => 'سلام پښتو', 'body_en' => 'Hello English', 'active' => true,
        ]);

        $all = $tpl->bodyAll();
        $this->assertStringContainsString('سلام فارسی', $all);
        $this->assertStringContainsString('سلام پښتو', $all);
        $this->assertStringContainsString('Hello English', $all);
        // Persian must come before Pashto before English.
        $this->assertTrue(strpos($all, 'سلام فارسی') < strpos($all, 'سلام پښتو'));
        $this->assertTrue(strpos($all, 'سلام پښتو') < strpos($all, 'Hello English'));

        // composed() returns the stacked body when trilingual is on (default).
        $this->assertSame($all, $tpl->composed());
    }

    public function test_crm_template_crud(): void
    {
        $this->postJson('/api/crm/templates', [
            'name' => 'Fee reminder', 'category' => 'fees',
            'body_fa' => 'یادآوری', 'body_ps' => 'یادونه', 'body_en' => 'Reminder', 'active' => true,
        ])->assertSuccessful();

        $this->getJson('/api/crm/templates')->assertOk()->assertJsonFragment(['name' => 'Fee reminder']);
        $this->assertDatabaseHas('message_templates', ['name' => 'Fee reminder', 'body_en' => 'Reminder']);
    }
}
