<?php
$doc = JFactory::getDocument();

$lang = JFactory::getLanguage();
$langCode = $lang->getTag();
$langCodeShort = substr($langCode, 0, 2);
$jinput = JFactory::getApplication()->input;

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

$locale = $this->locale;

$ad = $this->ads;

$conditions = [
    'used' => 'Gebraucht',
    'new' => 'Neu',
];

JHtml::_('jquery.framework');

$doc->addScript( JUri::base(true) . '/media/com_pixelcms_articles/js/jquery.colorbox-min.js' );
$doc->addStyleSheet( JUri::base(true) . '/media/com_pixelcms_articles/css/colorbox.css' );

$script = "
    function goBack() {
        (window.sessionStorage.getItem('product_link')) ? window.location.replace(window.sessionStorage.getItem('product_link')) : window.history.back()
    };
	jQuery( document ).ready(function() {
		jQuery('.product__images__thumbs a').colorbox({
			rel:'gal',
			scrolling: false,
			maxHeight: '80%',
			maxWidth: '80%',
			fixed: true,
			className: 'droppics'
		});
	});
";
$doc->addScriptDeclaration( $script );

$html = '<div class="product">';
$html .= '<div class="product__images">';
if (count($ad->images) > 0) {
    $html .= "<img class=\"product__images__big\" src=\"{$ad->images[0]->href}\">";
    $html .= '<div class="product__images__thumbs">';
    foreach ($ad->images as $key => $image) {
        $html .= "<a href=\"$image->href\"><img class=\"product__images\" src=\"$image->href?width=150\"></a>";
    }
    $html .= '</div>';
} else {
    $html .= "<div class=\"product__images__big product__images__big--empty\"></div>";
}

if ($this->params->get('show_contact', false)) {
// Ansprechpartnermodul
    if ($ad->contact_persons) {
        $html .= '<div class="ad_contact">';
        $html .= '<h3>Ansprechpartner</h3>';
        $html .= '<div class="ad_contact_wrapper">';
        foreach ($ad->contact_persons as $key => $contact) {
            $html .= '<div class="contact-card">';

            if ($contact->image && $contact->image->url) {
                $html .= '<div class="contact-card__image">';
                $html .= "<div><img src='{$contact->image->url}' /></div>";
                $html .= '</div>';
            }

            $html .= '<div class="contact-card__desc">';

            if (trim($contact->description)) {
                $html .= "<h4 class='contact-card__desc_name'>{$contact->description}</h4>";
            }

            $html .= '<table class="contact-card__desc_table">';
            $html .= "<tr><td>E-Mail</td><td><a href='mailto:{$contact->email}'>{$contact->email}</a></td></tr>";

            if ($contact->phone && $contact->phone->call_number) {
                $html .= "<tr><td>Telefon</td><td><span>{$contact->phone->country_code} {$contact->phone->area_code} {$contact->phone->call_number}</span></td></tr>";
            }
            if ($contact->mobile && $contact->mobile->call_number) {
                $html .= "<tr><td>Mobil</td><td><span>{$contact->mobile->country_code} {$contact->mobile->area_code} {$contact->mobile->call_number}</span></td></tr>";
            }
            if ($contact->fax && $contact->fax->call_number) {
                $html .= "<tr><td>Fax</td><td><span>{$contact->fax->country_code} {$contact->fax->area_code} {$contact->fax->call_number}</span></td></tr>";
            }

            $html .= '</table>';

            $html .= '</div>'; // contact_person__desc

            $html .= '</div>'; // ad__contact_person
        }
        $html .= '</div>'; // ad_contact_wrapper Ende
        $html .= '</div>'; // ad_contact Ende
    }
}
$html .= '</div>';
$html .= '<div class="product__description">';
$html .= "<h1>" . implode(' ', [$ad->manufacturer->value, $ad->model]) . "</h1>";
if (isset($ad->dealer_internal_id)) {
	$html .= "<small data-label='" . JText::_( 'COM_PIXELCMS_INTERNAL_ID' ) . "' class='product__description__internal_id'>$ad->dealer_internal_id</small>";
}
if ($this->params->get('print_btn')) {
    $datasheetLink = "https://www.traktorpool.de/search/detail/printpreview/machine_id/$ad->id/nocrawl/1/";

    if ($this->params->get('maschinen_datenblatt_type', 'default') === 'custom'
        || $model !== 'tracktorpool_products'
        || ($model === 'tracktorpool_products' && $ad->status !== 'active')) {
        $query = http_build_query([
            'articleId' => $ad->id,
            'Itemid' => $this->params->get('Itemid'),
            'format' => 'pdf',
        ]);
        $datasheetLink = JRoute::_("index.php?$query");
    }
    $html .= "<a class=\"product__description__download\" href=\"$datasheetLink\" target='_blank' rel=\"noopener noreferrer\"><img src=\"/media/jce/icons/pdf.png\"> Datenblatt</a>";
}

