<?php
/***
 * @package     jt_copymoduleassignments Joomla.Plugin
 * @copyright   Copyright (C) http://www.joomlatema.net, Inc. All rights reserved.
 * @license		http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @author     	JoomlaTema.Net
 * @link 		http://www.joomlatema.net
 ***/
defined('_JEXEC') or die;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
/**
 * Copy Module Assignments Plugin
 */
class PlgContentJt_Copymoduleassignments extends CMSPlugin
{
    protected $db;

    public function __construct($app, $plugin)
    {
        parent::__construct($app, $plugin);
        $this->db = Factory::getDbo();
    }

  public function onContentAfterSave($context, &$table, $isNew)
{
    if ($context != 'com_menus.item' || !$isNew) {
        return true;
    }

    $originalMenuId = Factory::getApplication()->input->getInt('id', 0);

    $query1 = $this->db->getQuery(true)
        ->select($this->db->quoteName('moduleid'))
        ->from($this->db->quoteName('#__modules_menu'))
        ->where($this->db->quoteName('menuid') . ' = ' . (int) $originalMenuId);
    $this->db->setQuery($query1);

    try {
        $modules = (array) $this->db->loadColumn();
    } catch (Exception $e) {
        return false;
    }

    if (!empty($modules)) {
        foreach ($modules as $mid) {
            $mdl = new stdClass();
            $mdl->moduleid = $mid;
            $mdl->menuid = $table->id;
            try {
                $this->db->insertObject('#__modules_menu', $mdl);
            } catch (Exception $e) {
                continue;
            }
        }
    }

    return true;
}
}