<?php
/*shows product desc at the bottom of product image*/
//get shop page's title
$t = $site->pageTitle($s['shop_page']);
$seo_pageTitle = seo_str($t);
//get product id and info
$pid = $site->productFromKey($_GET['junk']);
$product = $site->productInfo($pid);
$hideIfVirtual = ($product['virutal_product'] == 'y') ? ' style="display:none;"' : '';
//if product has been deleted or set to not show
if ($product['hide'] == 'y' || (int) $product['cat'] == 0)
{
    header("Location: /2/Error");
    exit;
}
//get cat live status
$catStatus = $mysql->get_array($mysql->query("live", "fs_shop_cats", "ID = {$product['cat']} LIMIT 1"));
//if cat is not live, redirect to error page
if ($catStatus['live'] == 'n')
{
    header("Location: /2/Error");
    exit;
}
//add to cart and redirect to basket page
if (isset($_POST['qty']))
{
    $now = time();
    $owner = $_SESSION['owner'];
//if order owner is empty, make uid
    if (empty($_SESSION['owner']))
    {
        $owner = 'FS'.substr(add_codes(''), 0, -3);
        $check = $mysql->num_rows($mysql->query("ID", "fs_shop_orderdata", "owner = '$owner' AND temp = 'n' LIMIT 1"));
        $owner .= ($check > 0) ? $check : 0;
        $_SESSION['owner'] = $owner;
        $mysql->insert("fs_shop_orderdata", "owner,temp,shipped,stamp", "$owner,y,n,$now");
    }
//virtual product
    $prdinfo = $site->productInfo($pid);
    $virtual = ($prdinfo['virutal_product'] == 'y') ? 'y' : 'n';
//setup insert into cart
    $post = $form->clean_fields($_POST);
    $price = ($product['sale_price'] > 0) ? $product['sale_price'] : $product['price'];
    $qty = ((int) $post['qty'] == 0) ? 1 : $post['qty'];
//check out
    $stock = $mysql->get_array($mysql->query("stock,plus_price", "fs_shop_stock", "pid = $pid AND `option` = '{$post['option']}' LIMIT 1"));
    $price += $stock['plus_price'];
    if ((int) $stock['stock'] <= $qty)
    {
        $qty = $stock['stock'];
    }
//out of stock
    if ((int) $stock['stock'] <= 0)
    {
        header("Location: /{$s['shop_page']}/$seo_pageTitle/{$prdinfo['url_key']}");
        exit;
    }
//insert
    $check = $mysql->num_rows($mysql->query("ID", "fs_shop_cart", "owner = '$owner' AND pid = $pid AND `option` = '{$post['option']}' AND `custom_field_val` = '{$post['custom_field_val']}' LIMIT 1"));
    if ($check == 0)
    {
        $mysql->insert("fs_shop_cart", "owner,pid,option,qty,price,item_name,stamp,temp,virtual,custom_field_val,price_incs_gst", "$owner,$pid,{$post['option']},$qty,$price,".str_replace(",", "&#8218;", addslashes($product['name'])).",$now,y,$virtual,{$post['custom_field_val']},{$product['price_incs_gst']}");
    }
    else
    {
        $_SESSION['alreadyInCart'] = 'yes';
    }
    header("Location: /{$s['shop_page']}/$seo_pageTitle/Basket");
    exit;
}
//add meta tags to the page if showing a sub category
$array['page_title'] = (!empty($product['meta_title'])) ? $product['meta_title'] : $array['page_title'];
$array['keywords'] = (!empty($product['meta_keywords'])) ? $product['meta_keywords'] : $array['keywords'];
$array['meta_desc'] = (!empty($product['meta_desc'])) ? $product['meta_desc'] : $array['meta_desc'];
//bread crumbs
$jsonBC = '';
if (!empty($product['cat']))
{
    $c = explode("\n", $site->cat_levels($product['cat']));
    if (is_array($c))
    {
        $y = 1;
        $crumbs .= '<a href="/'.$s['shop_page'].'/'.$seo_pageTitle.'">'.$t.'</a> &gt; ';
        $jsonBC .= '{
            "@type": "ListItem",
            "position": '.$y.',
            "item":
            {
                "@id": "/'.$s['shop_page'].'/'.$seo_pageTitle.'",
                "name": "'.$t.'"
            }
        },';
        for ($x = 0; $x < sizeof($c); $x++)
        {
            list($key, $name) = explode("#", $c[$x]);
            $crumbs .= (!empty($name)) ? '<a href="/'.$s['shop_page'].'/'.$seo_pageTitle.'/'.$key.'">'.$name.'</a> &gt; ' : '';
            $y++;
            if (!empty($name))
            {
                $jsonBC .= '{
                    "@type": "ListItem",
                    "position": '.$y.',
                    "item":
                    {
                        "@id": "/'.$s['shop_page'].'/'.$seo_pageTitle.'/'.$key.'",
                        "name": "'.$name.'"
                    }
                },';
            }
        }
        $crumbs = substr($crumbs, 0, -6);
        $jsonBC = '<script type="application/ld+json">
        {
            "@context": "http://schema.org",
            "@type": "BreadcrumbList",
            "itemListElement":['.trim($jsonBC, ',').']
        }
        </script>';
    }
}
//json product LD
$pageURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$jsonBC .= '<script type="application/ld+json">
{
    "@context": "https://schema.org/",
    "@type": "Product",
    "name": "'.$product['name'].'",
    "image": "/inc/shop/images/'.$product['mid_image'].'",
    "description": "'.strip_tags(addslashes($product['description'])).'",
    "offers":
    {
        "@type": "Offer",
        "url": "'.$pageURL.'",
        "priceCurrency": "AUD",
        "price": "'.$product['price'].'",
        "priceValidUntil": "'.date('Y-m-d', strtotime("+30 days")).'",
        "itemCondition": "http://schema.org/NewCondition",
        "availability": "http://schema.org/InStock"
    }
}
</script>';
//show product details on the page
$price = '<span content="'.$product['price'].'">'.$site->currency_symbol($product['price']).'</span>';
if ($product['sale_price'] > 0)
{
    $price = '<span class="sale">'.$site->currency_symbol($product['price']).'</span><strong style="padding-left:10px;" content="'.$product['sale_price'].'">'.$site->currency_symbol($product['sale_price']).'</strong>';}