$html .= '<table class="product__description__details">';
if (isset($ad->dealer)) {
    $dealerStr = ($ad->dealer->city) ? "{$ad->dealer->zip} {$ad->dealer->city}" : $ad->dealer->name;
    $html .= "<tr><td>Standort</td><td>$dealerStr</td></tr>";
}
$html .= "<tr><td>".JText::_( 'COM_PIXELCMS_MANUFACTURER' )."</td><td>{$ad->manufacturer->value}</td></tr>";
if (isset($ad->condition)) $html .= "<tr><td>".JText::_( 'COM_PIXELCMS_CONDITION' )."</td><td>" . JText::_( trim('COM_PIXELCMS_CONDITION_'.strtoupper($ad->condition->id)) ) . "</td></tr>";
if (isset($ad->year) && $ad->year) $html .= "<tr><td>".JText::_( 'COM_PIXELCMS_BUILD_YEAR' )."</td><td>{$ad->year}</td></tr>";
if (isset($ad->workhours) && $ad->workhours->show) if ($ad->workhours && $ad->workhours->show) $html .= "<tr><td>".JText::_( 'COM_PIXELCMS_WORKHOURS' )."</td><td>{$ad->workhours->show}</td></tr>";
if (isset($ad->power)) $html .= "<tr><td>".JText::_( 'COM_PIXELCMS_POWER' )."</td><td>{$ad->power->kW} kW ({$ad->power->PS} PS)</td></tr>";
if (isset($ad->max_speed) && $ad->max_speed->show) $html .= "<tr><td>{$ad->max_speed->name}</td><td>{$ad->max_speed->show}</td></tr>";
if (isset($ad->work_width) && $ad->work_width->show) $html .= "<tr><td>{$ad->work_width->name}</td><td>{$ad->work_width->show}</td></tr>";
if (isset($ad->cylinders) && $ad->cylinders->value) $html .= "<tr><td>{$ad->cylinders->name}</td><td>{$ad->cylinders->value}</td></tr>";
if (isset($ad->transmission) && $ad->transmission->show) $html .= "<tr><td>{$ad->transmission->name}</td><td>{$ad->transmission->show}</td></tr>";
if (isset($ad->tyre_type)) $html .= "<tr><td>".JText::_( 'COM_PIXELCMS_TYRE_TYPE' )."</td><td>{$ad->tyre_type}</td></tr>";
if (isset($ad->rim_diameter) && $ad->rim_diameter->value) $html .= "<tr><td>{$ad->rim_diameter->name}</td><td>{$ad->rim_diameter->show}</td></tr>";
if (isset($ad->available) && $ad->available->value) $html .= "<tr><td>{$ad->available->name}</td><td>{$ad->available->value}</td></tr>";
if (isset($ad->_3_point_hitch) && $ad->_3_point_hitch->show) $html .= "<tr><td>{$ad->_3_point_hitch->name}</td><td>{$ad->_3_point_hitch->show}</td></tr>";

if ($ad->additional) {
    foreach ($ad->additional as $value) {
        $html .= "<tr><td>{$value->name}</td><td>{$value->show}</td></tr>";
    }
}

