<?php

namespace Database\Seeders;

use App\Models\Customer;
use App\Models\Settings\RegionalSettings\Nationality;
use App\Models\User;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class CustomerSeeder extends Seeder
{
    public function run(): void
    {
        $faker = Faker::create();
        $nationalities = Nationality::all();
        $coaches = User::where('role', 'coach')->get();
        $registrationDate = now();

        $count = 50;

        $lastCustomer = Customer::whereYear('registration_date', $registrationDate->format('Y'))
            ->orderBy('id', 'desc')
            ->first();

        $lastNumber = $lastCustomer ? (int) substr($lastCustomer->code, -3) : 0;

        for ($i = $lastNumber + 1; $i <= $lastNumber + $count; $i++) {

            $gender = $faker->randomElement([1, 2]);

            $birthDate = $faker->dateTimeBetween('18 years', '60 years');
            $age = now()->diffInYears($birthDate);

            $height = $faker->numberBetween(150, 190); // cm
            $weight = $faker->numberBetween(50, 100); // kg
            $bmi = $weight / (($height / 100) ** 2);

            Customer::create([
                'code' => 'MEM-' . $registrationDate->format('Y') . '-' . str_pad($i, 3, '0', STR_PAD_LEFT),
                'name' => $gender == 1 ? $faker->name('male') : $faker->name('female'),
                'email' => $faker->unique()->safeEmail,
                'phone' => '05' . $faker->numberBetween(10000000, 99999999),
                'gender' => $gender,
                'birth_date' => $birthDate->format('Y-m-d'),
                'age' => $age,
                'height' => $height,
                'weight' => $weight,
                'bmi' => round($bmi, 2),
                'national_id' => $faker->unique()->numberBetween(1000000000, 9999999999),
                'nationality_id' => $nationalities->random()->id ?? null,
                'occupation' => $faker->randomElement(['موظف', 'طالب', 'طبيب', 'مهندس', 'معلم', 'رجل أعمال', 'ربة منزل']),
                'address' => $faker->address,
                'blood_type' => $faker->randomElement(['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']),
                'medical_conditions' => $faker->optional(0.3)->text(200),
                'emergency_contact' => '05' . $faker->numberBetween(10000000, 99999999),
                'registration_date' => $registrationDate->format('Y-m-d'),
                'avatar' => null,
                'assigned_coach_id' => $coaches->random()->id ?? null,
                'is_active' => true,
                'created_by' => 1,
            ]);
        }
    }
}
