<?php declare(strict_types=1);
namespace IdeaBooks\Storefront\Subscriber;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\Struct\ArrayEntity;
use \Mysqli;
use GeoIp2\WebService\Client as GeoIp2Client;
class ProductSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'addBuyFrom'
];
}
private function OpenCon()
{
//DATABASE_URL="mysql://ideabooks.nl:i9cIbFBadWuxdwgb@localhost:3306/ideabooks_albertvanderveen_nl"
$databaseUrl = getenv('DATABASE_URL');
$databaseUrlParts = explode(':', $databaseUrl);
$dbuser = trim($databaseUrlParts[1],'/');
$dbpass = explode('@', $databaseUrlParts[2])[0];
$dbhost = explode('@', $databaseUrlParts[2])[1];
$db = explode('/', $databaseUrlParts[3])[1];
/*
$dbhost = "localhost";
$dbuser = "app";
$dbpass = "SAg8XKmloD8cjS2dCvneYFMnH70onxgr";
$db = "ideanew2";
*/
$mysqli = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $mysqli;
}
private function CloseCon($mysqli)
{
$mysqli -> close();
}
public function addBuyFrom(ProductPageLoadedEvent $event): void
{
/*
$request = $event->getRequest();
$contextToken = $request->headers->get(PlatformRequest::HEADER_CONTEXT_TOKEN);
if ($contextToken) {
$persistedParams = $this->contextPersister->load($contextToken);
$persistedCountryId = $persistedParams[SalesChannelContextService::COUNTRY_ID] ?? null;
dump($persistedCountryId);
}
*/
//$country = $event->getPage()->getHeader()->activeShippingLocation->getCountry();
//dump($country);
//$isocode2 = $country->get('iso');
//$isocode2 = $_SERVER['GEOIP_CITY_COUNTRY_CODE'];
$mysqli = $this->OpenCon();
$ip = $_SERVER['REMOTE_ADDR'];
$query = "SELECT isocode2 FROM idea_ip WHERE ip = '".$ip."'";
if ($result = $mysqli->query($query)) {
if ($result->num_rows == 1){
$row = mysqli_fetch_assoc($result);
$isocode2 = $row['isocode2'];
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'isocode2 uit lokale tabel gehaald'.PHP_EOL, FILE_APPEND);
}
else {
$client = new GeoIp2Client(448110, 'HnTnKEMimEMUwKN3');
$record = $client->country($ip);
$isocode2 = $record->country->isoCode;
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'isocode2 via GeoIp2Client'.PHP_EOL, FILE_APPEND);
$query = "INSERT INTO idea_ip VALUES('" . $ip . "','" . $isocode2 . "')";
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'insert query ip/isocode2: '.$query.PHP_EOL, FILE_APPEND);
if ($result = $mysqli->query($query)) {
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'ip/isocode2 toegevoegd aan lokale tabel'.PHP_EOL, FILE_APPEND);
}
}
}
else $isocode2 = 'NL';//default als er iets misgaat
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'ip: '.$_SERVER['REMOTE_ADDR'].PHP_EOL, FILE_APPEND);
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'isocode2: '.$isocode2.PHP_EOL, FILE_APPEND);
$product = $event->getPage()->getProduct();
$titelnummer = trim($product->get('productNumber'), 'idea');//strip 'idea'
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'titelnummer: idea'.$titelnummer.PHP_EOL, FILE_APPEND);
$isSaleable = $product->get('stock') > 0 && $product->get('available');
$addtocartUrl = '';
//dump($titelnummer);
//dump($isSaleable);
//idearegio ophalen
$idearegio = null;
$query = "SELECT idearegio FROM idea_land WHERE isocode2 = '".$isocode2."'";
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'query idearegio: '.$query.PHP_EOL, FILE_APPEND);
if ($result = $mysqli->query($query)) {
//printf("Select returned %d rows.\n", $result->num_rows);
$row = mysqli_fetch_all($result, MYSQLI_ASSOC);
$idearegio = $row[0]['idearegio'];
}
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'idearegio: '.$idearegio.PHP_EOL, FILE_APPEND);
//dump($idearegio);
//eerst in het land zelf zoeken:
//$titelboekhandelurl_collection_land = Mage::getModel('ideabooks/titelboekhandelurl')->getCollection()
//->addFieldToFilter('titelnummer', $titelnummer)->addFieldToFilter('isocode2', $isocode2);
$boekhandels = array();
$query = "SELECT url, naam, isocode3 FROM idea_titelboekhandelurl WHERE titelnummer = '".$titelnummer."' AND isocode2 = '".$isocode2."' LIMIT 30";
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'query idea_titelboekhandelurl: '.$query.PHP_EOL, FILE_APPEND);
if ($result = $mysqli->query($query)) {
//printf("Select returned %d rows.\n", $result->num_rows);
//dump($result->num_rows);
$boekhandels = mysqli_fetch_all($result, MYSQLI_ASSOC);
//file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'boekhandels:'.print_r($boekhandels, true).PHP_EOL, FILE_APPEND);
}
//vervolgens in idearegio, maar met uitzondering van het land zelf (dat is immers al verwerkt)
/*
$titelboekhandelurl_collection_regio = Mage::getModel('ideabooks/titelboekhandelurl')->getCollection()
->addFieldToFilter('titelnummer', $titelnummer)
->addFieldToFilter('idearegio', $idearegio)
->addFieldToFilter('isocode2', array('neq' => $isocode2));
*/
if ($idearegio){
$query = "SELECT url, naam, isocode3 FROM idea_titelboekhandelurl WHERE titelnummer = '".$titelnummer."' AND isocode2 != '".$isocode2."' AND idearegio='".$idearegio."'";
if ($result = $mysqli->query($query)) {
//printf("Select returned %d rows.\n", $result->num_rows);
//$boekhandels = mysqli_fetch_all($result, MYSQLI_ASSOC);
//dump($result->num_rows);
$boekhandels = array_merge($boekhandels, mysqli_fetch_all($result, MYSQLI_ASSOC));
//file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'boekhandels na merge:'.print_r($boekhandels, true).PHP_EOL, FILE_APPEND);
}
}
file_put_contents(getenv('APP_DIR') . '/var/log/ProductSubscriber.log', PHP_EOL.date("Y-m-d H:i:s").chr(9).'boekhandels: '.print_r($boekhandels, true).PHP_EOL, FILE_APPEND);
$this->CloseCon($mysqli);
//dump($boekhandels);
$saleOptionAvailable = false;
$buyFrom = '';
//limiet nu anders oplossen: break uit foreach na 10 loops
$count = 0;
foreach ($boekhandels as $boekhandel) {
$saleOptionAvailable = true;
$boekhandelUrl = $boekhandel['url'];
if (stristr($boekhandelUrl, 'http') === false) $boekhandelUrl = 'http://'.$boekhandelUrl;
$buyFrom .= '<a href="'.$boekhandelUrl.'" onClick="ga(\'send\', \'event\', {
\'eventCategory\': \'Boekhandel links\',
\'eventAction\': \'click\',
\'eventLabel\': \''.$boekhandelUrl.'\',
\'hitCallback\': function() {
//alert(\'hit sent\');
//window.open(\''.$boekhandelUrl.'\',\'_blank\')
window.location.href = \''.$boekhandelUrl.'\'
}
}); return false;">'.ucwords(strtolower($boekhandel['naam'])).'</a> ('.$boekhandel['isocode3'].')<br />';
$count++;
if ($count == 30) break;
}
//direct via Ideabooks - niet toevoegen, in template
/*if ($isSaleable){
$saleOptionAvailable = true;
$buyFrom .= '<a href="'.$addtocartUrl.'">Idea Books Direct</a>';
}*/
//if (!$saleOptionAvailable) $buyFrom .= '';
//$buyFrom = '<h3>Buy this title from:</h3>'.$buyFrom;
//dump($buyFrom);
/* debug van $event->getPage() geeft o.a. deze key:
#extensions: array:1 [▼
"product_buyfrom" => Shopware\Core\Framework\Struct\ArrayEntity {#264113 ▼
#data: array:1 [▼
0 => "test.html"
]
de array data daarin is direct te benaderen, dus bijv via page.extensions.product_buyfrom.0: geeft string(9) "test.html"
*/
$buyFromStruct = new ArrayEntity();
$buyFromStruct->set(0,$buyFrom);
$event->getPage()->addExtension('product_buyfrom', $buyFromStruct);
//dump($event);
}
}