if ($ad->equipment) {
    $html .= "<tr><td>".JText::_( 'COM_PIXELCMS_EQUIPMENT' )."</td><td><ul>";
    foreach ($ad->equipment as $key => $value) {
        $html .= "<li>$value</li>";
    }
    $html .= "</ul></td></tr>";
}
if ((isset($ad->front_wheels->type) && $ad->front_wheels->type)|| (isset($ad->back_wheels->type) && $ad->back_wheels->type)) {
    $html .="<td>".JText::_( 'COM_PIXELCMS_WHEELING' )."</td><td>";
    if ($ad->front_wheels->type) {
        if ($ad->back_wheels->type) {
            $html .= JText::_( 'COM_PIXELCMS_FRONT' ).": {$ad->front_wheels->type}";
            if ($ad->front_wheels->quality) {
                $html .=  " / {$ad->front_wheels->quality}%";
            }
            $html .= "<br>".JText::_( 'COM_PIXELCMS_BACK' ).":  {$ad->back_wheels->type}";
            if ($ad->back_wheels->quality) {
                $html .=  " / {$ad->back_wheels->quality}%";
            }
        } else {
            $html .="{$ad->front_wheels->type}";
            if ($ad->front_wheels->quality) {
                $html .=  " / {$ad->front_wheels->quality}%";
            }
        }
    } else if ($ad->back_wheels->type) {
        $html .= "{$ad->back_wheels->type}";
        if ($ad->back_wheels->quality) {
            $html .=  " / {$ad->back_wheels->quality}%";
        }
    }
    $html .="</td></tr>";
}
$html .= '</table>';

if ($ad->free_text) {
    $html .= "<div class='product__description__free_text'>" . nl2br($ad->free_text) . "</div>";
}

$html .= "<div class=\"product__description__price\">";
if (isset ($ad->price) && isset ($ad->price->values) && $ad->price->values->netto > 0) {
    // $fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
    $formatted_netto = format_price($ad->price->values->netto, $this->params->getInt('decimals', 2));
    $formatted_brutto = format_price($ad->price->values->brutto, $this->params->getInt('decimals', 2));

    if ($ad->offer) {
        $formatted_old = format_price($ad->price->values->old, $this->params->getInt('decimals', 2));
        $nettoArr[] = "<del>$formatted_old {$ad->price->currency}</del>";
    }
    $nettoArr[] = "$formatted_netto {$ad->price->currency}";

    if (!$ad->vat->separable) {
        $html .= implode(' ', $nettoArr);
        $html .= '<small>' . JText::_( 'COM_PIXELCMS_VAT_NOT_SEPARABLE' ) . '</small>';
    } else {
        $html .= JText::sprintf('COM_PIXELCMS_NETTO_SPRINTF', implode(' ', $nettoArr));
        if ($ad->vat->value) {
            $sprintf_suffix = ($ad->vat->value !== 0.19) ? '_SHOW_VAT' : '';
            $html .= "<small>".JText::sprintf( 'COM_PIXELCMS_BRUTTO_SPRINTF' . $sprintf_suffix, "$formatted_brutto {$ad->price->currency}", $ad->vat->value * 100 ). "</small>";
        }
    }
} else {
    $html .= JText::_( 'COM_PIXELCMS_ASK_FOR_PRICE' );
}
$html .= "</div>";


$html .= '</div>';
$html .= '</div>';

$html .= '<span onclick="goBack()" class="back_to_overview ad__button">' . JText::_( 'COM_PIXELCMS_BACK_TO_OVERVIEW' ) . '</span>';

$relatedAds =  $this->relatedAds;

