<?php
  session_start();
  ob_start();

  if($_GET['sel'] == ""){
      echo "<meta http-equiv='refresh' content='0; url=/main.php?module=medicines_consulta&alert=2'>";
      return;
  }
  
  $sel = $_GET['sel'];
  $sel = str_replace("chk_", "", $sel);
  $arr = explode("|",$sel);
  $cond = "";
  for($x = 0; $x < count($arr); $x++){
      $cond .= "'" . $arr[$x] . "',";
  }
  if($cond != "")
      $cond =substr($cond, 0, - 1);

  //echo $cond;
  //return;

  require_once "../../../config/database.php";
  
    
  $queryclose = mysqli_query($mysqli, "SELECT apertura FROM apertura_cierre where id = 1") 
or die('error: '.mysqli_error($mysqli));
$rows  = mysqli_num_rows($queryclose);
$data  = mysqli_fetch_assoc($queryclose);
$bandera = $data['apertura'];
/*print_r($bandera);
die();*/

if($bandera == 'CERRADO') {
	echo '<script>
                alert("EL ALMACEN SE ENCUENTRA CERRADO POR INVENTARIO DEL SUPERVISOR");
                window.location = "https://inventarios.casatequilaarandas.com/main.php?module=closed";
          </script>';     
    return;
}

  //Update Stock and Status of transaccion_medicamentos
  for($x = 0; $x < count($arr); $x++) {
    //Get number to return and code of product
    $query = mysqli_query($mysqli, "SELECT numero, codigo FROM transaccion_medicamentos WHERE codigo_transaccion = '$arr[$x]'")
                                or die('error'.mysqli_error($mysqli));
    $rows  = mysqli_num_rows($query);
    $data  = mysqli_fetch_assoc($query);
    $qty = $data['numero'];
    $cod = $data['codigo'];

    //Set new value of stock
    $query = mysqli_query($mysqli, "
        UPDATE medicamentos SET stock = stock + $qty WHERE codigo = '$cod'")
        or die('error: '.mysqli_error($mysqli));

    //Set cancel status
    $query = mysqli_query($mysqli, "
        UPDATE transaccion_medicamentos SET status = 'C' WHERE codigo_transaccion = '$arr[$x]'")
        or die('error: '.mysqli_error($mysqli));
  }

  echo "<meta http-equiv='refresh' content='0; url=/cdc/main.php?module=medicines_consulta&alert=3'>";
?>