<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Content-Type: application/json');

chdir(dirname(__DIR__));

require_once('./REST/config.php');
if ($_GET['key'] != $restConfig['twinpolKey']) {
    echo 'Unauthorized';
    exit;
}

if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('./include/entryPoint.php');
// fix db, but why? 
$GLOBALS['db']->query("USE preDb_0dcc87940d3655fa574b253df04ca1c3;");

switch ($_GET["action"]) {
    case 'getProductByEAN':
        $db = $GLOBALS['db'];
        $ean = $_GET['ean'];
        $res = $db->fetchByAssoc($db->query("SELECT id, name, code FROM ecmproducts WHERE (ean='$ean' OR ean2='$ean') AND deleted=0"));
        if ($res) {
            $r = $db->fetchByAssoc($db->query("SELECT SUM(quantity) as qty FROM ecmstockstates WHERE product_id='".$res['id']."'"));
            $res['state'] = $r['qty'] | 0;

            $r= $db->query("SELECT stock_address FROM ecmproducts_stock_addresses WHERE ecmproduct_id='".$res['id']."';");
            $res['stock_addresses'] = "";
            while($row=$db->fetchByAssoc($r)) {
            	$res['stock_addresses'] .= " ".$row['stock_address'];
            }
        }
        echo json_encode($res);
        break;
}