<?php
/**
 * appRain CMF
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Team. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/docs
 */

class appRain_Base_Modules_AdminpanelUI  extends appRain_Base_Objects
{
    public function loadAdminLogin()
    {
        $lastLoginData = App::Model('Admin')->findAll('5 Order By lastlogin DESC');

        $html = "";
        foreach($lastLoginData['data'] as $key=>$data){
            if($data['lastlogin']){
                $html .= "<strong>{$data['f_name']} {$data['l_name']}</strong><br /> &nbsp;&nbsp;&nbsp;<em>" . $this->__(" on ") . App::Helper('Date')->dateFormated($data['latestlogin'],'long') . '</em>';
            }
        }
        return $html;
    }

    public function senitizeLink($val='')
    {
        $val = str_replace('{current_theme}',App::Config()->siteInfo('theme',true),$val);
        if (strstr($val,'{[ENCODE[') ) {
            $link = "";
            foreach (explode('{[ENCODE[',$val)  as  $line) {
                if(strstr( $line,']]}') ) {
                    $tmp = explode(']]}',$line);
                    $line = base64_encode($tmp[0]) . $tmp[1];
                }
                $link .=$line;
            }
            $val = $link;
        }
        return  $val;
    }

    public function pageCount($type='Content')
    {
        $uid = App::getUserStatusId();
        $result = App::Model('Page')->find("contenttype='{$type}' AND fkey={$uid}",null,'count(*) as cnt');
        return $result['cnt'];
    }

    public function adminName($id=null)
    {
        if(isset($id)) $Info = App::Model('Admin')->findById($id);
        $Info = App::Module('AdminManager')->thisAdminInfo();

        $name = "";
        $name .= isset($Info['f_name']) ? "{$Info['f_name']}" : "";
        $name .= isset($Info['l_name']) ? " {$Info['l_name']}" : "";
        $name .= isset($Info['name']) ? " {$Info['name']}" : "";
        return $name;
    }

    public function cacheChart()
    {
        $spaceEstimate = App::Load("Module/Developer")->cacheSpaceEstimate();
        $DataGrid = App::Module('DataGrid');
        $size = 0;
        foreach($spaceEstimate as $space){
            $DataGrid->addRow( $space['title'],$space['size'] . $this->__("kb"));
            $size += $space['size'];
        }

        $DataGrid->setHeader(array('Cache Type', 'Size'))
                 ->setFooter("Total memory size: {$size} kb")
                 ->Render();

    }

    public function autoCompleteInfo($JSReferance="")
    {
        $adminInfo = App::Model('Admin')->findAll();
        $data = Array();

        if(!empty($adminInfo['data']))
        foreach($adminInfo['data'] as $val){
            $data[] = $val['email'];
        }

        $memberInfo = App::Model('Member')->findAll();
        if(!empty($memberInfo['data'])){
            foreach($memberInfo['data'] as $val){
                $data[] = $val['email'];
            }
        }
        return App::Helper('JavaScript')->autoComplete($JSReferance,$data);
    }

    public function getPagemanagerHookList($theme,$page_current)
    {
        $themeInfo = app::__def()->getThemeInfo($theme);
        $hookDD = "<div style=\"float:left\" ><select name=\"data[Page][hook][]\" multiple=\"multiple\" size=\"14\" >";

        if(in_array('sitemenu',explode(',',$page_current['hook']))){
            $hookDD .= "<option selected=\"selected\" value=\"sitemenu\">Site Menu</option>";
        }
        else {
            $hookDD .= "<option value=\"sitemenu\">Site Menu</option>";
        }
        
        if(in_array('quicklinks',explode(',',$page_current['hook']))){
            $hookDD .= "<option selected=\"selected\" value=\"quicklinks\">Quick Links</option>";
        }
        else {
            $hookDD .= "<option value=\"quicklinks\">Quick Links</option>";
        }

        foreach($themeInfo['hooks'] as $hook){
            $hookDD .= "<optgroup label=\"{$hook['title']}\">";
            foreach($hook['list'] as $value=>$title){
                if(in_array($value,explode(',',$page_current['hook'])))$hookDD .= "<option selected=\"selected\" value=\"{$value}\">{$title}</option>";
                else $hookDD .= "<option value=\"{$value}\">{$title}</option>";
            }
            $hookDD .= "</optgroup>";
        }
        $hookDD .= "</select><br /><br />
        </div>";

        $hookDD .= '<div style="width:530px;padding-left:0px;float:left"><h6 style="margin-right:0">Select Place holder:</h6>'
		. '<p style="margin-left:20px">Press CTRL and Click on a placeholder name to check/uncheck selection.</p>'
		. '<h6 style="margin-right:0">Content Type</h6>'
		. '<p style="margin-left:20px">"Smart link" : Optimized link of a page, "Link" : Full link, "Text": Text Content</p>'

        . '<h6 style="margin-right:0">Insert Page or PHP code in other Page</h6>'
		. '<p style="margin-left:20px">Copy Page or Snip code inside content to render Static or Dynamic data'
		. "<br />{name=UI type=staticpage name=pagename autoformat=off}} <a href=\"javascript:void(0)\"  id=\"help-dialog-modal-open\">Help?</a> <a href=\"#\" id=\"dialog-modal-open\">All Codes?</a><p></div>
            <br class=\"clearboth\" />
            <div>
            <p style=\"margin-left:2px\">Enter comma saperated user define hook names at bellow input box<input type=\"text\" name=\"data[Page][userdefinehook]\" class=\"app_input\" value=\"{$page_current['userdefinehook']}\" /></p> </div>";

        return $hookDD;
    }

