<?php
    /*
     *      Osclass – software for creating and publishing online classified
     *                           advertising platforms
     *
     *                        Copyright (C) 2012 OSCLASS
     *
     *       This program is free software: you can redistribute it and/or
     *     modify it under the terms of the GNU Affero General Public License
     *     as published by the Free Software Foundation, either version 3 of
     *            the License, or (at your option) any later version.
     *
     *     This program is distributed in the hope that it will be useful, but
     *         WITHOUT ANY WARRANTY; without even the implied warranty of
     *        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     *             GNU Affero General Public License for more details.
     *
     *      You should have received a copy of the GNU Affero General Public
     * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
     */

    define('NEXT_REVO_THEME_VERSION', '2.0.0');
	

    function next_region_select() {
        View::newInstance()->_exportVariableToView('list_regions', Search::newInstance()->listRegions('%%%%', '>=', 'region_name ASC') ) ;

        if( osc_count_list_regions() > 0 ) {
            echo '<select name="sRegion">' ;
			echo '<option value="">' . __('Select a region', 'next') . '</option>' ;
            while( osc_has_list_regions() ) {
			   
                echo '<option value="' . osc_list_region_name() . '">' . osc_list_region_name() . '</option>' ;
            }
            echo '</select>' ;
        }

        View::newInstance()->_erase('list_regions') ;
    }


    if( !OC_ADMIN ) {
        if( !function_exists('add_close_button_action') ) {
            function add_close_button_action(){
                echo '<script type="text/javascript">';
                    echo '$(".flashmessage .ico-close").click(function(){';
                        echo '$(this).parent().hide();';
                    echo '});';
                echo '</script>';
            }
            osc_add_hook('footer', 'add_close_button_action');
        }
    }

    function theme_next_actions_admin() {
        if( Params::getParam('file') == 'oc-content/themes/next_revo/admin/settings.php' ) {
            if( Params::getParam('donation') == 'successful' ) {
                osc_set_preference('donation', '1', 'next_revo');
                osc_reset_preferences();
            }
        }

        switch( Params::getParam('action_specific') ) {
            case('settings'):
                $footerLink  = Params::getParam('footer_link');
                $defaultLogo = Params::getParam('default_logo');
                osc_set_preference('keyword_placeholder', Params::getParam('keyword_placeholder'), 'next_revo');
                osc_set_preference('footer_link', ($footerLink ? '1' : '0'), 'next_revo');
                osc_set_preference('default_logo', ($defaultLogo ? '1' : '0'), 'next_revo');
				osc_set_preference('defaultShowAs@all', Params::getParam('defaultShowAs@all'), 'next_revo');
                osc_set_preference('defaultShowAs@search', Params::getParam('defaultShowAs@all'));

                osc_set_preference('main-next-top',         trim(Params::getParam('main-next-top', false, false, false)),                  'next_revo');
                osc_set_preference('main-next-under',       trim(Params::getParam('main-next-under', false, false, false)),                'next_revo');
                osc_set_preference('main-next-middle',       trim(Params::getParam('main-next-middle', false, false, false)),                'next_revo');
                osc_set_preference('search-next-top',     trim(Params::getParam('search-next-top', false, false, false)),          'next_revo');
                osc_set_preference('search-next_middle',  trim(Params::getParam('search-next_middle', false, false, false)),       'next_revo');
				osc_set_preference('search-next_under',  trim(Params::getParam('search-next_under', false, false, false)),       'next_revo');
				osc_set_preference('item-next_desc',  trim(Params::getParam('item-next_desc', false, false, false)),       'next_revo');
				osc_set_preference('item-next_image',  trim(Params::getParam('item-next_image', false, false, false)),       'next_revo');
				osc_set_preference('header-next',         trim(Params::getParam('header-next', false, false, false)),                  'next_revo');
				osc_set_preference('related_next_ra_numads'    	, '4','next_revo','INTEGER');
	            osc_set_preference('related_next_ra_category'   , '1','next_revo','INTEGER');

                osc_add_flash_ok_message(__('Theme settings updated correctly', 'next_revo'), 'admin');
                header('Location: ' . osc_admin_render_theme_url('oc-content/themes/next_revo/admin/settings.php')); exit;
            break;
            case('upload_logo'):
                $package = Params::getFiles('logo');
                if( $package['error'] == UPLOAD_ERR_OK ) {
                    if( move_uploaded_file($package['tmp_name'], WebThemes::newInstance()->getCurrentThemePath() . "images/logo.jpg" ) ) {
                        osc_add_flash_ok_message(__('The logo image has been uploaded correctly', 'next_revo'), 'admin');
                    } else {
                        osc_add_flash_error_message(__("An error has occurred, please try again", 'next_revo'), 'admin');
                    }
                } else {
                    osc_add_flash_error_message(__("An error has occurred, please try again", 'next_revo'), 'admin');
                }
                header('Location: ' . osc_admin_render_theme_url('oc-content/themes/next_revo/admin/header.php')); exit;
            break;
            case('remove'):
                if(file_exists( WebThemes::newInstance()->getCurrentThemePath() . "images/logo.jpg" ) ) {
                    @unlink( WebThemes::newInstance()->getCurrentThemePath() . "images/logo.jpg" );
                    osc_add_flash_ok_message(__('The logo image has been removed', 'next_revo'), 'admin');
                } else {
                    osc_add_flash_error_message(__("Image not found", 'next_revo'), 'admin');
                }
                header('Location: ' . osc_admin_render_theme_url('oc-content/themes/next_revo/admin/header.php')); exit;
            break;
        }
    }
	
	if( !function_exists('next_show_as') ){
        function next_show_as(){

            $p_sShowAs    = Params::getParam('sShowAs');
            $aValidShowAsValues = array('list', 'gallery');
            if (!in_array($p_sShowAs, $aValidShowAsValues)) {
                $p_sShowAs = next_default_show_as();
            }

            return $p_sShowAs;
        }
    }
    if( !function_exists('next_default_show_as') ){
        function next_default_show_as(){
            return getPreference('defaultShowAs@all','next_revo');
        }
    }
    
	if( !function_exists('get_categoriesHierarchy') ) {
        function get_categoriesHierarchy( ) {
            $location = Rewrite::newInstance()->get_location() ;
            $section  = Rewrite::newInstance()->get_section() ;
            
            if ( $location != 'search' ) {
                return false ;
            }
            
            $category_id = osc_search_category_id() ;
            
            if(count($category_id) > 1) {
                return false;
            }
            
            $category_id = (int) $category_id[0] ;
            
            $categoriesHierarchy = Category::newInstance()->hierarchy($category_id) ;
            
            foreach($categoriesHierarchy as &$category) {
                $category['url'] = get_category_url($category) ;
            }
            
            return $categoriesHierarchy ;
         }
     }
     
     if( !function_exists('get_subcategories') ) {
         function get_subcategories( ) {
             $location = Rewrite::newInstance()->get_location() ;
             $section  = Rewrite::newInstance()->get_section() ;
            
             if ( $location != 'search' ) {
                 return false ;
             }
            
             $category_id = osc_search_category_id() ;
            
             if(count($category_id) > 1) {
                 return false ;
             }
            
             $category_id = (int) $category_id[0] ;
            
             $subCategories = Category::newInstance()->findSubcategories($category_id) ;
            
             foreach($subCategories as &$category) {
                 $category['url'] = get_category_url($category) ;
             }
            
             return $subCategories ;
         }
     }

     if ( !function_exists('get_category_url') ) {
         function get_category_url( $category ) {
             $path = '';
             if ( osc_rewrite_enabled() ) {
                if ($category != '') {
                    $category = Category::newInstance()->hierarchy($category['pk_i_id']) ;
                    $sanitized_category = "" ;
                    for ($i = count($category); $i > 0; $i--) {
                        $sanitized_category .= $category[$i - 1]['s_slug'] . '/' ;
                    }
                    $path = osc_base_url() . $sanitized_category ;
                }
            } else {
                $path = sprintf( osc_base_url(true) . '?page=search&sCategory=%d', $category['pk_i_id'] ) ;
            }
            
            return $path;
         }
     }
     
     if ( !function_exists('get_category_num_items') ) {
         function get_category_num_items( $category ) {
            $category_stats = CategoryStats::newInstance()->countItemsFromCategory($category['pk_i_id']) ;
            
            if( empty($category_stats) ) {
                return 0 ;
            }
            
            return $category_stats;
         }
     }
	 if( !function_exists('next_item_title') ) {
        function next_item_title() {
            $title = osc_item_title();
            foreach( osc_get_locales() as $locale ) {
                if( Session::newInstance()->_getForm('title') != "" ) {
                    $title_ = Session::newInstance()->_getForm('title');
                    if( @$title_[$locale['pk_c_code']] != "" ){
                        $title = $title_[$locale['pk_c_code']];
                    }
                }
            }
            return $title;
        }
    }
    if( !function_exists('next_item_description') ) {
        function next_item_description() {
            $description = osc_item_description();
            foreach( osc_get_locales() as $locale ) {
                if( Session::newInstance()->_getForm('description') != "" ) {
                    $description_ = Session::newInstance()->_getForm('description');
                    if( @$description_[$locale['pk_c_code']] != "" ){
                        $description = $description_[$locale['pk_c_code']];
                    }
                }
            }
            return $description;
        }
    }

    if( !function_exists('logo_header') ) {
        function logo_header() {
            $html = '<img border="0" alt="' . osc_page_title() . '" src="' . osc_current_web_theme_url('images/logo.jpg') . '" />';
            if( file_exists( WebThemes::newInstance()->getCurrentThemePath() . "images/logo.jpg" ) ) {
                return $html;
            } else if( osc_get_preference('default_logo', 'next_revo') && (file_exists( WebThemes::newInstance()->getCurrentThemePath() . "images/default-logo.jpg")) ) {
                return '<img border="0" alt="' . osc_page_title() . '" src="' . osc_current_web_theme_url('images/default-logo.jpg') . '" />';
            } else {
                return osc_page_title();
            }
        }
    }

    // install update options
    if( !function_exists('next_theme_install') ) {
        function next_theme_install() {
            osc_set_preference('keyword_placeholder', __('ie. car', 'next_revo'), 'next_revo');
            osc_set_preference('version', '2.0.0', 'next_revo');
            osc_set_preference('footer_link', true, 'next_revo');
            osc_set_preference('donation', '0', 'next_revo');
            osc_set_preference('default_logo', '1', 'next_revo');
            osc_reset_preferences();
        }
    }

    if(!function_exists('check_install_next_theme')) {
        function check_install_next_theme() {
            $current_version = osc_get_preference('version', 'next_revo');
            //check if current version is installed or need an update
            if( !$current_version ) {
                next_theme_install();
            }
        }
    }

    require_once WebThemes::newInstance()->getCurrentThemePath() . 'inc.functions.php';

    check_install_next_theme();
	/* ads  SEARCH */
    function search_ads_listing_top_fn() {
        if(osc_get_preference('search-next-top', 'next_revo')!='') {
            echo '<div class="clear"></div>' . PHP_EOL;
            echo '<div class="search_top">' . PHP_EOL;
            echo osc_get_preference('search-next-top', 'next_revo');
            echo '</div>' . PHP_EOL;
        }
    }
    osc_add_hook('search_top', 'search_ads_listing_top_fn');
	
	function search_ads_listing_under_fn() {
        if(osc_get_preference('search-next_under', 'next_revo')!='') {
            echo '<div class="clear"></div>' . PHP_EOL;
            echo '<div class="search_under">' . PHP_EOL;
            echo osc_get_preference('search-next_under', 'next_revo');
            echo '</div>' . PHP_EOL;
        }
    }
    osc_add_hook('search_under', 'search_ads_listing_under_fn');

    function main_ads_listing_medium_fn() {
        if(osc_get_preference('main-next-middle', 'next_revo')!='') {
            echo '<div class="clear"></div>' . PHP_EOL;
            echo '<div class="middle_main">' . PHP_EOL;
            echo osc_get_preference('main-next-middle', 'next_revo');
            echo '</div>' . PHP_EOL;
        }
    }
    osc_add_hook('main_middle', 'main_ads_listing_medium_fn');
	
	function search_ads_listing_medium_fn() {
        if(osc_get_preference('search-next_middle', 'next_revo')!='') {
            echo '<div class="clear"></div>' . PHP_EOL;
            echo '<div class="middle_search">' . PHP_EOL;
            echo osc_get_preference('search-next_middle', 'next_revo');
            echo '</div>' . PHP_EOL;
        }
    }
    osc_add_hook('search_middle', 'search_ads_listing_medium_fn');

    /* remove theme */
    function next_delete_theme() {
        osc_remove_preference('keyword_placeholder', 'next_revo');
        osc_remove_preference('footer_link', 'next_revo');
        osc_remove_preference('default_logo', 'next_revo');
        osc_remove_preference('donation', 'next_revo');

        osc_remove_preference('main-next-top', 'next_revo');
        osc_remove_preference('main-next-under', 'next_revo');
        osc_remove_preference('main-next-middle', 'next_revo');
        osc_remove_preference('search-next-top', 'next_revo');
        osc_remove_preference('search-next_middle', 'next_revo'); 
		osc_remove_preference('search-next_under', 'next_revo');
		osc_remove_preference('item-next_desc', 'next_revo');
		osc_remove_preference('item-next_image', 'next_revo');
		osc_remove_preference('header-next', 'next_revo');
    }


	
		function next_popular_ads_start() {

			$num_ads = 8; // SETS HOW MANY POPULAR ADS TO DISPLAY
			View::newInstance()->_exportVariableToView('items', array());

            $mSearch = new Search();
            $mSearch->addField('SUM('.DB_TABLE_PREFIX.'t_item_stats.i_num_views) AS total_views');
            $mSearch->addJoinTable('t_item_stats.fk_i_item_id',DB_TABLE_PREFIX."t_item_stats",DB_TABLE_PREFIX."t_item_stats.fk_i_item_id = ".DB_TABLE_PREFIX."t_item.pk_i_id",'JOIN');
            $mSearch->addGroupBy(DB_TABLE_PREFIX.'t_item_stats.fk_i_item_id');
            $mSearch->order('total_views');
            $mSearch->limit('0', $num_ads);

            $nItems      = $mSearch->doSearch();
            $nTotalItems = count($nItems);
            if( $nTotalItems > 0 ) {
                View::newInstance()->_exportVariableToView('items', $nItems);
                return $nTotalItems;
            }
            unset($mSearch);
			
			return 0;
		}


		function next_popular_ads_end(){
		GLOBAL $stored_items;
		   View::newInstance()->_exportVariableToView('items', $stored_items); 
		}


    
    
    function osc_related_next_ra_numads() {
        return(osc_get_preference('related_next_ra_numads', 'next_revo')) ;
    }
    
    function osc_related_next_category() {
        return(osc_get_preference('related_next_ra_category', 'next_revo')) ;
    }
    
    function osc_related_next_country() {
        return(osc_get_preference('related_next_ra_country', 'next_revo')) ;
    }
    
    function osc_related_next_region() {
        return(osc_get_preference('related_next_ra_region', 'next_revo')) ;
    }
    
    function osc_related_next_picOnly() {
        return(osc_get_preference('related_next_picOnly', 'next_revo')) ;
    }
    
    function osc_related_next_css() {
    	return(osc_get_preference('related_next_css', 'next_revo')) ;
    }
    
    function osc_related_next_autoembed() {
    	return(osc_get_preference('related_next_autoembed', 'next_revo')) ;
    }
    function osc_related_next_premiumOnly() {
    	return(osc_get_preference('related_next_premiumonly', 'next_revo')) ;
    }
