<?php
$document = JFactory::getDocument();
$lang = JFactory::getLanguage();
$langCode = $lang->getTag();
$langCodeShort = substr($langCode, 0, 2);

$conditions = [
    ['uid' => 1, 'id' => 'used', 'name' => JText::_( 'COM_PIXELCMS_CONDITION_USED' )],
    ['uid' => 2, 'id' => 'new', 'name' => JText::_( 'COM_PIXELCMS_CONDITION_NEW' )],
    ['uid' => 3, 'id' => 'demonstration', 'name' => JText::_( 'COM_PIXELCMS_CONDITION_DEMONSTRATION' )],
    ['uid' => 4, 'id' => 'accident_or_fire_damage', 'name' => JText::_( 'COM_PIXELCMS_CONDITION_ACCIDENT_OR_FIRE_DAMAGE' )],
    ['uid' => 5, 'id' => 'showroom_machine', 'name' => JText::_( 'COM_PIXELCMS_CONDITION_SHOWROOM_MACHINE' )],
    ['uid' => 6, 'id' => 'rental', 'name' => JText::_( 'COM_PIXELCMS_CONDITION_RENTAL' )],
];

$uid = bin2hex(random_bytes(10));

$model = $this->params->get('model', 'tracktorpool_products');

$script = "
'use strict';

Vue.config.devtools = true;