if ($relatedAds) {
    $html .= "<h2>".JText::_( 'COM_PIXELCMS_RELATEDADS' )." {$ad->category->name}</h2>";
    $html .= '<div class="custom ads">';
    foreach (array_slice( $relatedAds, 0, 3) as $key => $ad) {
        $html .= '<div class="ad">';
        if (count($ad->images) > 0) {
            $html .= "<a class=\"ad__image\" href=\"$ad->link\">";
            $html .= "<div href=\"$ad->link\" class=\"ad__image__wrapper\" style=\"background-image:url({$ad->images[0]->href})\"></div>";
        } else {
            $html .= "<a class=\"ad__image ad__image--empty\" href=\"$ad->link\">";
            $html .= "<div href=\"$ad->link\" class=\"ad__image__wrapper\"></div>";
        }

        $priceStyle = $this->params->get('price_style');
        $html .= '<div class="ad__price">';

        if (isset($ad->price->values) && $ad->price->values->netto > 0) {
            // $fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
            $formatted_netto = format_price($ad->price->values->netto, $this->params->getInt('decimals', 2));
            $formatted_brutto = format_price($ad->price->values->brutto, $this->params->getInt('decimals', 2));

            $nettoArr = [];
            if ($ad->offer) {
                $formatted_old = format_price($ad->price->values->old, $this->params->getInt('decimals', 2));
                $nettoArr[] = "<del>$formatted_old {$ad->price->currency}</del>";
            }
            $nettoArr[] = "$formatted_netto {$ad->price->currency}";

            if (!$ad->vat->separable) {
                $html .= implode(' ', $nettoArr);
                $html .= '<div>' . JText::_( 'COM_PIXELCMS_VAT_NOT_SEPARABLE' ) . '</div>';
            } else {
                $html .= JText::sprintf('COM_PIXELCMS_NETTO_SPRINTF', implode(' ', $nettoArr));
                if ($ad->vat->value) {
                    $html .= "<div>".JText::sprintf( 'COM_PIXELCMS_BRUTTO_SPRINTF', "$formatted_brutto {$ad->price->currency}" ). "</div>";
                }
            }
        } else {
            $html .= JText::_( 'COM_PIXELCMS_ASK_FOR_PRICE' );
        }
//
//        if (isset($ad->price->values) && $ad->price->values->netto > 0) {
//            if (in_array($priceStyle, [0,1,3,4])) {
//                $html .= "<div> ".JText::_(  in_array($priceStyle, [0,1]) ?  'COM_PIXELCMS_NETTO' : 'COM_PIXELCMS_NETTO_SHORT' )." " . number_format($ad->price->values->netto, 2, ',', '.') . " {$ad->price->currency}"  . "</div>";
//            }
//            if (in_array($priceStyle, [0,2,3,5]) && $ad->vat->value) {
//                $html .= "<div> ".JText::_(  in_array($priceStyle, [0,2]) ?  'COM_PIXELCMS_BRUTTO' : 'COM_PIXELCMS_BRUTTO_SHORT' )." " . number_format($ad->price->values->brutto, 2, ',', '.') . " {$ad->price->currency}"  . "</div>";
//            }
//        } else {
//            $html .= "<div>".JText::_( 'COM_PIXELCMS_ASK_FOR_PRICE' )."</div>";
//        }
        $html .= "</div>";
        $html .= "</a>";

        $html .= "<h3>".implode(' ', [$ad->manufacturer->value, $ad->model])."</h3>";
        if (isset($ad->year) && $ad->year) {
            $html .= "<div>".JText::_('COM_PIXELCMS_BUILD_YEAR').": {$ad->year}</div>";
        }
        if ($ad->power) {
            $html .= "<div>".JText::_('COM_PIXELCMS_POWER').": {$ad->power->kW} kW ({$ad->power->PS} PS)</div>";
        }
        if (isset($ad->workhours) && $ad->workhours->show) {
            $html .= "<div>".JText::_('COM_PIXELCMS_WORKHOURS').": {$ad->workhours->show}</div>";
        }

        $html .= "<a class=\"ad__button\" href=\"$ad->link\">".JText::_('COM_PIXELCMS_READ_MORE')."</a>";

        $html .= '</div>';
    }
    $html .= '</div>';
}
if ($model === 'tracktorpool_products'):
    $html .= "<div class=\"traktorpool-copyright\">Ein Service von <a target=\"_blank\" href=\"https://www.traktorpool.de/{$this->params->get('tracktorpool_alias')}/\"><img src=\"https://www.traktorpool.de/images/frontend/de/logo.svg\" alt=\"Traktorpool\"></a></div>";
endif;

echo $html;
