<?php

namespace Database\Factories;

use App\Models\LocalizationManagement\City;
use App\Models\LocalizationManagement\Country;
use App\Models\LocalizationManagement\Quarter;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\User;
use App\Models\LocalizationManagement\Address;
use Illuminate\Database\Eloquent\Factories\Factory;

class UserAddressFactory extends Factory{

    protected $model = Address::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition(){
        $ksa   = Country::with('states')->whereId(194)->first();
        $state = $ksa->states->random()->id;
        $city = City::whereStateId($state)->inRandomOrder()->first()->id;
        $quarter = Quarter::whereCityId($city)->inRandomOrder()->first()->id;


        return [
           // "customer_id" => User::factory(),
            'title' => $this->faker->randomElement(['Home', 'Work', 'Father', 'Mother']),
            'default' => rand(0, 1),
            'contact_full_name' => $this->faker->name,
            'email' => $this->faker->safeEmail,
            'phone' => $this->faker->phoneNumber,
            'address' => $this->faker->streetAddress,
            'address2' => $this->faker->address,
            'country_id' => $ksa->id,
            'state_id' => $state,
            'city_id' => $city,
            'quarter_id' => $quarter,
            'zip_code' => $this->faker->postcode,
            'po_box' => $this->faker->numberBetween(1000, 9999),
        ];
    }



    public function configure(){
        return $this->afterCreating(function (Address $address) {
            if (empty($address->customer_id)){
                  $users = Customer::get()->pluck("id")->toArray();
                  $userId = (blank($users)) ? Customer::factory() : fake()->randomElement($users);
                  $address->update(["customer_id" => $userId]);
            }
        });
    }
}
