<?php
session_start();
ob_start();
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);
        }
    }

$fecha = $_GET['fecha'];
$nombre = $_GET['nombre'];
$observacion_enc = $_GET['observacion_enc'];
$txtCorreo = $_GET['txtCorreo'];
$txtMotivo = $_GET['txtMotivo'];
if($txtCorreo == '') {
    
     echo '<script>
                alert("No has seleccionado un correo para enviar la remision");
                window.location = "https://inventarios.casatequilaarandas.com/main.php?module=remision";
    </script>';
    return;
}

/*if($observacion_enc == '') {
    
     echo '<script>
                alert("No has seleccionado hecho ningun comentario en la observacion");
                window.location = "http://localhost/inventario/main.php?module=remision";
    </script>';
    return;
}*/

$query = mysqli_query($mysqli, "SELECT count(1) as cant FROM remision_detalle WHERE status = 'A' and idenc IS NULL")
                                or die('error'.mysqli_error($mysqli));
$rows  = mysqli_num_rows($query);
$data  = mysqli_fetch_assoc($query);
$cant = $data['cant'];

if($cant == 0) {
    echo '<script>
                alert("No has seleccionado partidas");
                window.location = "https://inventarios.casatequilaarandas.com/main.php?module=remision";
    </script>';
    return;
}
$created_user = $_SESSION['id_user'];

//Get Max Folio + 1
$query = mysqli_query($mysqli, "SELECT IFNULL(MAX(folio),0) + 1 as folio FROM remision_encabezado")
                                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 remision_encabezado(folio,fecha,created_user,nombre,status,observacion_enc,txtCorreo,txtCancel,txtMotivo) 
    VALUES('$folio','$fecha','$created_user','$nombre','A','$observacion_enc','$txtCorreo','','$txtMotivo')    ")
    or die('error '.mysqli_error($mysqli));

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

//Update idenc in table remision_detalle
$query = mysqli_query($mysqli, "UPDATE remision_detalle SET idenc = '$idenc' WHERE status = 'A' and idenc IS NULL")
        or die('error: '.mysqli_error($mysqli));

//Query Encabezado
$queryEnc = mysqli_query($mysqli, "
    SELECT e.*
    FROM remision_encabezado 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 detalle
$querydet = mysqli_query($mysqli, "
    SELECT c.name_user, b.*
    FROM remision_detalle 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.id, a.fecha, a.codigo, a.cantidad, b.codigo, b.nombre, b.unidad, a.observaciones, a.created_user, c.username
    FROM remision_detalle as a
    INNER JOIN medicamentos as b ON a.codigo = b.codigo and a.tipo_transaccion='Remision'
    INNER JOIN usuarios as c on a.created_user = c.id_user
    WHERE a.idenc = '$idenc'
    ORDER BY id")
        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'];
$folio_rem_perfil = $data_perfil['folio2'];
$nombre_perfil = $data_perfil['nombre_empresa'];
$direccion_perfil = $data_perfil['direccion'];
$direccion_perfil = $data_perfil['direccion'];
$email_perfil = $data_perfil['email'];
$almacen_perfil = $data_perfil['almacen'];
$almacenista_perfil = $data_perfil['almacenista'];

//insertar nombre de quien recibe
$queryrecibe = mysqli_query($mysqli, "
SELECT b.nombre FROM remision_encabezado as a,correos as b WHERE a.txtCorreo = b.tipo and a.id = $idenc ")
or die('Error '.mysqli_error($mysqli));
$rows  = mysqli_num_rows($queryrecibe);
$data  = mysqli_fetch_assoc($queryrecibe);
/*print_r($data);
die();*/
$recibe = $data['nombre'];
  

?>
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>REMISION</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']."/images/logo.png' border='0' width='250' height='110' align=\"center\"><br>";		*/	 
	     ?>
		  <div id="title" align="center" style ="font:bold" >
		  REMISION
        </div>
        <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_rem_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  "SOLICITO:  <br><div align=\"left\" style='color:#14A1F5;style='font-size:90%;font-weight:bold;'>   $rw_detalle[name_user]</div>";
			   echo  "MOTIVO DE SALIDA: <br> <div align=\"left\" style='color:#14A1F5; style='font-size:100%;font-weight:bold;'> $rw_encabezado[txtMotivo]</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>PARTIDA</small></th>
					<th height="20" align="center" valign="middle" bgcolor="#005a6f" style="color: #ffffff;"><small>CANTIDAD</small></th>
                    <th height="20" align="center" valign="middle" bgcolor="#005a6f" style="color: #ffffff;"><small>ARTICULO</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>TRANS</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 style='padding-right:10px;' width='100' height='13' align='center' valign='middle'style='font-size:80%;'>$data[cantidad]</td>
						  <td style='padding-left:5px;' width='300' height='13' valign='middle'style='font-size:80%;'>$data[nombre]</td>
						  <td width='150' height='13' align='center' valign='middle'style='font-size:80%;'>$data[codigo]</td>
                        <td width='100' height='13' align='center' valign='middle'style='font-size:80%;'>PR-$data[id]</td> 
                    </tr>";
            $no++;
        }
        ?>  
                </tbody>
            </table>

            
        </div>
		
		
<?php
if($sta == 'A'){  /*  
   echo "<div align='center'>
   <img src='http://".$_SERVER['HTTP_HOST']."/images/espera.png' border='0' width='150' height='150' align=\"center\">
   </div>";*/
}


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\">$recibe</div><br>"; 


             
?>








    </body>
</html>

<?php
$filename="$folio_rem_perfil-$idenc.pdf"; 
//$filename="REM.pdf"; 

/*require 'mailer/src/enviar_remision.php';*/

//==========================================================================================================
$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_remision.php';

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

?>

