<?php

/**
 * SP Engage Integration - logic hooks for leads.
 * @author Celenia Software
 */

class SP_LogicHooksLD
{

    /**
     *
     * @param SugarBean $bean
     * @param string $event
     * @param array $args
     */
    function afterDelete($bean, $event, $args)
    {
        if (isset($bean->sp_frommerge) && $bean->sp_frommerge == 'yes') { return; }
        if (isset($bean->sp_synctosilverpop) && $bean->sp_synctosilverpop == 1)
        {
            // $GLOBALS['log']->fatal('SP => Saving deleted object pointer with id ' . $bean->id);
            $this->saveDeletedObject($bean);
        }
    }

    /**
     *
     * @param SugarBean $bean
     * @param string $event
     * @param array $args
     */
    function afterSave($bean, $event, $args)
    {
        if (isset($bean->sp_frommerge) && $bean->sp_frommerge == 'yes')
        {
            foreach ($bean->sp_slaverecs as $slaveRecordId)
            {
                $slaveBean = BeanFactory::getBean('Leads', $slaveRecordId);

                if (isset($bean->sp_synctosilverpop) && $bean->sp_synctosilverpop == 1)
                {
                    if (isset($slaveBean->sp_synctosilverpop) && $slaveBean->sp_synctosilverpop == 1)
                    {
                        // $GLOBALS['log']->fatal('SP => Saving merged object pointer with id ' . $bean->id);
                        if ($bean->id != $slaveBean->id)
                        {
                            $this->saveMergedObject($bean, $slaveBean);
                        }
                    }
                }
                else
                {
                    if ($bean->id != $slaveBean->id)
                    {
						if (isset($slaveBean->sp_synctosilverpop) && $slaveBean->sp_synctosilverpop == 1)
						{
							$this->saveDeletedObject($slaveBean);
						}
                    }
                }
            }
        }
    }

    private function saveDeletedObject($bean)
    {
        $deletedObject = BeanFactory::newBean("SP_DeletedObjectPointer");
        $deletedObject->sp_objectid   = $bean->id;
        $deletedObject->sp_engageid   = $bean->sp_engageid;
        $deletedObject->sp_objecttype = "lead";
        $deletedObject->save();
    }

    private function saveMergedObject($masterBean, $slaveBean)
    {
        $mergedObject = BeanFactory::newBean("SP_MergedObjectPointer");
        $mergedObject->sp_masterid    = $masterBean->id;
        $mergedObject->sp_slaveid     = $slaveBean->id;
        $mergedObject->sp_objecttype  = "lead";
        $mergedObject->save();
    }
}
