<?php
declare(strict_types=1);

if (!function_exists('hv4_emit_event')) {

    function hv4_emit_event(
        string $eventType,
        array $payload = [],
        ?string $entityType = null,
        $entityId = null
    ): void {

        try {

            if (!hv4_table_exists('system_events')) {
                return;
            }

            db()->prepare(
                "INSERT INTO system_events 
                (event_type, entity_type, entity_id, payload) 
                VALUES (?, ?, ?, ?)"
            )->execute([
                $eventType,
                $entityType,
                $entityId,
                json_encode($payload)
            ]);

        } catch (Throwable $e) {

            error_log($e->getMessage());
        }
    }
}

if (!function_exists('hv4_notify_user')) {
    function hv4_notify_user(int $userId, string $title, string $body, string $category = 'general', string $link = ''): void {
        try {
            if (!hv4_table_exists('notification_inbox')) return;
            db()->prepare('INSERT INTO notification_inbox (user_id, title, body, category, link, created_at) VALUES (?,?,?,?,?,NOW())')
               ->execute([$userId, $title, $body, $category, $link]);
        } catch (\Throwable $e) { error_log('hv4_notify_user: ' . $e->getMessage()); }
    }
}

if (!function_exists('hv4_notify_role')) {
    function hv4_notify_role(string $permission, string $title, string $body, string $category = 'general', string $link = ''): void {
        try {
            if (!hv4_table_exists('notification_inbox')) return;
            // permission is a code string e.g. 'tickets.manage' — join via permissions.code
            $stmt = db()->prepare("
                SELECT DISTINCT u.id FROM users u
                JOIN roles r ON u.role_id = r.id
                JOIN role_permissions rp ON rp.role_id = r.id
                JOIN permissions p ON p.id = rp.permission_id
                WHERE p.code = ? AND u.status = 'active'
            ");
            $stmt->execute([$permission]);
            $ins = db()->prepare('INSERT INTO notification_inbox (user_id, title, body, category, link, created_at) VALUES (?,?,?,?,?,NOW())');
            foreach ($stmt->fetchAll(\PDO::FETCH_COLUMN) as $uid) {
                $ins->execute([(int)$uid, $title, $body, $category, $link]);
            }
            // (broadcast skipped — user_id is NOT NULL in this schema)
        } catch (\Throwable $e) { error_log('hv4_notify_role: ' . $e->getMessage()); }
    }
}

if (!function_exists('hv4_notify_admins')) {
    function hv4_notify_admins(string $title, string $body, string $category = 'general', string $link = ''): void {
        try {
            if (!hv4_table_exists('notification_inbox')) return;
            $stmt = db()->prepare("SELECT id FROM users WHERE status='active' AND role_id IN (SELECT id FROM roles WHERE name IN ('super_admin','admin')) LIMIT 50");
            $stmt->execute();
            $ins = db()->prepare('INSERT INTO notification_inbox (user_id, title, body, category, link, created_at) VALUES (?,?,?,?,?,NOW())');
            foreach ($stmt->fetchAll(\PDO::FETCH_COLUMN) as $uid) {
                $ins->execute([(int)$uid, $title, $body, $category, $link]);
            }
        } catch (\Throwable $e) { error_log('hv4_notify_admins: ' . $e->getMessage()); }
    }
}
