<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        $permissions = [
            ['name' => 'expenses.create', 'module' => 'expenses', 'action' => 'create'],
            ['name' => 'expenses.list', 'module' => 'expenses', 'action' => 'list'],
            ['name' => 'expenses.view', 'module' => 'expenses', 'action' => 'view'],
        ];

        foreach ($permissions as $perm) {
            DB::table('permissions')->insertOrIgnore([
                'name' => $perm['name'],
                'module' => $perm['module'],
                'action' => $perm['action'],
                'created_at' => now(),
            ]);
        }

        // Also seed the 5050 account if missing
        $academies = DB::table('academies')->pluck('id');
        foreach ($academies as $academyId) {
            $exists = DB::table('financial_accounts')
                ->where('academy_id', $academyId)
                ->where('code', '5050')
                ->exists();

            if (!$exists) {
                DB::table('financial_accounts')->insert([
                    'uuid' => (string) \Illuminate\Support\Str::uuid(),
                    'academy_id' => $academyId,
                    'code' => '5050',
                    'name' => 'Miscellaneous Expenses',
                    'name_ar' => 'مصروفات نثرية',
                    'type' => 'expense',
                    'category' => 'operating',
                    'is_system' => true,
                    'is_active' => true,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }
    }

    public function down(): void
    {
        DB::table('permissions')->whereIn('name', ['expenses.create', 'expenses.list', 'expenses.view'])->delete();
        DB::table('financial_accounts')->where('code', '5050')->delete();
    }
};
