<?php

namespace Database\Seeders;

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Faker\Factory;
class MemberSeeder extends Seeder
{
    public function run(): void
    {
        DB::disableQueryLog();
        Model::unsetEventDispatcher();

        $chunkSize = 100;
        $tableName = 'members';
        $faker = Factory::create();
        $hashedPassword = Hash::make('password');
        $now = CarbonImmutable::now();
        $startDate = $now->subMonths(18);

        $addresses = ['Riyadh - Al Olaya', 'Jeddah - Al Hamra', 'Dammam - Al Faisaliyah', 'Riyadh - Al Malaz', 'Jeddah - Al Rawdah'];

        $total = 500;
        $rows = [];

        for ($i = 0; $i < $total; $i++) {
            $firstName =  $faker->firstName;
            $lastName = $faker->lastName;
            $name = $firstName . ' ' . $lastName;

            $createdAt = CarbonImmutable::createFromTimestamp(
                rand($startDate->timestamp, $now->timestamp)
            )->setTime(12, 0, 0);

            $status = [1, 2, 2, 2][array_rand([1, 2, 2, 2])];
            $memberType = rand(1, 2);
            $startSub = $createdAt->addDays(rand(0, 5));
            $endSub = rand(0, 10) > 2 ? $startSub->addMonths(rand(6, 24)) : null;

            $rows[] = [
                'name'                    => 'm' . '-' . $name,
                'phone'                   => '05' . str_pad(10000000 + $i, 8, '0', STR_PAD_LEFT),
                'dob'                     => $createdAt->subYears(rand(18, 55))->format('Y-m-d'),
                'address'                 => $addresses[array_rand($addresses)],
                'email'                   => strtolower(str_replace(' ', '.', $name)) . $i . '@example.com',
                'status'                  => $status,
                'member_type'             => $memberType,
                'start_date_subscription' => $startSub->format('Y-m-d'),
                'end_date_subscription'   => $endSub?->format('Y-m-d'),
                'qr_code'                 => 'MC-' . $now->year . '-' . (1000000 + $i),
                'password'                => $hashedPassword,
                'created_at'              => $createdAt->format('Y-m-d H:i:s'),
                'updated_at'              => $createdAt->format('Y-m-d H:i:s'),
            ];

            if (count($rows) >= $chunkSize) {
                DB::table($tableName)->insert($rows);
                $rows = [];
            }
        }

        if (!empty($rows)) {
            DB::table($tableName)->insert($rows);
        }

        $this->command->info("Members seeded: {$total} records");
    }
}