document.addEventListener('DOMContentLoaded', function (event) {
	var app = new Vue({
		el: '#app-$uid',
		data: {
			pageSize: {$this->params->get('page_size', 15)},
			currentPage: 1,
			maxPages: 5,
			priceStyle: {$this->params->get('price_style', 0)},
			products: ". json_encode($this->ads) .",
			filters: {
				manufacturer: false,
				category: false,
				age: false,
				condition: false,
				dealer: false,
			},
      sortKey: 'default',
			sortOrders: {
				default: 1,
				year: 1,
				price: 1,
        workhours: 1,
        trade_price: 1,
        power: 1,
			},
		},
		filters: {
		  short: function short(value) {
		    var short = value.substr(0, 20);
		    return short + ((short.length !== value.length) ? '...' : '');
		  },
		  sprintf: sprintf,
		},
		methods: {
		    setURL: function setURL() {
		        var obj = {
		            p: this.currentPage, 
		            s: {k: this.sortKey, o: this.sortOrders[this.sortKey]},
		            f: {
		              m: this.filters.manufacturer, 
		              c: this.filters.category, 
		              co: this.filters.condition,
		              d: this.filters.dealer,
		            }
		        };
		        window.location.hash = '!' + encodeURI(btoa(JSON.stringify(obj)))
		    },
		    saveURL: function saveURL() {
		        window.sessionStorage.setItem('product_link', window.location.href);
		    },
		    formatPrice: function formatPrice(value) {
          return value.toLocaleString('de-DE', { style: 'currency', currency: 'EUR',currencyDisplay: 'code', minimumFractionDigits:2, maximumFractionDigits: 2 });
        },
		    parseURL: function parseURL() {
		        var _this = this;
		        var hash = window.location.hash.substr(2);
		        if (hash) {
		            try {
		                var obj = JSON.parse(atob(decodeURI(hash)));
		                this.filters.manufacturer = obj.f.m;
		                this.filters.category = obj.f.c;
		                this.filters.condition = obj.f.co || false;
		                this.filters.dealer = obj.f.d || false;
		                
		                this.sortKey= obj.s.k;
		                this.sortOrders[this.sortKey]= obj.s.o;
		                
		                this.\$nextTick(function() {
		                    _this.setPage(obj.p);
		                });
		            } catch (err) {
		                console.log(err);
		            }
		        }
		    },
			setPage: function setPage(page) {
				this.currentPage = Math.max(1, Math.min(page, this.pages));
				
				var menu = document.getElementById('menu-container');
				var menuHeight = menu ? menu.clientHeight : 0;
				
				var bounding = this.\$refs.topPagination.getBoundingClientRect();
				
				if (bounding.top < 0) {
          window.scrollBy({
            top: this.\$refs.topPagination.getBoundingClientRect().y - menuHeight - parseInt(getComputedStyle(this.\$refs.topPagination).marginTop, 10), 
            behavior: 'smooth'
          });
				}
			}
		},
		created: function created() {
		    this.parseURL();
		},
		computed: {
			pages: function pages() {
				return Math.ceil(this.filteredData.length / this.pageSize);
			},
			pagination: function pagination() {
			  var _this = this;
			  var paddingPages = 2;
			  var paginationSize = Math.min((paddingPages * 2 + 1), _this.pages);

        return [].concat(Array(paginationSize).fill().map(function(_v,k) { return k; })).map(function (v) {
          if (paginationSize === _this.pages) return (v + 1);
          return v + Math.max(1, _this.currentPage - paddingPages) - Math.max(0, _this.currentPage + paddingPages - _this.pages);
        });
      },
			paginatedData: function paginatedData() {
			    this.setURL();
				return this.filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
			},
			filteredData: function filteredData() {
				var _this = this;
				var sortKey = this.sortKey;
				var order = this.sortOrders[sortKey] || 1;
				var filtered = this.products;
				
				this.currentPage = 1;

				if (this.filters.manufacturer !== false) {
					filtered = filtered.filter(function (value) {
						return value.manufacturer.id == _this.filters.manufacturer;
					});
				}
				if (this.filters.category !== false) {
					filtered = filtered.filter(function (value) {
						return value.category.id == _this.filters.category;
					});
				}
				if (this.filters.condition !== false) {
					filtered = filtered.filter(function (value) {
						return value.condition.id == _this.filters.condition;
					});
				}
				if (this.filters.dealer !== false) {
					filtered = filtered.filter(function (value) {
						return value.dealer.id == _this.filters.dealer;
					});
				}
				if (this.filters.age !== false) {
					var date = new Date();
					filtered = filtered.filter(function (value) {
						return date.getFullYear() - value.year <= _this.filters.age;
					});
				}
				
        if (sortKey === 'default') {
          return filtered;
        }
				
				return filtered.concat().sort(function(a,b) {
				    if (['price', 'workhours', 'trade_price', 'power'].includes(sortKey)) {
				        return Math.sign(((b[sortKey]) ? b[sortKey].value : -1) - ((a[sortKey]) ? a[sortKey].value : -1)) * order;
				    }
				    return Math.sign(b[sortKey] - a[sortKey]) * order;
				});
			},
			manufacturers: function manufacturers() {
				var _this2 = this;

				var manufacturers = [];
				var filtered = this.products;

				if (this.filters.dealer !== false) {
					filtered = filtered.filter(function (value) {
						return value.dealer.id == _this2.filters.dealer;
					});
				}
				if (this.filters.category !== false) {
					filtered = filtered.filter(function (value) {
						return value.category.id == _this2.filters.category;
					});
				}
				if (this.filters.age !== false) {
					var date = new Date();
					filtered = filtered.filter(function (value) {
						return date.getFullYear() - value.year <= _this2.filters.age;
					});
				}
				
				var counts = {};
				filtered.forEach(function (val, index) {
					var id = val.manufacturer.id;
					if (!manufacturers[id]) {
						manufacturers[id] = val.manufacturer;
					}
					counts[id] = 1  + (counts[id] || 0)
					manufacturers[id].count = counts[id];
				});
				
                return manufacturers.filter(function(a){
                    return a;
                }).sort(function(a,b) {
                    if(a.id === 0) return -1; else if(b.id === 0) return 1;
				    return a.value.localeCompare(b.value)
				});
			},
			categories: function categories() {
				var _this3 = this;

				var categories = [];
				var filtered = this.products;

				if (this.filters.dealer !== false) {
					filtered = filtered.filter(function (value) {
						return value.dealer.id == _this3.filters.dealer;
					});
				}
				if (this.filters.manufacturer !== false) {
					filtered = filtered.filter(function (value) {
						return value.manufacturer.id == _this3.filters.manufacturer;
					});
				}
				if (this.filters.age !== false) {
					var date = new Date();
					filtered = filtered.filter(function (value) {
						return date.getFullYear() - value.year <= _this3.filters.age;
					});
				}

				var counts = {};
				filtered.forEach(function (val, index) {
					var id = val.category.id;
					if (!categories[id]) {
						categories[id] = val.category;
					}
					counts[id] = 1  + (counts[id] || 0)
					categories[id].count = counts[id];
				});
				
                return categories.filter(function(a){
                    return a;
                }).sort(function(a,b) {
				    return a.name.localeCompare(b.name);
				});
			},
			dealers: function dealers() {
			  " . (($model === 'technikboerse_products') ? '' : 'return [];' ) . "
        var _this5 = this;

				var dealers = [];
				var dealer_ids = [];
				var filtered = this.products;
				
        filtered.forEach(function (val, index) {
          if (!dealer_ids.includes(val.dealer.id)) {
            dealers.push(val.dealer);
            dealer_ids.push(val.dealer.id);
          }
				});
				
				return dealers.sort(function(a,b) {
				    return a.name.localeCompare(b.name);
				});
			},
			conditions: function conditions() {
			    if (" . (($model === 'mascus_products') ? 'true' : 'false') . ") return [];
				var conditionsTranslation = ". json_encode(array_column($conditions, null, 'id')) .";
				var conditions = [];
				var filtered = this.products;
                
				filtered.forEach(function (val, index) {
				    var condition = conditionsTranslation[val.condition.id]
					conditions[condition.uid] = condition;
				});
				
                return conditions.filter(function(a){
                    return a;
                }).sort(function(a,b) {
				    return a.name.localeCompare(b.name);
				});
			},
			ages: function ages() {
				var _this4 = this;

				var ages = {};
				var filtered = this.products;
				var date = new Date();

				if (this.filters.manufacturer !== false) {
					filtered = filtered.filter(function (value) {
						return value.manufacturer.id == _this4.filters.manufacturer;
					});
				}
				if (this.filters.category !== false) {
					filtered = filtered.filter(function (value) {
						return value.category.id == _this4.filters.category;
					});
				}
				if (this.filters.age !== false) {
					ages[this.filters.age] = {
						value: this.filters.age,
						id: this.filters.age
					};
				}

				filtered.forEach(function (value, index) {
					var age = date.getFullYear() - value.year;
					ages[age] = {
						value: age,
						id: age,
					};
				});
				return ages;
			}
		}
	});
});
";

