<?
  $sessionrequired=0;
  $nologsessionstart=1; // log after bot checks..
  $protectedpage=1;
  require "includes/sessionhandler.php";
  
  if (!isset($_GET["setid"]) || !is_valid($_GET["setid"]))
  {
    // die("Go away");
    // Delay this response
    \Kiobi\Utils\AntiBot::backOff();
    // And redirect to blocking page
    Header("Location: /b?u=blocked/info");
    return;
  }
  else
  {
    $setid = intval($_GET["setid"]);
  }
  
  $nolog = false;
  
  // A newguid request and the order parameter? Scraping 
  if ($newguid && $_GET['order'])
  {
    $nolog=true;
  }
  
  // if we came here, log the entrytag when we are allowed to log
  if ($delayedsessionstartlogging && !$nolog) {
    $entrytag = $_SESSION['entrytag']??null;
    log_session_start($entrytag);
  }
  
  if (!isset($dbQuery)) { $dbQuery = new \Kiobi\Database\Query(); }
  
  $query = "select 
 sets.siteid, sets.title, sets.altimages, sets.setrating, sets.setvotes, sr.price, sr.lastprice, sr.lowestprice, IFNULL(sr.rrp, sets.rrp) as rrp, sr.localrrp, ean, UNIX_TIMESTAMP(sets.added_at) as added_at, UNIX_TIMESTAMP(sr.updated_at) as updated_at,
