<?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['e5Key']) {
    echo 'Unauthorized';
    exit;
}

if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('./include/entryPoint.php');

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;
    case 'getProducts':
        $products = [];
        $db = $GLOBALS['db'];
        $r = $db->query("SELECT id, name, code FROM ecmproducts WHERE active=1 AND deleted=0");
        while($row=$db->fetchByAssoc($r)) {
            $p = [];
            $p['name'] = $row['name'];
            $p['code'] = $row['code'];
            array_push($products, $p);
        }
        echo json_encode($products);
        break;
}