<?php
require_once 'ApiGlobalFunctions.php';

$usuario=$_POST['uid'];
$password=$_POST['key'];
$url=$_POST['url'];
$caja=$_POST['cajaid'];
$productcode=$_POST['ProductCode'];
$cantidad=$_POST['qty'];

$include=includec($url);
include $include;

$validate=loginkey($usuario,$password,$url);
if($validate==1){
    if($cantidad>0){
       mysqli_set_charset($link, "utf8");
        $campo=diccionario($url,'codproduct');        
        $query=mysqli_query($link, "SELECT vtiger_products.productid 
        FROM vtiger_products 
        INNER JOIN vtiger_productcf ON vtiger_productcf.productid=vtiger_products.productid 
        INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid 
        WHERE deleted='0' AND ".$campo."='$productcode'");
        $data=mysqli_fetch_array($query);    
        $productid=$data['productid'];
        if($productid>0){        
            $query=mysqli_query($link,"SELECT *FROM caja_productos WHERE productid='$productid' AND cajaid='$caja'");
            $num=mysqli_num_rows($query);            
            if($num>0){
                $data=mysqli_fetch_array($query);
                $qty=$data['cantidad'];
                $cantidad=$cantidad+$qty;
                mysqli_query($link,"UPDATE caja_productos SET cantidad='$cantidad' WHERE cajaid='$caja' AND productid='$productid'");
                $docs[0]=array('Result'=>'1', 'id'=>"Creado");
            }else{
                mysqli_query($link,"INSERT INTO caja_productos VALUES ('$caja','$productid','$cantidad','0','0','0','0')");
                mysqli_query($link,"UPDATE vtiger_paquetes SET paquetes_tks_estado='Nueva' WHERE paquetesid='$caja'");
                $docs[0]=array('Result'=>'1', 'id'=>"Creado");

            }
        }else{
            $docs[0]=array('Result'=>'2', 'id'=>"Error Product");
        }
    }else{
            $docs[0]=array('Result'=>'0', 'id'=>"Error Qty");
    }
    echo json_encode(setDataJSON($docs,1));
}