<?php

class pkg_yoothemeInstallerScript
{
    protected $db;
    protected $app;
    protected $tmp;
    protected $php = '5.4.0';

    public function __construct()
    {
        $this->db = JFactory::getDBO();
        $this->app = JFactory::getApplication();
        $this->tmp = $this->app->getCfg('tmp_path');
    }

    public function preflight($type, $parent)
    {
        // abort if PHP version < 5.4
        if (version_compare(PHP_VERSION, $this->php, '<')) {
            JError::raiseWarning(null, "<p>You need PHP {$this->php} or later to install the template.</p>");
            return false;
        }

        if ($type == 'update') {

            $name = (string) $parent->manifest->packagename;

            // backup theme.css
            if (JFile::exists(JPATH_ROOT . "/templates/{$name}/css/theme.css")) {
                JFile::copy(JPATH_ROOT . "/templates/{$name}/css/theme.css", "{$this->tmp}/theme.css");
            }

            // clean specific folders
            $folders = array(
                "/templates/{$name}/less",
                "/templates/{$name}/vendor",
                "/templates/{$name}/templates"
            );

            foreach ($folders as $path) {
                JFolder::delete(JPATH_ROOT . $path);
            }
        }
    }

    public function postflight($type, $parent)
    {
        if ($type == 'update') {

            $name = (string) $parent->manifest->packagename;

            // updateservers url update workaround
            if ($parent->manifest->updateservers) {

                $servers = $parent->manifest->updateservers->children();

                $this->db->setQuery(
                    "UPDATE `#__update_sites` a" .
                    " LEFT JOIN `#__update_sites_extensions` b ON b.update_site_id = a.update_site_id" .
                    " SET location = " . $this->db->quote(trim((string) $servers[0])) . ', enabled = 1' .
                    " WHERE b.extension_id = (SELECT `extension_id` FROM `#__extensions` WHERE `type` = 'package' AND `element` = 'pkg_{$name}')"
                )->execute();

            }

            // restore theme.css
            if (JFile::exists("{$this->tmp}/theme.css")) {
                if (JFile::copy("{$this->tmp}/theme.css", JPATH_ROOT . "/templates/{$name}/css/theme.css")) {
                    JFile::delete("{$this->tmp}/theme.css");
                }
            }

        }
    }
}