$size = $site->shop_settings('productimage_height,productimage_width');
$details = '<div id="contentInject"></div><h1>'.$t.'</h1><p id="shopCrumbs">'.$crumbs.'</p><img src="/inc/shop/images/'.$product['large_image'].'" alt="'.$product['name'].'" class="ShowForMobile" />';
//extra images for mobile
$Extraquery = $mysql->query("thumb,large", "fs_shop_products_images", "pid = $pid ORDER BY `order` ASC");
if ($mysql->num_rows($Extraquery) > 0)
{
    $details .= '<div class="ShowForMobile" id="extrapix">';
    while ($extra = $mysql->get_array($Extraquery))
    {
        $details .= '<a href="/inc/shop/images/'.$extra['large'].'" class="mlightbox" title="'.$product['name'].'"><img src="/inc/shop/images/clear.gif" height="50" width="50" style="background-image: url(/inc/shop/images/'.$extra['thumb'].');" alt="'.$product['name'].'" /></a>';
    }
    $details .= '</div>';
}
$details .= '<script type="text/javascript">jQuery(\'.mlightbox\').magnificPopup({type:\'image\',gallery:{enabled:true}});</script>';
//
$details .= '<table border="0" cellpadding="0" cellspacing="0" id="details"><tr><th valign="top" class="HideForMobile"><a href="/inc/shop/images/'.$product['large_image'].'" class="lightbox" title="'.$product['name'].'" id="mainpic"><img src="/inc/shop/images/clear.gif" width="'.$size['productimage_width'].'" height="'.$size['productimage_height'].'" alt="'.$product['name'].'" border="0" style="background-image: url(/inc/shop/images/'.$product['mid_image'].');" /></a><img src="/inc/shop/images/'.$product['mid_image'].'" style="display:none;" />';
$ppCurrency = $site->shop_settings('paypal_currency');
//extra images
$Extraquery = $mysql->query("thumb,large", "fs_shop_products_images", "pid = $pid ORDER BY `order` ASC");
if ($mysql->num_rows($Extraquery) > 0)
{
    $details .= '<div id="extrapix">';
    while ($extra = $mysql->get_array($Extraquery))
    {
        $details .= '<a href="/inc/shop/images/'.$extra['large'].'" class="lightbox" title="'.$product['name'].'"><img src="/inc/shop/images/clear.gif" height="50" width="50" style="background-image: url(/inc/shop/images/'.$extra['thumb'].');" alt="'.$product['name'].'" /></a>';
    }
    $details .= '</div>';
}
$details .= '<script type="text/javascript">jQuery(\'.lightbox\').magnificPopup({type:\'image\',gallery:{enabled:true}});</script>';
$details .= '</th><td valign="top"><h2><span>'.$product['name'].'</span><small>'.$price.'</small></h2>
<form id="addtocart" name="addtocart" method="post" action="">
<h3 id="addtocartMsg" style="display:none;">Product has been added to your cart.<div><a href="/'.$s['shop_page'].'/'.$seo_pageTitle.'/Basket">Checkout</a> | <a href="#" onclick="jQuery(\'#addtocartMsg\').hide();return false;">Continue shopping</a></div></h3>
<table border="0" cellspacing="0" cellpadding="0">';
$inStock = $site->in_stock($pid);
//product options
$basePrice = ($product['sale_price'] > 0) ? $product['sale_price'] : $product['price'];
if ($inStock == true)
{
    $stockQuery = $mysql->query("`option`,stock,plus_price", "fs_shop_stock", "pid = $pid ORDER BY ID ASC");
    $numOptions = $mysql->num_rows($stockQuery);
    if ($numOptions == 1)
    {
        $stockData = $mysql->get_array($stockQuery);
        $details .= '<tr'.$hideIfVirtual.'><td>'.$product['stock_label'].':</td><td>'.$stockData['option'].'<input type="hidden" name="option" id="option" value="'.$stockData['option'].'" /></td></tr>';
    }
    else
    {
        while ($stockData = $mysql->get_array($stockQuery))
        {
            $check = ($stockData['stock'] > 0) ? '' : ' disabled="disabled"';
            $outStockTxt = ($stockData['stock'] > 0) ? '' : ' - Out of stock';
            $stockPlusPrice = ($stockData['plus_price'] > 0) ? ' ('.$site->currency_symbol(($basePrice + $stockData['plus_price'])).')' : ' ('.$site->currency_symbol(($basePrice)).')';
            $stockOptions .= '<option value="'.$stockData['option'].'"'.$check.'>'.$stockData['option'].$outStockTxt.$stockPlusPrice.'</option>';
        }
        $details .= '<tr'.$hideIfVirtual.'><td>'.$product['stock_label'].':</td><td><select name="option" id="option" onchange="checkStock();">'.$stockOptions.'</select></td></tr>';
    }
}
//custom field
if ($product['custom_field'] == 'y')
{
    $details .= '<tr><td>'.stripslashes($product['custom_field_lbl']).':</td><td><input name="custom_field_val" type="text" id="custom_field_val" /></td></tr>';
}
//qty
if ($inStock == true)
{
    $details .= '<tr><td>Quantity:</td><td><input name="qty" type="text" id="qty" value="1" size="11" /><div id="leftInStock" style="float:right;padding-left:5px;"></div></td></tr><tr><td><input name="pid" type="hidden" id="pid" value="'.$pid.'" /></td><td><span><input type="submit" name="addtocartbtn" id="addtocartbtn" value="Add to cart" style="height:30px;" /></span></td></tr>
<tr><td colspan="2">';
//social buttons
    $social = $site->shop_settings('prdpage_socialBtns');
    if ($social['prdpage_socialBtns'] != 'n')
    {
        $details .= '<div class="addthis_default_style addthis_16x16_style"><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_11"></a><a class="addthis_button_preferred_6"></a><a class="addthis_button_compact"></a></div><script type="text/javascript" src="//s7.addthis.com/js/250/addthis_widget.js#username=xa-4d28e29f267ace89"></script>';
    }
    $details .= '</td></tr>';
}
else
{
    $details .= '<tr><td><h3 style="margin:0;">Out of stock</h3></td></tr><tr><td>';
    $details .= '</td></tr>';
}
$details .= '</table></form></td></tr></table><p><span>'.$product['description'].'</span></p>';
//also bought
$alsobought = $site->shop_settings('shop_show_alsobought');
if ($alsobought['shop_show_alsobought'] == 'y')
{
    $prods = [];
    $q = $mysql->query("owner", "fs_shop_cart", "pid = $pid AND temp = 'n' ORDER BY RAND() LIMIT 20");
    while ($d = $mysql->get_array($q))
    {
        $query = $mysql->query("pid", "fs_shop_cart", "owner = '{$d['owner']}' AND pid != $pid ORDER BY RAND() LIMIT 20");
        while ($data = $mysql->get_array($query))
        {
            $item = $site->productInfo($data['pid']);
            if ((int) $item['ID'] > 0 && $item['hide'] == 'n' && (int) $item['cat'] > 0)
            {
                $t = $data['pid'];
                if (!in_array($t, $prods))
                {
                    $prods[] = $data['pid'];
                }
            }
        }
    }
    if (sizeof($prods) > 0)
    {
        $x = 1;
        foreach ($prods as $key => $ids)
        {
            list($pid, $cat) = explode("|", $ids);
            $item = $site->productInfo($pid);
            $array['customerswhobroughthis'] .= '<a href="/'.$s['shop_page'].'/'.$seo_pageTitle.'/'.$item['url_key'].'" title="'.$item['name'].'"><img src="/inc/shop/images/clear.gif" border="0" alt="'.$item['name'].'" style="background-image:url(/inc/shop/images/'.$item['tiny_image'].');" /></a>';
            if ($x == 12)
            {
                break;
            }
            $x++;
        }
    }
    $details .= (!empty($array['customerswhobroughthis'])) ? '<div id="alsobought"><h2>Customers who bought this item also bought...</h2>'.$array['customerswhobroughthis'].'</div>' : '';
}
$mainhtml .= stripslashes($details);
//header facebook and shop css
$metaDesc = (empty($product['meta_desc'])) ? $product['description'] : $product['meta_desc'];
$head = '<meta property="og:title" content="'.$product['name'].'" />
<meta property="og:description" content="'.strip_tags($metaDesc).'" />
<meta property="og:image" content="'.httpOrHttps().'://'.$_SERVER['HTTP_HOST'].'/inc/shop/images/'.$product['mid_image'].'" />
<meta property="og:type" content="website" />
<meta property="og:url" content="'.httpOrHttps().'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'" />'.$jsonBC;
//load head code, only load if its not in the head already
if (!strstr($mainhtml, '/prototype/'))
{
    $head .= '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>';
}
if (!strstr($mainhtml, '/scriptaculous/'))
{
    $head .= '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js?load=effects,builder"></script>';
}
$mainhtml = str_replace("</head>", $head.'</head>', $mainhtml);
//include this add-ons's overwrite css file from the template being used, if there is one
$t = settings('template');
if (file_exists('templates/'.$t['template'].'/addons/shop.css'))
{
    $mainhtml = str_replace("</head>", '<link rel="stylesheet" type="text/css" href="/templates/'.$t['template'].'/addons/shop.css" /></head>', $mainhtml);
}
else
{
    $mainhtml = str_replace("</head>", '<link rel="stylesheet" type="text/css" href="//www.freesites.com.au/addons/shop.css" /></head>', $mainhtml);
}
//stock check js function
$js = '<script>function checkStock(){jQuery.post(window.location, {pid:jQuery("#pid").val(), option: jQuery("#option").val(), stockCheck:"y"}, function(data){jQuery("#leftInStock").html(data);});}jQuery(document).ready(function(){checkStock();});
jQuery(document).ready(function(){
var frm = jQuery("#addtocart");
frm.submit(function(e) {
jQuery("#addtocartMsg").hide();
jQuery.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: frm.serialize(),
success: function()
{
jQuery(\'#basketLineHeader\').load(\'/'.$s['shop_page'].'/'.$seo_pageTitle.'/Basket #basketLineHeader a\');
jQuery("#addtocartMsg").show();
}
});
e.preventDefault();
});
});
</script>';
$mainhtml = str_replace("</head>", $js.'</head>', $mainhtml);
//light box
$head = '<link rel="stylesheet" href="/inc/gallery/src/lightbox.css" type="text/css" />';
$head .= '<script type="text/javascript" src="/inc/gallery/src/lightbox.js"></script>';
$mainhtml = str_replace("</head>", $head.'</head>', $mainhtml);
//end
