<?php
declare(strict_types=1);

namespace Tests\Factories;

final class MemberFactory extends Factory
{
    private static int $sequence = 0;

    protected function table(): string
    {
        return 'members';
    }

    protected function defaults(): array
    {
        self::$sequence++;
        $nid = '2990101' . str_pad((string) self::$sequence, 7, '0', STR_PAD_LEFT);

        return [
            'branch_id' => $this->getOrCreateBranchId(),
            'full_name_ar' => 'عضو اختبار ' . self::$sequence,
            'full_name_en' => 'Test Member ' . self::$sequence,
            'national_id' => $nid,
            'date_of_birth' => '1990-01-01',
            'gender' => 'male',
            'phone_mobile' => '0100' . str_pad((string) self::$sequence, 7, '0', STR_PAD_LEFT),
            'membership_type' => 'working',
            'member_category' => 'working_member',
            'status' => 'active',
            'is_archived' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
    }

    private function getOrCreateBranchId(): int
    {
        $branch = $this->db->selectOne("SELECT id FROM branches WHERE is_active = 1 LIMIT 1");
        if ($branch) {
            return (int) $branch['id'];
        }

        return (new BranchFactory($this->db))->create()['id'];
    }
}