//function to show related Ads    	 
function related_next_start() {
    $rmItemId = osc_item_id() ;
    $ra_numads = (osc_related_next_ra_numads() != '') ? osc_related_next_ra_numads() : '' ;
    $country = (osc_related_next_country() != '') ? osc_related_next_country() : '' ;
    $region = (osc_related_next_region() != '') ? osc_related_next_region() : '' ;
    $category = (osc_related_next_category() != '') ? osc_related_next_category() : '' ;
    $picOnly = (osc_related_next_picOnly() != '') ? osc_related_next_picOnly() : ''; 
    $premiumonly = (osc_related_next_premiumOnly() != '') ? osc_related_next_premiumOnly() : '';
    
    $mSearch = new Search() ;
    
    //Excluding current item
    $mSearch->dao->where(sprintf("%st_item.pk_i_id <> $rmItemId", DB_TABLE_PREFIX));
    
    //Checking if item is premium
    if($premiumonly ==1){
    $mSearch->dao->where(sprintf("%st_item.b_premium = 1", DB_TABLE_PREFIX));
    }
    
    //Adding Country as condition
    if($country ==1){
    $mSearch->addCountry(osc_item_country()) ;
    }
    
    //Adding Region as condition
    if($region ==1) {
    $mSearch->addRegion(osc_item_region()) ;
    }
    
    //Adding Item Category as condition
    if($category ==1) {
    $mSearch->addCategory(osc_item_category_id()) ;
    }
    
    //Adding condition for item having pictures
    if($picOnly == 1 ) {
    $mSearch->withPicture(true); //Search only Item which have pictures
    }
    
    //limiting number of related ads
    $mSearch->limit(0, $ra_numads) ; // fetch number of ads to show set in preference
    
    //Searching with all enabled conditions
    $aItems = $mSearch->doSearch();
     


	
	$global_items = View::newInstance()->_get('items') ; //save existing item array
	View::newInstance()->_exportVariableToView('items', $aItems); //exporting our searched item array

    require_once WebThemes::newInstance()->getCurrentThemePath() . 'related_next_ads.php';


  
     //calling stored item array
    View::newInstance()->_exportVariableToView('items', $global_items); //restore original item array
    }



?>