sr.siteid, sites.title as sitetitle, sites.weight, sets.status, IFNULL(d.title, sets.title) as localtitle, IFNULL(d.shortdescription, sets.description) as shortdescription , d.description, d.features, sss.shipping from sets join sets_region sr on sets.setid=sr.setid and sr.regionid=".REGION."  and sr.status='A' 
join sites on sr.siteid=sites.siteid left join descriptions_sets d on sets.setid=d.setid and d.language='".LANGUAGE."' 
left join sites_sets_shipping sss on sets.setid=sss.setid and sr.siteid=sss.siteid and sss.regionid=".REGION." where sets.setid=$setid";
  $row = getCachedRow($query, 60);
  
  if (!$row)
  {
    // Retry overall
    $query = "select sets.siteid, sets.altimages, sets.setrating, sets.setvotes, sets.title, price, lastprice, lowestprice, rrp, ean, UNIX_TIMESTAMP(added_at) as added_at, UNIX_TIMESTAMP(sets.updated_at) as updated_at, sites.title as sitetitle, sites.weight, sets.status, IFNULL(d.title, sets.title) as localtitle, IFNULL(d.shortdescription, sets.description) as shortdescription , d.description, d.features, sss.shipping from sets left join sites on sets.siteid=sites.siteid
left join descriptions_sets d on sets.setid=d.setid and d.language='".LANGUAGE."' left join sites_sets_shipping sss on sets.setid=sss.setid and sets.siteid=sss.siteid and regionid=".REGION." where sets.setid=$setid";
    $row = getCachedRow($query, 60);
  }
  
  // hardcoded localtile fix for speelwatch
  if (LANGUAGE <> 'nl')
  {
    $query = "select s.setid, s.title, dsnl.title as nltitle, dslocal.title as localtitle from sets s left join descriptions_sets dsnl on s.setid=dsnl.setid and dsnl.language='nl' left join descriptions_sets dslocal on s.setid=dslocal.setid and dslocal.language='".LANGUAGE."' where s.setid=$setid";
    $row3 = getCachedRow($query);
    if ($row3)
    {
      // Override with nltitle if no local title
      if (!$row3['localtitle'] && $row3['nltitle'])
      {
        $row['localtitle'] = $row3['nltitle'];
      }
    }
  }
  
  // $row is set if we found something about this set
  if ($row)
  {
    // Now check the url and redirect iff needed
    $wanted = '/'.LOCALE.'/set/'.$setid.'/'.escape($row['title']).'.html';
    $safari = '/'.LOCALE.'/set/'.$setid.'/undefined';
    $uri = parse_url($_SERVER['REQUEST_URI']);
    // undefined safari hits?
    if ($uri['path'] == $safari)
    {
      Header("Location: /b?u=blocked");
      return;
    }
    else if ($wanted <> $uri['path']) // fix path
    {
      Header("Location: $wanted".($uri['query'] ? '?'.$uri['query'] : ''), true , 301);
      return;
    }
    
    $title = htmlspecialchars($row['title']);
    $price = $row['price'];
    $rrp = $row['rrp'];
    $ages = $row['ages'];
    $localrrp = $row['localrrp'];
    $lastprice = $row['lastprice'];
    $description = $row['description'];
    $features = $row['features'];
    $added_at = $row['added_at'];
    $updated_at = is_null($row['updated_at']) ? $row['added_at'] : $row['updated_at'];
    $siteid = $row['siteid'];
    $sitetitle = $row['sitetitle'];
    $status=$row['status'];
    $lowprice = $row['lowestprice'];
    $ean = $row['ean'];
    $altimages = intval($row['altimages']);
    $setrating = round($row['setrating'], 1);
    $setvotes = intval($row['setvotes']);
    if (!$lowprice) { $lowprice = $price; }
    // Extra
    $localtitle = htmlspecialchars($row['localtitle']);
    $shortdescription = $row['shortdescription'];
    $shipping = $row['shipping'];
    $nolocaldelivery = is_null($row['shipping']);
    $hasinstructions = in_array($row['hasinstructions'], array('Y', 'A')) ? $row['hasinstructions'] : '';
    // Check if there is another site with the same price in the current region
    if ($nolocaldelivery)
    {
      $query = "select ss.siteid, s.title as sitetitle, sss.shipping from sites_sets ss join sites s on ss.siteid=s.siteid join currencies c on s.currencyid=c.currencyid join sites_sets_shipping sss on ss.siteid=sss.siteid and ss.setid=sss.setid and sss.regionid=".REGION." where ss.setid=$setid and availability='A' and s.status in ('A','F') and sss.shipping is not null and ss.price='$price'";
      $row2 = getCachedRow($query, 60); // 60 seconds on set page info. Just avoid lotsa queries around extra emails etc.
      if ($row2)
      {
        $siteid=$row2['siteid'];
        $sitetitle=$row2['sitetitle'];
        $shipping=$row2['shipping'];
        $nolocaldelivery = is_null($row2['shipping']);
      }
    }
    // Override the X to I (X is for updaters only)
    if ($status == 'X') { $status = 'I'; }
    // No local delivery? Set site status to 'I' to show the 'add to your speelwatch' links
    if ($nolocaldelivery) { $status='I'; }
    
    // Do we need to check for a premium site delivered cheaper w/ heigher weight value (eg: amazon/bol pricematching?
    $premiumoverride = false;
    
    $query = "select 
s.siteid,
s.title as sitetitle,
s.weight,
ss.price,
sss.shipping,
ss.price+sss.shipping as deliveredprice
from 
sites_sets ss join sites s on ss.siteid=s.siteid join sites_sets_shipping sss on ss.siteid=sss.siteid and ss.setid=sss.setid and sss.regionid=".REGION." 
where ss.setid=$setid and availability='A' and s.status in ('A','F') and (s.throttle & ".Kiobi\Utils\Throttle::SETPAGE." = 0) 
order by round(deliveredprice,2) asc, s.weight desc
LIMIT 0,1";
    $row2 = getCachedRow($query, 60);
    if ($row2)
    {
      if ((round($row2['deliveredprice'],2) <= round($price + $shipping, 2))  && ($row2['weight'] > 0))
      {
        // A premium partner is cheaper delvivered at home
        $premiumoverride = true;
        $premiumsiteid = $row2['siteid'];
        $premiumsitetitle = $row2['sitetitle'];
        $premiumprice = $row2['price'];
        $premiumshipping = $row2['shipping'];
      }
    }
  }
  else
  {
    Header("Location: /");
    return;
  }
  
  // Extra check for not logged in
  // Brickwatch all is weighted, but Speelwatch isn't, so still used
  if (!isLoggedIn() && !$premiumoverride)
  {
    // Is there any premium site at all with a price set ?
    $query = "select 
  s.siteid,
  s.title as sitetitle,
  s.weight,
  ss.price,
  sss.shipping,
  ss.price+sss.shipping as deliveredprice
from 
  sites_sets ss join sites s on ss.siteid=s.siteid join sites_sets_shipping sss on ss.siteid=sss.siteid and ss.setid=sss.setid and sss.regionid=".REGION." 
  where ss.setid=$setid and availability='A' and s.status in ('A','F') and s.weight > 0 and (s.throttle & ".Kiobi\Utils\Throttle::SETPAGE." = 0) 
  order by deliveredprice asc, s.weight desc
LIMIT 0,1";
    $row2 = getCachedRow($query, 60);
    if ($row2)
    {
      // We fake a premium partner 
      $premiumoverride = true;
      $premiumsiteid = $row2['siteid'];
      $premiumsitetitle = $row2['sitetitle'];
      $premiumprice = $row2['price'];
      $premiumshipping = $row2['shipping'];
      $ALLSITES = 0;
      // This happens when premium site-site is disabled in between updates, so no premiumoverride set
      //sendAdminEmail("We hit the unknown abyss...", "Temporary state for set $setid / $siteid / ".REGION);
    }
  }
  
  $highprice = $price;
  
  // TODO: swicth to localprice and exchangerate etc.
  $query = "SELECT min(minprice) as minprice, max(maxprice) as maxprice FROM pricechange_region WHERE minprice > 0 and setid=$setid and regionid in (0, ".REGION.')';
  $row = getCachedRow($query, 60); // ONce a minute
  if ($row)
  {
    $highprice = $row['maxprice'];
    if (!$lowprice) { $lowprice = $row['minprice']; }
  }
  
  // Could be done in a single query before, but hey...
  $query = "SELECT min(minprice) as recentlowprice FROM pricechange_region where setid=$setid and regionid=".REGION." and minprice > 0 and date >= date_add(NOW(), interval -6 month )";
  $row = getCachedRow($query, 60); // ONce a minute
  $recentlowprice = ($row) ? doubleval($row['recentlowprice']) : 0;
  
  $discount = sprintf("%.0f",(($rrp-$price)/$rrp)*100);
  
  $mainbrandid = 0;
  $mainbrand = '';
  $mainbrandlogo = false;
  // Main brand
  $query = "SELECT b.brandid, b.title, b.haslogo from brands_sets bs join brands b on bs.brandid=b.brandid where bs.setid=$setid and b.visible='Y' and bs.forced in ('Y','N') order by bs.forced asc, weight desc, title asc LIMIT 0,1";
  $row = getCachedRow($query); // default 10 minutes
  if ($row)
  {
    $mainbrandid = $row['brandid'];
    $mainbrand = $row['title'];
    $mainbrandlogo = ($row['haslogo'] == 'Y');
    $breadcrumbs = array(
      [
        'url'=>'/brands',
        'name'=>t('Brands')
      ],
      [
        'url'=>'/brands/'.$mainbrandid.'/'.escape($mainbrand),
        'name'=>$mainbrand,
        'image'=>($mainbrandlogo ? 'https://cdn.kiobi.com/images/speelwatch/brands/'.strtolower(escape($row['title'])).'.png' : false)
      ]
    );
  }
  
  $pagetitle = $localtitle;
  if ($mainbrandid)
  {
    $pagetitle = (stristr($localtitle, $mainbrand)) ? $localtitle : "$mainbrand $localtitle";
  }
  if ($status == 'A') {
    $pagetitle .= '. '.t('Now').' '.getDisplayPrice($price);
    $pagetitle .= ' '.t('at').' '.$sitetitle;
    //$pagetitle .= ', '.$discount.'% '.t('below').' '.strtolower(t('The')).' '.t('Lego retail price');
  }
  
  // maintitle is just the title tag. pagetitle alsoo has more description
  $pagemaintitle = $pagetitle;
  $pagetitle  = t('Info for ').$pagetitle;
  
  // Meta description for google needs to differ per region
  $ogdescription = $pagetitle.'. '.t('Delivered to').' '.t('region-'.REGION);
  $ogdescription .= ($shortdescription) ? '. '.$shortdescription : t('header.extra');
  // And less then 160 chars for msn, so shortened version
  $pagedescription = $localtitle;
  if ($mainbrandid)
  {
    $pagedescription = (stristr($localtitle, $mainbrand)) ? $localtitle : "$mainbrand $localtitle";
  }
  if ($status == 'A') {
    $pagedescription .= '. '.t('Now').' '.getDisplayPrice($price, '€');
    $pagedescription .= ' '.t('at').' '.$sitetitle;
    if ($discount > 4) {
      $pagedescription .= str_replace('{price}', $discount.'%', t(', a {price} discount!'));
    }
    else
    {
      $pagedescription .= '.';
    }
    $pagedescription .= ' '. t('Delivered to').' '.t('region-'.REGION).'.';
  }
  else
  {
    $pagedescription .= '. '.t('No longer available').' '.t('in').' '.t('region-'.REGION).'.';
  }
  // Add pagedescription
  if ((strlen($pagedescription) < 150) && ($shortdescription)) {
    $pagedescription .= ' '.$shortdescription;
  }
  
  // ?? $nologout = 1;
  $image_src = "https://cdn.kiobi.com/images/speelwatch/sets/$setid.jpg";
  list($image_width, $image_height, $dummy1, $dummy2) = @getimagesize('/export/kiobi/cdn/images/speelwatch/sets/'.$setid.'.jpg');
  
  $ISPRODUCTPAGE = true;
  $headerinject = "<link rel='preload' as='image' href='https://cdn.kiobi.com/images/speelwatch/sets/$setid.jpg' fetchpriority='high'>";
  include "includes/header.php";
  include "includes/set.php";
  $pushinject = "<img src='/images/view/set/$setid.gif' width=1 height=1 alt=''>";
  $scriptinject .= "<script src='https://cdn.kiobi.com/js/tags.js'></script>";
  include "includes/footer.php";
?>