    public function staticPageLeftLinks($action,$id=null)
    {
        $page_arr = App::Pagemanager()->getData(null,null,"contenttype='Content'");
        $pageData = App::Pagemanager()->pages($id);

        $pageClass = 'open'; $snipClass = 'open';
        $pageSelect = ''; $snipSelect = '';

        if($pageData['contenttype'] == 'Snip' || $action == 'createsnip'){
            $pageClass = 'closed';
            $snipSelect = 'selected';
        }
        else{
            $snipClass = 'closed';
            $pageSelect = 'selected';
        }

        $chileClass = 'expended';

        $html =
                '<h6 id="h-menu-pages" class="'  . $pageSelect . '"><a href="#pages"><span>Pages (' . count($page_arr['data']) . ')</span></a></h6>
                    <ul id="menu-pages" class="'  . $pageClass . '">
                        <li class="' . (($action=='create')?'selected':'') .'"><a href="' . App::Config()->baseUrl('/page/manage/create') .'">New Page</a></li>
                        <li class="collapsible last">
                            <a href="#" class="collapsible plus">Manage Pages</a>
                            <ul class="' . $chileClass . '">';
                            foreach($page_arr['data'] as $val){
                                if($id == $val['id'])$html .= '<li class="selected"><a href="' . App::Config()->baseUrl("/page/manage/update/{$val['id']}"). '">' . $val['name']. '</a></li>';
                                else $html .= '<li><a href="' . App::Config()->baseUrl("/page/manage/update/{$val['id']}"). '">' . $val['name']. '</a></li>';
                            }
        $html .=			'</ul>
                        </li>
                    </ul>';

        $page_arr = App::Pagemanager()->getData(null,null,'contenttype="Snip"');
        $html .='<h6 id="h-menu-snips" class="'  . $snipSelect . '"><a href="#snips"><span>Snips (' . count($page_arr['data']) . ')</span></a></h6>
                    <ul id="menu-snips" class="' . $snipClass  . '">
                        <li class="' . (($action=='createsnip')?'selected':'') .'"><a href="' . App::Config()->baseUrl('/page/manage/createsnip') .'">New Snip</a></li>
                        <li class="collapsible last">
                            <a href="#" class="collapsible plus">Manage Snips</a>
                            <ul class="' . $chileClass . '">';
                            foreach($page_arr['data'] as $key=>$val){
                                if($id == $val['id']){
                                    $html .= '<li class="selected"><a href="' . App::Config()->baseUrl("/page/manage/update/{$val['id']}"). '">' . $val['name']. '</a></li>';
                                }
                                else {
                                    $html .= '<li><a href="' . App::Config()->baseUrl("/page/manage/update/{$val['id']}"). '">' . $val['name']. '</a></li>';
                                }
                            }
        $html .=			'</ul>
                        </li>
                    </ul>';

        return $html;
    }

    public function pageCodesList()
    {
        $page_arr = App::Pagemanager()->getData();
        $snipCodeList = "";
        $pageCodeList = "";

        foreach($page_arr['data'] as $val){
            if($val['contenttype'] == appRain_Base_Modules_PageManager::CONTENT){
                $pageCodeList .= "{{name=UI type=staticpage name={$val['name']} autoformat=off}}<br />";
            }
            else{
                $snipCodeList .= "{{name=UI type=staticpage name={$val['name']} autoformat=off}}<br />";
            }
        }

        return '<div id="dialog-modal" title="All Page Codes">
                <strong>Page Codes</strong>
                <p>' . $pageCodeList . '</p>
                <strong>Snip Codes</strong>
                <p>' . $snipCodeList . '</p>
                </div>';
    }

    public function dashBoardLink()
    {
        $__AppConfig = App::Helper('Config');
        $params = $__AppConfig->get('params');

        if((isset($params['controller']) && $params['controller'] == 'admin') &&
           (isset($params['action']) && $params['action'] == 'introduction')){
            return $__AppConfig->baseUrl('/admin/account');
        }
        else {
            return $__AppConfig->baseUrl('/admin/introduction');
        }

    }

    public function currentDate()
    {
        return '<span style="color:#ffff99">' .  date('l, jS F Y h:i:s A',App::Helper('Date')->getTime()) . '</span>';
    }

    public function themeInfo($currentTheme="")
    {
        $theme_info = App::Load('Helper/Utility')->getDirLising(VIEW_PATH);
        $info = App::__Def()->getThemeInfo($currentTheme);

        return $this->__("Current Theme <strong>") . "{$info['name']}</strong>";
    }

    public function LPCollapseLink()
    {
        $collapseAdminLeftPan = App::Session()->Read('collapseAdminLeftPan');
        $str = ($collapseAdminLeftPan) ?  "&#187;" : "&laquo;" ;
        return App::Helper('Html')
            ->LinkTag(
                'javascript:void(0)',
                $str,
                array(
                    'style'=>"text-decoration:none;color:#EEE;font-size:18px;font-weight:bold;margin-top:8px;display:block;float:left;margin-left:10px",
                    'onclick'=>"jQuery(this).html('&#164;');jQuery(this).css('cursor','wait'); jQuery.ajax({url: siteInfo.baseUrl + '/admin/switchadminleftpan',context: document.body,success: function(){window.location='';}});"
                )
            );
    }

    public function QNColumns()
    {
        $collapseAdminLeftPan = App::Session()->Read('collapseAdminLeftPan');
        return  ($collapseAdminLeftPan) ?  4 : 3;
    }

    public function isAdminLeftPancollapsed(){
        return App::Session()->Read('collapseAdminLeftPan');
    }
}
