<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class MembershipSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Create sample branches if they don't exist
        $branches = \App\Models\Branch::firstOrCreate(
            ['name' => 'Nairobi Main Branch'],
            ['location' => 'Koinange Street, Nairobi', 'description' => 'Main branch located in the heart of Nairobi CBD']
        );

        \App\Models\Branch::firstOrCreate(
            ['name' => 'Westlands Branch'],
            ['location' => 'Westlands, Nairobi', 'description' => 'Modern branch serving the Westlands business district']
        );

        // Create sample users if they don't exist
        $users = [
            [
                'name' => 'John Doe',
                'first_name' => 'John',
                'second_name' => 'Doe',
                'phone_number' => '+254700000001',
                'id_number' => '12345678',
                'email' => 'john.doe@example.com',
                'password' => bcrypt('password'),
                'branch_id' => $branches->id,
            ],
            [
                'name' => 'Jane Smith',
                'first_name' => 'Jane',
                'second_name' => 'Smith',
                'phone_number' => '+254700000002',
                'id_number' => '87654321',
                'email' => 'jane.smith@example.com',
                'password' => bcrypt('password'),
                'branch_id' => $branches->id,
            ],
            [
                'name' => 'Michael Johnson',
                'first_name' => 'Michael',
                'second_name' => 'Johnson',
                'phone_number' => '+254700000003',
                'id_number' => '11223344',
                'email' => 'michael.johnson@example.com',
                'password' => bcrypt('password'),
                'branch_id' => $branches->id,
            ],
        ];

        foreach ($users as $userData) {
            $user = \App\Models\User::firstOrCreate(
                ['email' => $userData['email']],
                $userData
            );

            // Create membership for each user if it doesn't exist
            \App\Models\Membership::firstOrCreate(
                ['user_id' => $user->id],
                [
                    'membership_number' => 'MS' . str_pad($user->id, 6, '0', STR_PAD_LEFT),
                    'joining_date' => now()->subDays(rand(1, 365)),
                    'status' => 'active',
                    'share_capital' => rand(1000, 50000),
                    'savings_balance' => rand(5000, 100000),
                    'notes' => 'Auto-generated membership',
                ]
            );
        }
    }
}
