<?php
session_start();
/*
if(!isset($_SESSION['contador']))
{
	$_SESSION['contador'] = 0;
}

if($_SESSION['contador'] > 0)
{
	$_SESSION['contador'] = 0;
	header("Location: "."http://".$_SERVER['HTTP_HOST']."/inventario/main.php?main.php?module=saldo_inicial");
	exit;
}

$_SESSION['contador'] += 1;

  
*/




ob_start();

if($_GET['sel'] == ""){
   echo '<script>
                alert("No has seleccionado partidas");
                window.location = "http://'.$_SERVER['HTTP_HOST'].'/cdc/main.php?module=saldo_inicial";
    </script>';
}

$fecha = $_GET['fecha'];
$nombre = $_GET['nombre'];
$observacion_enc = $_GET['observacion_enc'];
$txtCorreo = $_GET['txtCorreo'];

if($txtCorreo == "" or $_GET['sel'] == "" ) {
    
     echo '<script>

                alert("No has seleccionado un correo para guardar y enviar la entrada de almacen");
                window.location = "http://'.$_SERVER['HTTP_HOST'].'/cdc/main.php?module=saldo_inicial";
    </script>';
    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";
include "../../../config/fungsi_tanggal.php";
include "../../../config/fungsi_rupiah.php";

function delete_files($folder_path){
        $files = glob($folder_path.'/*');

        foreach($files as $file)
        {
            if(is_file($file)) unlink($file);
        }
    }


$queryvalid = mysqli_query($mysqli, "SELECT count(*) as 'cuenta' FROM transaccion_medicamentos WHERE idenc is NULL and status = 'A'")
or die('Error '.mysqli_error($mysqli));
$rows  = mysqli_num_rows($queryvalid);
$data  = mysqli_fetch_assoc($queryvalid);
/*print_r($data);
die();*/
$cta_val = $data['cuenta'];

	if($cta_val == 0 ) {
    /*echo "No has seleccionado partidas para tu remision";*/
	 echo "<div class='alert alert-success alert-dismissable'>
             
                <h4>  <i class='icon fa fa-check-circle'></i> ERROR GARRAFAL!!!!!!</h4>
                No has seleccionado partidas para tu entrada.
              </div>";
	
    return;
} 

//SELECT codigo,numero,tipo_transaccion,observaciones FROM `transaccion_medicamentos` WHERE codigo = 'S000117'and observaciones = 'POR INVETNARIO INCIAL'

$created_user = $_SESSION['id_user'];
$name_user = $_SESSION['name_user'];

//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,txtCorreo) 
    VALUES('$folio','$fecha','$created_user','$name_user','A','$observacion_enc','$txtCorreo')")
    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'];

//Update idenc in table transaccion_medicamentos
for($x = 0; $x < count($arr); $x++) {
    $query = mysqli_query($mysqli, "
        UPDATE transaccion_medicamentos SET idenc = '$idenc' WHERE codigo_transaccion = '$arr[$x]'")
        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);  
$sta = $rw_encabezado['status'];  

       

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

$no = 1;




$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
    FROM transaccion_medicamentos as a
    INNER JOIN medicamentos as b ON a.codigo=b.codigo and a.tipo_transaccion='Entrada'
    INNER JOIN usuarios as c on a.created_user = c.id_user 
    WHERE a.codigo_transaccion in(" . $cond . ")
    ORDER BY codigo_transaccion DESC")
        or die('Error '.mysqli_error($mysqli));

$count  = mysqli_num_rows($query);



//Query parametros perfil
$queryperfil = mysqli_query($mysqli, "SELECT * FROM perfil")
                                or die('error'.mysqli_error($mysqli));
$rows  = mysqli_num_rows($queryperfil);
$data_perfil  = mysqli_fetch_assoc($queryperfil);
$folio_perfil = $data_perfil['folio'];
$nombre_perfil = $data_perfil['nombre_empresa'];
$direccion_perfil = $data_perfil['direccion'];
$email_perfil = $data_perfil['email'];
$almacen_perfil = $data_perfil['almacen'];
$almacenista_perfil = $data_perfil['almacenista'];




?>
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>ENTRADAS DE ALMACEN</title>
        <link rel="stylesheet" type="text/css" href="../../assets/css/laporan.css" />
       
    </head>
    <body>
        <div id="myHeader">
           <?php echo $data_perfil['nombre_empresa'];?>	   
        </div>
        
        <hr><br> 
 <?php
			echo "<img src='http://".$_SERVER['HTTP_HOST']."/cdc/images/logo.png' border='0' width='250' height='110' align=\"center\"><br>";
			 
			 ?>		
		
		  <div id="title"align="center" style ="font:bold">
           ENTRADA ALMACEN POR SALDO INICIAL AL ALMACEN DE <?php echo $data_perfil['almacen'];?> 
             <br>  
             <br>
             <br>

             <?php
            
               
               $dias = array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","Sábado");
               $meses = array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
               //echo $dias[date('w')]." ".date('d')." de ".$meses[date('n')-1]. " del ".date('Y') ;
             
              ?>

        <br>
        </div>
        <br>
        <br>
        <br>

        <div id="myHeader">
              


               <?php
               //echo  'Entrega:  ';
           

               $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;'>$folio_perfil-$rw_encabezado[folio]</div><br>";
			   echo "<br>"; 
			   echo  "<div align=\"right\" style='color:#ff0000; style='font-size:100%;font-weight:bold;'>$rw_encabezado[fecha]</div><br>";			   
			   echo  "INGRESA:  <br><div align=\"left\" style='color:#14A1F5;style='font-size:90%;font-weight:bold;'>$rw_usuario[name_user]</div>";
			   echo  "SE ENVIO A:<br>   <div align=\"left\" style='color:#14A1F5; style='font-size:90%;font-weight:bold;'> $rw_encabezado[txtCorreo] EL DIA  $rw_encabezado[fecha]</div>"; 			   
			   echo  "OBSERVACION GENERAL: <br> <div align=\"left\" style='color:#14A1F5; style='font-size:90%;font-weight:bold;'> $rw_encabezado[observacion_enc]</div>"; 
              ?>

        </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)) {
        #    $precio_compra = format_rupiah($data['precio_compra']);
         #   $precio_venta = format_rupiah($data['precio_venta']);
          
            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>";
if($sta == 'A'){    
   echo "<div align='center'>
   <img src='http://".$_SERVER['HTTP_HOST']."/cdc/images/entrada.png' border='0' width='450' height='310' align=\"center\">
   </div>";
}



             
?>








    </body>
</html>

<?php
$filename="Entrada_$folio_perfil-$idenc.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);
	$html2pdf->Output($filename);
	$html2pdf->Output('./mailer/src/pdf/'.$filename, 'F');
}
catch(HTML2PDF_exception $e) { echo $e; }
require 'mailer/src/enviar_entrada_inicial.php';

delete_files('./mailer/src/pdf')
?>