<?php defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Updater\Updater;
use Joomla\Registry\Registry;

class joomlacmsupdateInstallerScript
{

	protected $list = ['https://update.joomla.org/core/list.xml',];

	public function postflight($type, $parent)
	{
		if (!in_array((string) $type, ['install', 'update', 'delete']))
		{
			return;
		}

		$enabled = 0;

		if ($type === 'delete')
		{
			$enabled = 1;
		}

		$db = Factory::getDbo();

		foreach ($this->list as $link)
		{

			$query      = $db->getQuery(true);
			$fields     = array(
				$db->quoteName('enabled') . ' = ' . $db->q($enabled),
			);
			$conditions = array(
				$db->quoteName('location') . ' = ' . $db->q($link),
			);
			$query->update($db->quoteName('#__update_sites'))->set($fields)->where($conditions);
			$db->setQuery($query);
			$db->execute();

		}

		$this->rebuild();
		$this->findUpdates();
	}

	protected function findUpdates()
	{
		Updater::getInstance()->findUpdates();
	}

	protected function rebuild()
	{
		Factory::getApplication()->getLanguage()->load('com_installer');
		BaseDatabaseModel::addIncludePath(JPATH_ROOT . '/administrator/components/com_installer/models');
		$model = BaseDatabaseModel::getInstance('Updatesites', 'InstallerModel');
		$model->rebuild();
	}

}