<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/

class Core_Plugin_Savecollection
{
    /**
     * Hook: onItemDeleteBefore
     * Called when any content item is deleted from the platform.
     * Removes all saved items and collection mappings referencing the deleted content.
     */
    public function onItemDeleteBefore($event)
    {
        $item = $event->getPayload();
        if (!$item || !method_exists($item, 'getType') || !method_exists($item, 'getIdentity')) {
            return;
        }

        $contentType = $item->getType();
        $contentId = $item->getIdentity();

        if (empty($contentType) || empty($contentId)) {
            return;
        }

        try {
            Engine_Api::_()->getApi('savecollection', 'core')
                ->onContentDelete($contentType, $contentId);
        } catch (Exception $e) {
            // Silently fail to not disrupt the deletion process
        }
    }

    /**
     * Hook: onUserDeleteBefore
     * Called when a user account is deleted.
     * Removes all saved items, collections, and mappings for the user.
     */
    public function onUserDeleteBefore($event)
    {
        $payload = $event->getPayload();
        $userId = is_object($payload) ? $payload->getIdentity() : (int) $payload;

        if (empty($userId)) {
            return;
        }

        try {
            Engine_Api::_()->getApi('savecollection', 'core')
                ->onUserDelete($userId);
        } catch (Exception $e) {
            // Silently fail to not disrupt the deletion process
        }
    }
}
