<?php

namespace Database\Seeders;

use App\Domain\Identity\Models\Role;
use App\Domain\Shared\Models\Academy;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $academy = Academy::firstOrCreate(
            ['slug' => 'el-captain'],
            [
                'name' => 'El Captain Academy',
                'name_ar' => 'أكاديمية الكابتن',
                'slug' => 'el-captain',
                'email' => 'info@elcaptain.com',
                'currency' => 'EGP',
                'timezone' => 'Africa/Cairo',
                'locale' => 'ar',
                'status' => 'active',
            ]
        );

        $admin = User::firstOrCreate(
            ['email' => 'admin@oc-sport.com'],
            [
                'academy_id' => $academy->id,
                'name' => 'Mahmoud Aglan',
                'name_ar' => 'محمود عجلان',
                'email' => 'admin@oc-sport.com',
                'password' => Hash::make('Alarcade123#'),
                'status' => 'active',
            ]
        );

        $this->call(FinancialAccountsSeeder::class);
        $this->call(RolesAndPermissionsSeeder::class);
        $this->call(PermissionSeeder::class);
        $this->call(PaymentNotificationTemplateSeeder::class);

        // Assign academy_owner role to the admin user
        $ownerRole = Role::where('academy_id', $academy->id)
            ->where('slug', 'academy_owner')
            ->first();

        if ($ownerRole) {
            $admin->update(['role_id' => $ownerRole->id, 'is_super_admin' => true]);
            if (!$admin->roles()->where('role_id', $ownerRole->id)->exists()) {
                $admin->roles()->attach($ownerRole->id);
            }
        }
    }
}
