<?php
session_start();
ob_start();

if (!isset($_GET['id'])) {
    echo "Favor de seleccionar una remision";
    return;
}
$idRem = $_GET['id'];

require_once "../../../config/database.php";
include "../../../config/fungsi_tanggal.php";
include "../../../config/fungsi_rupiah.php";

$created_user = $_SESSION['id_user'];

//Query Details of Remision
$queryDet = mysqli_query($mysqli, "
    SELECT r.*, u.name_user 
    FROM remision_detalle as r
        left join usuarios as u on u.id_user = r.created_user
    WHERE idenc = '$idRem' ")
        or die('Error '.mysqli_error($mysqli));
$banDet = 0;
while ($data = mysqli_fetch_assoc($queryDet)) {
  $queryProd = mysqli_query($mysqli, "
        SELECT codigo, nombre, unidad, stock 
        FROM medicamentos 
        WHERE codigo = '$data[codigo]' ")
            or die('error '.mysqli_error($mysqli));
  $prd = mysqli_fetch_assoc($queryProd);
  
  //Validate Stock of Product
  if($prd['stock'] < $data['cantidad']) {    
    echo "Existencia insuficiente para el producto $data[codigo] - $prd[nombre] <br> 
          Stock: $prd[stock], Cantidad Remision: $data[cantidad]";
    $banDet = 1;
  }
}

if($banDet == 1)
  return;

//Get Max Folio + 1
$query = mysqli_query($mysqli, "SELECT IFNULL(MAX(folio),0) + 1 as folio FROM transaccion_medicamentos_enc")
                                or die('error'.mysqli_error($mysqli));
$rows  = mysqli_num_rows($query);
$data  = mysqli_fetch_assoc($query);
$folio = $data['folio'];

//Insert in table transaccion_medicamentos_enc
$query = mysqli_query($mysqli, "
    INSERT INTO transaccion_medicamentos_enc(folio, fecha, created_user, nombre, status, observacion_enc) 
    SELECT '$folio', fecha, created_user, nombre, 'A', observacion_enc 
    FROM remision_encabezado 
    WHERE id = '$idRem' ")
    or die('error '.mysqli_error($mysqli));

//Get Last Insert Id
$query = mysqli_query($mysqli, "SELECT MAX(id) as idenc FROM transaccion_medicamentos_enc")
                                or die('error'.mysqli_error($mysqli));
$rows  = mysqli_num_rows($query);
$data  = mysqli_fetch_assoc($query);
$idenc = $data['idenc'];

//Get Last Detail Id
$query_id = mysqli_query($mysqli, "
    SELECT RIGHT(codigo_transaccion,6) as codigo 
    FROM transaccion_medicamentos
    ORDER BY codigo_transaccion DESC LIMIT 1")
        or die('Error : '.mysqli_error($mysqli));
$data_id = mysqli_fetch_assoc($query_id);      
$codigo = $data_id['codigo'] + 1;
$tahun  = date("Y");

//Query Details of Remision
$queryDet = mysqli_query($mysqli, "
    SELECT r.*, u.name_user 
    FROM remision_detalle as r
        left join usuarios as u on u.id_user = r.created_user
    WHERE idenc = '$idRem' ")
        or die('Error '.mysqli_error($mysqli));
//Insert rows in table transaccion_medicamentos
while ($data = mysqli_fetch_assoc($queryDet)) {
    $buat_id = str_pad($codigo, 6, "0", STR_PAD_LEFT);
    $codigo_transaccion = "TR-$tahun-$buat_id";

    $queryPrd = mysqli_query($mysqli, "
        INSERT INTO transaccion_medicamentos(codigo_transaccion, fecha, codigo, numero, created_user, tipo_transaccion, observaciones, nombre_entrega, status, idenc) 
        VALUES('$codigo_transaccion', '$data[fecha]', '$data[codigo]', '$data[cantidad]', '$data[created_user]', 'Salida', '$data[observaciones]', '$data[name_user]', 'A', '$idenc' )")
        or die('Error: '.mysqli_error($mysqli));  
    if ($queryPrd) {            
        $queryExi = mysqli_query($mysqli, "
            UPDATE medicamentos SET stock = stock - '$data[cantidad]'
            WHERE codigo   = '$data[codigo]' ")
                or die('Error: '.mysqli_error($mysqli));
    }

    $codigo = $codigo + 1;
}


//Update idenc in table remision_encabezado
$query = mysqli_query($mysqli, "
    UPDATE remision_encabezado SET idSalida = '$idenc', status = 'S' WHERE id = '$idRem' ")
    or die('error: '.mysqli_error($mysqli));


//Query Encabezado
$queryEnc = mysqli_query($mysqli, "
    SELECT e.*
    FROM transaccion_medicamentos_enc as e
    WHERE e.id = '$idenc'")
        or die('Error '.mysqli_error($mysqli));
$rw_encabezado=mysqli_fetch_array($queryEnc);        

$hari_ini = date("d-m-Y");
$no = 1;

//Query detalle
$querydet = mysqli_query($mysqli, "
    SELECT c.name_user, b.*
    FROM transaccion_medicamentos as b , usuarios as c
    where b.created_user = c.id_user
    and b.idenc = '$idenc'")
        or die('Error '.mysqli_error($mysqli));
$rw_detalle=mysqli_fetch_array($querydet);


$query = mysqli_query($mysqli, "
    SELECT a.tipo_transaccion, a.codigo_transaccion, a.fecha, a.codigo, a.numero, b.codigo, b.nombre, b.unidad, a.observaciones, a.created_user, c.username, a.nombre_entrega
    FROM transaccion_medicamentos as a
      INNER JOIN medicamentos as b ON a.codigo=b.codigo and a.tipo_transaccion='Salida'
      INNER JOIN usuarios as c on a.created_user = c.id_user 
    WHERE a.idenc = '$idenc'
    ORDER BY codigo_transaccion")
        or die('Error '.mysqli_error($mysqli));
?>
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>SALIDAS DE ALMACEN</title>
        <link rel="stylesheet" type="text/css" href="../../../assets/css/laporan.css" />       
    </head>
    <body>
       <div id="myHeader">
           Tequila San Matias de Jalisco,   
        </div>        
        <hr><br>    
		 <?php
			 echo "<img src='http://".$_SERVER['HTTP_HOST']."/images/logo.png' border='0' width='250' height='110' align=\"center\"><br>";			 
			 ?>
			 <br>
		  <div id="title" align="center" style ="font:bold" >
		  SALIDA ALMACEN  <br>
      ( AUTOMATICA )
          <br>
        <br>
        </div>
        <br>
        <br>
        <br>
        <div id="myHeader">
        <?php
           $sql_usuario=mysqli_query($mysqli,"select * from usuarios WHERE id_user='$_SESSION[id_user]' ");
           $rw_usuario=mysqli_fetch_array($sql_usuario);
               			   
			   echo  "<div align=\"right\" style='color:#ff0000;font-size:100%;font-weight:bold;'>$rw_encabezado[serie]$rw_encabezado[folio]</div><br>";
			   echo  "<div align=\"right\" style='font-size:100%;font-weight:bold;'>$rw_encabezado[fecha]</div><br>";  
			   echo  "<div align=\"left\" style='font-size:90%;font-weight:bold;'>AUTORIZA: $rw_detalle[name_user]</div><br>";
			   echo  "<div align=\"left\" style='font-size:90%;font-weight:bold;'>OBSERVACION GENERAL: $rw_encabezado[observacion_enc]</div>";
         echo "<br>";
        ?>
        </div>

        <div id="myHeader">		
            <table width="100%" border="0.3" cellpadding="0" cellspacing="0">
                <thead style="background:#e8ecee">
                    <tr class="tr-title">
					<th height="15" align="center" valign="middle" bgcolor="#005a6f" style="color: #ffffff;"><small>#</small></th>
                        <th height="20" align="center" valign="middle" bgcolor="#005a6f" style="color: #ffffff;"><small>TRANS</small></th>
                        <th height="20" align="center" valign="middle" bgcolor="#005a6f" style="color: #ffffff;"><small>CODIGO</small></th>
                        <th height="20" align="center" valign="middle" bgcolor="#005a6f" style="color: #ffffff;"><small>PRODUCTOS</small></th>
                        <th height="20" align="center" valign="middle" bgcolor="#005a6f" style="color: #ffffff;"><small>CANT</small></th>         
                        <th height="20" align="center" valign="middle"bgcolor="#005a6f" style="color: #ffffff;"><small>DETALLE</small></th>
                    </tr>
                </thead>
                <tbody>
              <br>  
             <br>
             <br>
        <?php
        while ($data = mysqli_fetch_assoc($query)) {
            echo "  <tr>
                         <td width='15' height='13' align='center' valign='middle' style='font-size:80%;'>$no</td>
                        <td width='100' height='13' align='center' valign='middle'style='font-size:80%;'>$data[codigo_transaccion]</td>                        
                        <td width='60' height='13' align='center' valign='middle'style='font-size:80%;'>$data[codigo]</td>
                        <td style='padding-left:5px;' width='180' height='13' valign='middle'style='font-size:80%;'>$data[nombre]</td>
                        <td style='padding-right:10px;' width='30' height='13' align='center' valign='middle'style='font-size:80%;'>$data[numero]</td>
                                 
						<td width='280' height='13' align='center' valign='middle'style='font-size:80%;'>$data[observaciones]</td>
                    </tr>";
            $no++;
        }
        ?>  
                </tbody>
            </table>            
        </div>
		
		
<?php

echo "<br>";    
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
echo  "<div align=\"center\">_________________________</div><br>"; 
echo "<br>";
echo  "<div align=\"center\">Recibe</div><br>";
/*echo  "<div align=\"center\">$rw_detalle[nombre_entrega]</div><br>"; */
?>
    </body>
</html>

<?php
$filename="SALIDAS DE ALMACEN.pdf"; 

//==========================================================================================================
$content = ob_get_clean();
$content = '<page style="font-family: freeserif">'.($content).'</page>';

require_once('../../../assets/plugins/html2pdf_v4.03/html2pdf.class.php');
try
{
    $html2pdf = new HTML2PDF('P','F4','en', false, 'ISO-8859-15',array(10, 10, 10, 10));
    $html2pdf->setDefaultFont('Arial');
    $html2pdf->writeHTML($content, isset($_GET['vuehtml']));
    $html2pdf->Output($filename);
}
catch(HTML2PDF_exception $e) { echo $e; }
?>