$document->addScriptDeclaration( $script );

if ($this->params->get('show_page_heading')) {
    echo "<div class=\"page-header\">";
    echo "<h2 itemprop=\"headline\">{$this->params->get('page_title')}</h2>";
    echo "</div>";
}

?>
<div id="app-<?php echo $uid ?>">
    <div class="filter">
        <div class="select-group">
            <label for="sortKey"><?php echo JText::_( 'COM_PIXELCMS_SORTKEY_LABEL' ) ?></label>
            <select id="sortKey" v-model="sortKey">
                <option value="default"><?php echo JText::_( 'COM_PIXELCMS_SORTKEY_DEFAULT' ) ?></option>
                <option value="year"><?php echo JText::_( 'COM_PIXELCMS_SORTKEY_YEAR' ) ?></option>
                <option value="price"><?php echo JText::_( 'COM_PIXELCMS_SORTKEY_PRICE' ) ?></option>
            </select>
        </div>
        <div class="select-group">
            <label for="sortOrder"><?php echo JText::_( 'COM_PIXELCMS_SORTORDER_LABEL' ) ?></label>
            <select v-bind:disabled="sortKey === 'default'" v-model="sortOrders[sortKey]" id="sortOrder">
                <option v-bind:value="-1"><?php echo JText::_( 'COM_PIXELCMS_SORTORDER_ASC' ) ?></option>
                <option v-bind:value="1"><?php echo JText::_( 'COM_PIXELCMS_SORTORDER_DESC' ) ?></option>
            </select>
        </div>
        <div class="select-group">
            <label for="filterCategory"><?php echo JText::_( 'COM_PIXELCMS_SELECT_CATEGORY_LABEL' ) ?></label>
            <select v-model="filters.category" id="filterCategory">
                <option v-bind:value="false" selected><?php echo JText::_( 'COM_PIXELCMS_SELECT_CATEGORY' ) ?></option>
                <option v-bind:value="item.id" v-for="item in categories">{{ item.name }} ({{ item.count }})</option>
            </select>
        </div>
        <div class="select-group">
            <label for="filterManufacturer"><?php echo JText::_( 'COM_PIXELCMS_SELECT_MANUFACTURER_LABEL' ) ?></label>
            <select v-model="filters.manufacturer" id="filterManufacturer">
                <option v-bind:value="false" selected><?php echo JText::_( 'COM_PIXELCMS_SELECT_MANUFACTURER' ) ?></option>
                <option v-bind:value="item.id" v-for="item in manufacturers">{{ item.value }} ({{ item.count }})</option>
            </select>
        </div>
        <?php if (empty($this->params->get('traktorpool_condition') && $model !== 'mascus_products' )): ?>
            <div class="select-group">
                <label for="filterCategory"><?php echo JText::_( 'COM_PIXELCMS_CONDITION' ) ?></label>
                <select v-model="filters.condition" id="filterCondition">
                    <option v-bind:value="false" selected><?php echo JText::_( 'COM_PIXELCMS_CONDITION_0' ) ?></option>
                    <option v-bind:value="item.id" v-for="item in conditions">{{ item.name }}</option>
                </select>
            </div>
        <?php endif; ?>
        <div class="select-group" v-if="dealers.length > 1">
          <label for="filterCategory"><?php echo JText::_( 'COM_PIXELCMS_DEALER' ) ?></label>
          <select v-model="filters.dealer" id="filterDealer">
            <option v-bind:value="false" selected><?php echo JText::_( 'COM_PIXELCMS_SELECT_DEALER' ) ?></option>
            <option v-bind:value="item.id" v-for="item in dealers">{{ item.name }}</option>
          </select>
        </div>
        <!-- 		<select v-model="filters.age" placeholder="Alter">
			<option v-bind:value="false" selected><?php echo $locale->select_age ?></option>
			<option v-bind:value="item.id" v-for="item in ages"><?php echo $locale->newer_than ?></option>
		</select> -->
        <div class="filter__result_text">
            <span v-if="filteredData.length == 1"><?php echo JText::_( 'COM_PIXELCMS_ITEM_1' ) ?></span>
            <span v-else><?php echo JText::_( 'COM_PIXELCMS_ITEM_2' ) ?></span>
        </div>
    </div>
    <div  class="pagination" v-if="(pages > 1)" ref="topPagination">
        <ul>
            <li v-on:click="setPage(currentPage - 1)" v-bind:class="{ disabled: (currentPage == 1) }"><?php echo JText::_( 'COM_PIXELCMS_PREV_PAGE' ) ?></li>
            <li v-if="pagination[0] !== 1">...</li>
            <li v-on:click="setPage(page)" v-for="page in pagination" v-bind:class="{ active: (page == currentPage) }">{{ page }}</li>
            <li v-if="pagination[4] && pagination[4] !== pages">...</li>
            <li v-on:click="setPage(currentPage + 1)" v-bind:class="{ disabled: (currentPage == pages) }"><?php echo JText::_( 'COM_PIXELCMS_NEXT_PAGE' ) ?></li>
        </ul>
    </div>
    <div class="custom ads">
        <div class="ad" v-bind:class="{'ad--offer': product.offer}" v-for="(product, index) in paginatedData">
            <a v-on:click="saveURL" class="ad__image" v-bind:class="{'ad__image--empty': product.images.length === 0}" v-bind:href="product.link">
                <div v-if="product.images[0]" class="ad__image__wrapper" v-bind:style="{ backgroundImage: 'url(\'' + ((product.images[0]) ? product.images[0].href + '?width=500&quality=90' : '') + '\')' }"></div>
                <div v-else class="ad__image__wrapper ad__image__wrapper--empty"></div>
				        <div class="ad__price" v-if="product.price.values && product.price.values.netto">
                    <div>
                      <del v-if="product.price.values.old">{{ formatPrice(product.price.values.old) }}</del>
                      <span v-if="product.vat.separable">{{ "<?php echo JText::_( 'COM_PIXELCMS_NETTO_SPRINTF' ) ?>" | sprintf(formatPrice(product.price.values.netto)) }}</span>
                      <span v-else>{{ formatPrice(product.price.values.netto) }}</span>
                    </div>
                    <div v-if="product.vat.separable">
                      <span>{{ "<?php echo JText::_( 'COM_PIXELCMS_BRUTTO_SPRINTF' ) ?>" | sprintf(formatPrice(product.price.values.brutto)) }}</span>
                    </div>
                    <div v-else>
                      <span><?php echo JText::_( 'COM_PIXELCMS_VAT_NOT_SEPARABLE' ) ?></span>
                    </div>
                </div>
                <div class="ad__price" v-else><?php echo JText::_( 'COM_PIXELCMS_ASK_FOR_PRICE' ) ?></div>
            </a>
            <h3><span v-if="product.manufacturer">{{product.manufacturer.value}}</span> <span v-if="product.model">{{product.model}}</span></h3>
            <div v-if="product.year"><?php echo JText::_( 'COM_PIXELCMS_BUILD_YEAR' ) ?>: {{product.year}}</div>
            <div v-if="product.power"><?php echo JText::_( 'COM_PIXELCMS_POWER' ) ?>: {{product.power.kW}} kw ({{product.power.PS}} PS)</div>
            <div v-if="product.workhours"><?php echo JText::_( 'COM_PIXELCMS_WORKHOURS' ) ?>: {{product.workhours.show}}</div>
            <div v-if="!product.workhours && !product.power && !product.year" class="layout-spacer"></div>
            <a v-on:click="saveURL" class="ad__button" v-bind:href="product.link"><?php echo JText::_( 'COM_PIXELCMS_READ_MORE' ) ?></a>
        </div>
        <div v-if="paginatedData.length == 0" class="ad__empty">
            Leider ergab Ihre Suche keinen Treffer.
        </div>
    </div>
    <div class="pagination" v-if="(pages > 1)">
      <ul>
        <li v-on:click="setPage(currentPage - 1)" v-bind:class="{ disabled: (currentPage == 1) }"><?php echo JText::_( 'COM_PIXELCMS_PREV_PAGE' ) ?></li>
        <li v-if="pagination[0] !== 1">...</li>
        <li v-on:click="setPage(page)" v-for="page in pagination" v-bind:class="{ active: (page == currentPage) }">{{ page }}</li>
        <li v-if="pagination[4] !== pages">...</li>
        <li v-on:click="setPage(currentPage + 1)" v-bind:class="{ disabled: (currentPage == pages) }"><?php echo JText::_( 'COM_PIXELCMS_NEXT_PAGE' ) ?></li>
      </ul>
    </div>
</div>
<?php if ($model === 'tracktorpool_products' ): ?>
<div class="traktorpool-copyright">
    Ein Service von <a target="_blank" href="<?php echo "https://www.traktorpool.de/{$this->params->get('tracktorpool_alias', '')}/" ?>"><img src="https://www.traktorpool.de/images/frontend/de/logo.svg" alt="Traktorpool"></a>
</div>
<?php endif; ?>
