<?php

namespace Database\Seeders;

use App\Models\Association;
use App\Models\City;
use App\Models\Org;
use App\Models\State;
use App\Models\User;
use Illuminate\Database\Seeder;

class AssociationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get the first organization (or create one if none exists)
        $org = Org::first() ?? Org::create(['name' => 'مؤسسة سدو']);

        // Get some states and cities (assuming they exist from LocationSeeder)
        $states = State::limit(3)->get();
        $cities = City::limit(5)->get();

        // Get or create some users to be representatives
        $users = User::limit(3)->get();
        if ($users->count() < 3) {
            // Create additional users if we don't have enough
            $existingEmails = $users->pluck('email')->toArray();
            $newUsers = [];

            $userData = [
                ['name' => 'Ahmed Al-Mansouri', 'email' => 'ahmed@example.com', 'phone' => '+966501234567'],
                ['name' => 'Fatima Al-Zahra', 'email' => 'fatima@example.com', 'phone' => '+966502345678'],
                ['name' => 'Mohammed Al-Rashid', 'email' => 'mohammed@example.com', 'phone' => '+966503456789'],
            ];

            foreach ($userData as $user) {
                if (! in_array($user['email'], $existingEmails)) {
                    $newUsers[] = User::create([
                        'name' => $user['name'],
                        'email' => $user['email'],
                        'phone' => $user['phone'],
                        'password' => bcrypt('password'),
                    ]);
                }
            }

            $users = $users->merge($newUsers)->take(3);
        }

        $associations = [
            [
                'name' => 'جمعية الخير لرعاية الأيتام',
                'license_number' => 'LIC-2024-001',
                'license_expiration_date' => now()->addYears(2),
                'city' => 'الرياض',
                'street' => 'شارع الملك فهد',
                'district' => 'العليا',
                'postal_code' => '11564',
                'building_number' => '123',
                'secondary_number' => '456',
                'lat' => 24.7136,
                'lng' => 46.6753,
                'iban' => 'SA0380000000608010167519',
                'bank_name' => 'البنك الأهلي السعودي',
                'account_holder_name' => 'جمعية الخير لرعاية الأيتام',
                'is_verified' => true,
                'is_locked' => false,
                'user_id' => $users[0]->id,
                'org_id' => $org->id,
            ],
            [
                'name' => 'جمعية التنمية الاجتماعية',
                'license_number' => 'LIC-2024-002',
                'license_expiration_date' => now()->addYears(3),
                'city' => 'جدة',
                'street' => 'شارع الأمير سلطان',
                'district' => 'الحمراء',
                'postal_code' => '21451',
                'building_number' => '789',
                'secondary_number' => '101',
                'lat' => 21.4858,
                'lng' => 39.1925,
                'iban' => 'SA0380000000608010167520',
                'bank_name' => 'بنك الراجحي',
                'account_holder_name' => 'جمعية التنمية الاجتماعية',
                'is_verified' => true,
                'is_locked' => false,
                'user_id' => $users[1 % $users->count()]->id,
                'org_id' => $org->id,
            ],
            [
                'name' => 'جمعية الرحمة الخيرية',
                'license_number' => 'LIC-2024-003',
                'license_expiration_date' => now()->addYear(),
                'city' => 'الدمام',
                'street' => 'شارع الخليج العربي',
                'district' => 'الشاطئ',
                'postal_code' => '31411',
                'building_number' => '456',
                'secondary_number' => '789',
                'lat' => 26.4207,
                'lng' => 50.0888,
                'iban' => 'SA0380000000608010167521',
                'bank_name' => 'البنك السعودي للاستثمار',
                'account_holder_name' => 'جمعية الرحمة الخيرية',
                'is_verified' => false,
                'is_locked' => false,
                'user_id' => $users[2 % $users->count()]->id,
                'org_id' => $org->id,
            ],
            [
                'name' => 'جمعية نماء للتطوير المجتمعي',
                'license_number' => 'LIC-2024-004',
                'license_expiration_date' => now()->addYears(2)->addMonths(6),
                'city' => 'مكة المكرمة',
                'street' => 'شارع إبراهيم الخليل',
                'district' => 'العزيزية',
                'postal_code' => '21955',
                'building_number' => '321',
                'secondary_number' => '654',
                'lat' => 21.3891,
                'lng' => 39.8579,
                'iban' => 'SA0380000000608010167522',
                'bank_name' => 'بنك سامبا',
                'account_holder_name' => 'جمعية نماء للتطوير المجتمعي',
                'is_verified' => true,
                'is_locked' => false,
                'user_id' => $users[0]->id,
                'org_id' => $org->id,
            ],
            [
                'name' => 'جمعية البناء الخيرية',
                'license_number' => 'LIC-2024-005',
                'license_expiration_date' => now()->addMonths(8),
                'city' => 'المدينة المنورة',
                'street' => 'شارع قباء',
                'district' => 'قباء',
                'postal_code' => '42351',
                'building_number' => '147',
                'secondary_number' => '258',
                'lat' => 24.5247,
                'lng' => 39.5692,
                'iban' => 'SA0380000000608010167523',
                'bank_name' => 'البنك الأهلي التجاري',
                'account_holder_name' => 'جمعية البناء الخيرية',
                'is_verified' => false,
                'is_locked' => true,
                'user_id' => $users[1 % $users->count()]->id,
                'org_id' => $org->id,
            ],
        ];

        foreach ($associations as $associationData) {
            $association = Association::create($associationData);

            // Attach random states and cities to the association
            if ($states->isNotEmpty()) {
                $association->states()->attach($states->random(rand(1, 2))->pluck('id'));
            }

            if ($cities->isNotEmpty()) {
                $association->cities()->attach($cities->random(rand(1, 3))->pluck('id'));
            }
        }

        $this->command->info('تم إنشاء '.count($associations).' جمعية');
    }
}
