<?php

/**
 * @see Zend_View_Helper_Abstract
 */
goweb::loadClass('Zend_View_Helper_Abstract');

/**
 * @see cssmin
 */
require_once LIBRARY_PATH . '/External/cssmin.php';

/**
 * Goweb Sitemanager 5 Framework
 *
 * Retorna os Javascripts para serem carregados.
 *
 * @version    5.0.20
 * @category   Goweb
 * @package    Goweb_View_Helper_GetJavascript
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2010 (c) Goweb (http://www.goweb.pt)
 *
 *
 */

class Goweb_View_Helper_GetCssMinified extends Zend_View_Helper_Abstract{

    /**
     * Retorna os Javascripts para serem carregados.
     *
     * @return array
     */
    public function GetCssMinified(){
        $dir = WWW_PATH . '/media/css/';
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $cssFiles = Goweb::getCss();
        $lastmodified = 0;
        foreach ($cssFiles as $cssFile){
            if (is_file(WWW_PATH . $cssFile)){
                $lastmodified = max($lastmodified, filemtime(WWW_PATH . $cssFile));
            }
        }

        $md5File = $lastmodified . '-' .md5(serialize($cssFiles)) . '.css';

        if (!is_file($dir . $md5File)){
            $list = glob($dir . '*-' . md5(serialize($cssFiles)) . '.css');
            if (count($list) > 0){
                /**
                 * Remover ficheiros anteriores
                 */
                foreach ($list as $file){
                    if (is_writable($file)){
                        @unlink($file);
                    }
                }
            }
            $contents = '';
            foreach ($cssFiles as $cssFile){
                if (is_file(WWW_PATH . $cssFile)){
                    $content = file_get_contents(WWW_PATH . $cssFile);
                    $content = str_replace(array('../../','../', 'url(image'), array(realpath(dirname($cssFile).'/../../'), realpath(dirname($cssFile).'/../'), 'url('.dirname($cssFile).'/image'), $content);
                    $contents .= "\n\n";
                }
            }
            $contents .= "\n\n" . cssmin::minify($contents);
            if ($fp = fopen($dir . $md5File, 'wb')) {
                fwrite($fp, $contents);
                fclose($fp);
            }
        }
        return '/media/css/' . $md5File;
    }
}
