<?php
declare(strict_types=1);

use App\Core\Registries\MenuRegistry;
use App\Core\Registries\PermissionRegistry;
use App\Core\EventBus;

MenuRegistry::register('temporary', [
    'label_ar'   => 'الأعضاء المؤقتون',
    'label_en'   => 'Temporary Members',
    'icon'       => 'user-clock',
    'route'      => '/temporary',
    'permission' => 'temp.view',
    'parent'     => null,
    'order'      => 380,
    'children'   => [],
]);

PermissionRegistry::register('temporary', [
    'temp.add'    => ['ar' => 'إضافة عضو مؤقت',   'en' => 'Add Temporary Member'],
    'temp.edit'   => ['ar' => 'تعديل عضو مؤقت',   'en' => 'Edit Temporary Member'],
    'temp.remove' => ['ar' => 'إزالة عضو مؤقت',   'en' => 'Remove Temporary Member'],
    'temp.view'   => ['ar' => 'عرض الأعضاء المؤقتين', 'en' => 'View Temporary Members'],
]);

EventBus::listen('member.profile_data', function (array &$data) {
    if (isset($data['member']) && $data['member']) {
        $memberId = is_object($data['member']) ? (int) $data['member']->id : (int) ($data['member']['id'] ?? 0);
        if ($memberId > 0) {
            try {
                $db = \App\Core\App::getInstance()->db();
                if ($db->tableExists('temporary_members')) {
                    $data['temporary'] = $db->select(
                        "SELECT * FROM temporary_members WHERE member_id = ? AND is_archived = 0 ORDER BY created_at ASC",
                        [$memberId]
                    );
                }
            } catch (\Throwable $e) {
                // Table may not exist yet
            }
        }
    }
});