<?php
/*
JOHNN GUTIERREZ,
FECHA DE CREACION   2021-01-27
ULTIMA MODIFICASION 2021-01-28
 */
include '../conn_obj/utiles_pdo.php';
include '../conn_obj/conn_param.php';
date_default_timezone_set("America/Panama");
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
#error_reporting(E_ALL);

session_start();
$_SESSION['db_name'] = $_POST['db_name'];
$_SESSION['cod_dep'] = $_POST['cod_dep'];
$_SESSION['cod_pro'] = $_POST['cod_pro'];

$cDb_Name = $_SESSION['db_name'];
$cCod_Dep = $_SESSION['cod_dep'];
$cCod_Pro = $_SESSION['cod_pro'];

$conn = new Utiles($cDb_Name, $Srv_Info['hostname'], $Srv_Info['username'], $Srv_Info['password']);

$cSql_Cmd = "SELECT ifnull(pr_man_exist,0) AS pr_man_exist FROM productos_det WHERE (pr_id='$cCod_Pro') AND  (suc_id=1)";
$conn->query($cSql_Cmd);
$oFndDat = $conn->fetchArray();
if ($oFndDat['pr_man_exist'] == 0) {
  $cSql_Cmd = "SELECT
      ex.pr_id,
      UPPER(TRIM(dp.dep_descripcion)) AS dep_descripcion,
      999999 AS Exist_Total,
      000000 AS Exist_Ped,
      000000 AS Exist_Apart,
      999999 AS Exist_Disp,
      dp.dep_id
    FROM  $cDb_Name.prod_existencia ex
    LEFT OUTER JOIN $cDb_Name.depositos dp ON ex.p_existencia_dep_id=dp.dep_id
    WHERE (dp.para_la_venta=1) AND (ex.pr_id = '$cCod_Pro')
    AND   IF( (('$cCod_Dep'='%') OR ('$cCod_Dep'='*')),1=1,dp.dep_id='$cCod_Dep')
    ORDER BY ex.p_existencia_dep_id,ex.pr_id ";

  $conn->query($cSql_Cmd);
  $oData = $conn->fetchAll();
} else {
  $cSql_Cmd = 'SELECT
              ex.pr_id,
              UPPER(TRIM(dp.dep_descripcion)) AS dep_descripcion,
              ex.p_existencia AS Exist_Total,
              ex.p_pventas    AS Exist_Ped,
              ex.p_apartado   AS Exist_Apart,
              ex.p_existencia - (ex.p_pventas+ex.p_apartado) AS Exist_Disp,
              dp.dep_id
            FROM  ' . $cDb_Name . '.prod_existencia ex
            LEFT OUTER JOIN ' . $cDb_Name . '.depositos dp ON ex.p_existencia_dep_id=dp.dep_id
            WHERE (dp.para_la_venta=1) AND (ex.pr_id = "' . $cCod_Pro . '")
            AND   IF( (("' . $cCod_Dep . '"="%") OR ("' . $cCod_Dep . '"="*")),1=1,dp.dep_id="' . $cCod_Dep . '")
            ORDER BY ex.p_existencia_dep_id,ex.pr_id ';

  $conn->query($cSql_Cmd);
  $oData = $conn->fetchAll();
}
header('content-type: application/json');
echo json_encode($oData);
@mysqli_close($conn);
