<?php
//============================================================+
// File name   : example_005.php
// Begin       : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 005 for TCPDF class
//               Multicell
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

/**
 * Creates an example PDF TEST document using TCPDF
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: Multicell
 * @author Nicola Asuni
 * @since 2008-03-04
 */

//  $conn_string = "host=172.16.0.22 port=3306 dbname=citas user=siverc password=InhRR*2023";
            
//  // establecemos una conexion con el servidor postgresSQL
//  $VUS = pg_connect($conn_string);
 
//  // Revisamos el estado de la conexion en caso de errores. 
//  if(!$VUS) {
//      echo "Error: No se ha podido conectar a la base de datos de CITAS";
//  } else {
//      echo "AVISO: Se conecto correctamente a la base de datos de CITAS";
//      $var_consulta="SELECT * FROM tblPTR_valor_diario";    
//      $qTMP = pg_query($VUS, $var_consulta);                    
//  }

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

$IntNumReg = $_GET["nr"];
$IntNumSol = $_GET["ns"];
$InttipoNumReg = $_GET["nr"];
$tipo = $_GET["nt"];
$tipoc = $_GET["ntc"];

// // detalles de la conexion
// $conn_stringADM = "host=localhost port=5432 dbname=sivercA user=postgresuser password=p05tgr35u53r";
 
// // establecemos una conexion con el servidor postgresSQL
// $ADM = pg_connect($conn_stringADM);
 
// // Revisamos el estado de la conexion en caso de errores. 

// if(!$ADM) {
//     echo "Connection to ADM Database error\n";
// } 

// detalles de la conexion
$conn_stringADM = "host=172.16.0.21 port=5432 dbname=sivercA user=postgresuser password=p05tgr35u53r";
 
// establecemos una conexion con el servidor postgresSQL
$ADM = pg_connect($conn_stringADM);
 
// Revisamos el estado de la conexion en caso de errores. 

if(!$ADM) {
    echo "Connection to ADM Database error\n";
} 

$number='90922';

$sql="SELECT * FROM ctg_productos_{$tipo} WHERE adm_{$tipo}_numreg = '{$IntNumReg}' LIMIT 1 ";
$qTMP = pg_query($ADM, $sql);
    while ($rTMP = pg_fetch_assoc($qTMP)) {    
                ////// MAIN DATA
                $numsol=$rTMP["adm_pb_numsol"];
                $nomprod=$rTMP["adm_pb_nomprod"];
                $regnum=$rTMP["adm_pb_numreg"];
                $formid=$rTMP["adm_pb_forma"];
                $formDesc=$rTMP["adm_pb_forma"];
                $package=$rTMP["adm_pb_presenta"];
                $autori=$rTMP["adm_pb_autori"];
                $vencim=$rTMP["adm_pb_vencim"];
                $admin=$rTMP["adm_pb_admin"];
                $admin_oth=$rTMP["adm_pb_admin_oth"];
                $admin_val1=$rTMP["adm_pb_admin_val1"];
                $admin_val2=$rTMP["adm_pb_admin_val2"];
                $envaid=$rTMP["adm_pb_env_id"];
                $envaDesc=$rTMP["adm_pb_env_id"];
                $admusuario=$rTMP["adm_pb_usr"];
                $farma_ci=trim($rTMP["adm_pb_farm_ci"]);

                $date1=substr($autori,8,2)."/".substr($autori,5,2)."/".substr($autori,0,4);
                $date2=substr($vencim,8,2)."/".substr($vencim,5,2)."/".substr($vencim,0,4);
                $fecha=Date("d-m-Y");
                switch ( substr($fecha,3,2)) {
                    case '01':
                        $issdate="Enero ";
                        break;
                    case '02':
                        $issdate="Febrero ";
                        break;
                    case '03':
                        $issdate="Marzo ";
                        break;
                    case '04':
                        $issdate="Abril ";
                        break;
                    case '05':
                        $issdate="Mayo ";
                        break;
                    case '06':
                        $issdate="Junio ";
                        break;
                    case '07':
                        $issdate="Julio ";
                        break;
                    case '08':
                        $issdate="Agosto ";
                        break;
                    case '09':
                        $issdate="Septiembre ";
                        break;
                    case '10':
                        $issdate="Octubre ";
                        break;
                    case '11':
                        $issdate="Noviembre ";
                        break;
                    case '12':
                        $issdate="Diciembre ";
                        break;
                }                
                $fecha =substr($fecha,0,2)." de ".$issdate." de ".substr($fecha,6,4);

                $representante="- - - - - - - ";
                $propietario="- - - - - - - ";
                $almacenador="- - - - - - - ";
                $distribuidor="- - - - - - -";
                $farmaceutico="- - - - - - - ";
                $desc = "";

                $sql1="SELECT * FROM ctg_formas WHERE ctg_for_id = '{$formid}' LIMIT 1 ";
                $qTMP1 = pg_query($ADM, $sql1);
                while ($rTMP1 = pg_fetch_assoc($qTMP1)) {    
                    $formDesc=$rTMP1["ctg_for_desc"];
                }

                $sql0="SELECT * FROM ctg_envases WHERE ctg_env_id = '{$envaid}' LIMIT 1 ";
                $qTMP0 = pg_query($ADM, $sql0);
                while ($rTMP0 = pg_fetch_assoc($qTMP0)) {    
                    $envaDesc=$rTMP0["ctg_env_desc"];
                }

                //// ACTIVE INGREDIENTS 
                $sql2="SELECT * FROM ctg_productos_pb_formula WHERE \"adm_pbFOR_numreg\" = '{$IntNumReg}' AND \"adm_pbFOR_tipo\"='1' ";
                $qTMP2 = pg_query($ADM, $sql2);
                while ($rTMP2 = pg_fetch_assoc($qTMP2)) {

                    if (!empty($formula))
                            $formula .= ", ";
                    $txt="";
                    $valor = $rTMP2["adm_pbFOR_can"];
                    $valor = floatval($valor);
                    $txt .= $rTMP2["adm_pbFOR_sus_nom"]." ".$rTMP2["adm_pbFOR_cominfo"]." ".$valor;
                    $unimed=$rTMP2["adm_pbFOR_ume_id"];
                    switch ($unimed) {
                        case '1':
                            $txt .= 'mg'; break;
                        case '2':
                            $txt .= 'mcg'; break;
                        case '3':
                            $txt .= 'IU'; break;
                        case '4':
                            $txt .= $rTMP2["adm_pbFOR_ume_oth"]; break;
                    }
                    $formula .= $txt;            
                }
                //// INDICATIONS
                $sql3="SELECT * FROM \"ctg_productos_pb_FIT\"  WHERE \"adm_pbFIT_numreg\" = '{$IntNumReg}' LIMIT 1";
                $qTMP3 = pg_query($ADM, $sql3);
                while ($rTMP3 = pg_fetch_assoc($qTMP3)) {
                    $indications=$rTMP3["adm_pbFIT_fit_1"];         
                }        

                $sql4="SELECT * FROM \"ctg_productos_pb_EMPRESAS\"  WHERE \"adm_pbEMP_numreg\" = '{$IntNumReg}' AND \"adm_pbEMP_rol_id\" ='REP' LIMIT 1";
                $qTMP4 = pg_query($ADM, $sql4);
                while ($rTMP4 = pg_fetch_assoc($qTMP4)) {
                    $codemp=$rTMP4["adm_pbEMP_rif"];
                    
                    $sql41="SELECT * FROM ctg_empresas WHERE ctg_emp_rif = '{$codemp}' LIMIT 1 ";
                    $qTMP41 = pg_query($ADM, $sql41);
                    while ($rTMP41 = pg_fetch_assoc($qTMP41)) {    
                        $representante=$rTMP41["ctg_emp_nombre"];//." Dirección:".$rTMP41["ctg_emp_dir"]." Teléfono:".$rTMP41["ctg_emp_tels"]." Fax:".$rTMP41["ctg_emp_fax"];
                    }
                    
                }

                $sql5="SELECT * FROM \"ctg_productos_pb_EMPRESAS\"  WHERE \"adm_pbEMP_numreg\" = '{$IntNumReg}' AND \"adm_pbEMP_rol_id\" ='PRO' LIMIT 1";
                $qTMP5 = pg_query($ADM, $sql5);
                while ($rTMP5 = pg_fetch_assoc($qTMP5)) {
                    $codemp=$rTMP5["adm_pbEMP_rif"];
                    
                    $sql51="SELECT * FROM ctg_empresas WHERE ctg_emp_rif = '{$codemp}' LIMIT 1 ";
                    $qTMP51 = pg_query($ADM, $sql51);
                    while ($rTMP51 = pg_fetch_assoc($qTMP51)) {    
                        $propietario=$rTMP51["ctg_emp_nombre"];//." Dirección:".$rTMP51["ctg_emp_dir"]." Teléfono:".$rTMP51["ctg_emp_tels"]." Fax:".$rTMP51["ctg_emp_fax"];
                    }
                }

                $sql5="SELECT * FROM \"ctg_productos_pb_EMPRESAS\"  WHERE \"adm_pbEMP_numreg\" = '{$IntNumReg}' AND \"adm_pbEMP_rol_id\" ='ALM' LIMIT 1";
                $qTMP5 = pg_query($ADM, $sql5);
                while ($rTMP5 = pg_fetch_assoc($qTMP5)) {
                    $codemp=$rTMP5["adm_pbEMP_rif"];
                    
                    $sql51="SELECT * FROM ctg_empresas WHERE ctg_emp_rif = '{$codemp}' LIMIT 1 ";
                    $qTMP51 = pg_query($ADM, $sql51);
                    while ($rTMP51 = pg_fetch_assoc($qTMP51)) {    
                        $almacenador=$rTMP51["ctg_emp_nombre"];//." Dirección:".$rTMP51["ctg_emp_dir"]." Teléfono:".$rTMP51["ctg_emp_tels"]." Fax:".$rTMP51["ctg_emp_fax"];
                    }
                }      

                $sql5="SELECT * FROM \"ctg_productos_pb_EMPRESAS\"  WHERE \"adm_pbEMP_numreg\" = '{$IntNumReg}' AND \"adm_pbEMP_rol_id\" ='DIS' LIMIT 1";
                $qTMP5 = pg_query($ADM, $sql5);
                while ($rTMP5 = pg_fetch_assoc($qTMP5)) {
                    $codemp=$rTMP5["adm_pbEMP_rif"];
                    
                    $sql51="SELECT * FROM ctg_empresas WHERE ctg_emp_rif = '{$codemp}' LIMIT 1 ";
                    $qTMP51 = pg_query($ADM, $sql51);
                    while ($rTMP51 = pg_fetch_assoc($qTMP51)) {    
                        $distribuidor=$rTMP51["ctg_emp_nombre"];//." Dirección:".$rTMP51["ctg_emp_dir"]." Teléfono:".$rTMP51["ctg_emp_tels"]." Fax:".$rTMP51["ctg_emp_fax"];
                    }
                }                     
                $sql5="SELECT * FROM ctg_farmaceuticos WHERE ctg_farm_ci = '{$farma_ci}' LIMIT 1";
                $qTMP5 = pg_query($ADM, $sql5);
                while ($rTMP5 = pg_fetch_assoc($qTMP5)) {
                    $farmaceutico=strtoupper($rTMP5["ctg_farm_nombre"]);
                } 
                break;
            

        // echo "num sol (".$numsol.") nomprod (".$nomprod.")";
    }

//// LOCATION FOLDER
$sql9="SELECT * FROM adm_config";
$qTMP9 = pg_query($ADM, $sql9);
while ($rTMP9 = pg_fetch_assoc($qTMP9)) {
    $location=$rTMP9["adm_cnf_location_adm"];
    $firma=$rTMP9["adm_cnf_firma"];
}      
pg_free_result($qTMP);

$dirpath="/var/www/html/siverc".$location."/docs/{$tipo}/".$IntNumReg."/0/";
$dirpath2="/docs/{$tipo}/".$IntNumReg."/0/";
$path_new = "/var/www/html/siverc$location/docs/{$tipo}/";

mkdir($path_new,7777);
shell_exec("chmod 7777 $path_new");

$path_new .= "{$IntNumReg}/";	
mkdir($path_new,7777);
shell_exec("chmod 7777 $path_new");

$path_new1 = $path_new . "0/";	
mkdir($path_new1,7777);
shell_exec("chmod 7777 $path_new1");

$filename=$dirpath.$tipo.'_'.$IntNumReg.'_DR-01_1.pdf';
if (!file_exists($filename)){
    $sql9="INSERT INTO adm_control_{$tipo}1_docs (
        adm_cod_numsol,
        adm_cod_tpr_id,
        adm_cod_tpt_id,
        adm_cod_ttc_id,
        adm_cod_tec_id,
        adm_cod_tmf_id,
        adm_cod_part,
        adm_cod_path,
        adm_cod_file,
        adm_cod_numreg,
        adm_cod_sta,
        adm_cod_usr,
        adm_cod_dt ) VALUES (
        '".$IntNumSol."',
        '06',
        'AO',
        'DR',
        '".$admusuario."',
        '01',
        '1',
        '".$dirpath2."',
        'pb_".$IntNumReg."_DR-01_1.pdf',
        '".$IntNumReg."',
        '1',
        '".$admusuario."',
        now()
        )";
    $qTMP9 = pg_query($ADM, $sql9);
    // echo $sql9;
    // die();
}

// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->setPrintHeader(true);

class MYPDF extends TCPDF {

    //Page header
    public function Header() {
        // Logo
        $img_file = K_PATH_IMAGES.'pb_4_1.png';//'water_mark_13.jpeg';
        $this->Image($img_file, 5, 2, 0, 0, '', '', '', false, 300, '', false, false, 0);

    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->setY(-15);
        // Set font
        $this->setFont('helvetica', 'I', 7);
        // Page number
        $codveri="02902993";
        $this->Cell(0, 10, 'Pagina '.$this->getAliasNumPage().' de '.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
    }
}

// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->setHeaderMargin(PDF_MARGIN_HEADER);
$pdf->setFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
	require_once(dirname(__FILE__).'/lang/eng.php');
	$pdf->setLanguageArray($l);
}

// ---------------------------------------------------------
$box='1';
// set font
$pdf->setFont('helvetica', '', 12);

// add a page
$pdf->AddPage('P', 'LETTER');

// set cell padding
$pdf->setCellPaddings(1, 1, 1, 1);


// set color for background
$pdf->setFillColor(275, 275, 127);

// MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0)


// set some text to print
$txt1 = <<<EOD
SISTEMA NACIONAL DE REGISTRO SANITARIO DE PRODUCTOS FARMACÉUTICOS
CERTIFICADO DE REGISTRO SANITARIO

EOD;
$txt2 = <<<EOD
El Instituto Nacional de Higiene “Rafael Rangel” de conformidad con lo establecido en los artículos 1, 18 y 19 de la Ley de Medicamentos, publicada en la Gaceta Oficial de la República Bolivariana de Venezuela Nº 37.006 del 03 de Agosto de 2.000; siendo favorables los resultados de la evaluación integral, confiere el Registro Sanitario al siguiente producto farmacéutico:

EOD;
$pdf->Ln(45);
$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(190, 25, $number, 0, 'L', 0, 0, '', '', true);

$pdf->setFont('helvetica', '', 12);
$pdf->Ln(10);
$pdf->MultiCell(190, 25, $txt1, 0, 'C', 0, 0, '', '', true);
$pdf->Ln(15);
$pdf->setFont('helvetica', '',9);

$pdf->MultiCell(190, 25, $txt2, 0, 'J', 0, 0, '', '', true);
$pdf->Ln(25);

// set font
$pdf->setFont('helvetica', '', 7);

$pdf->MultiCell(40, 5, 'CLASIFICACIÓN', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(145, 5, "PRODUCTO BIOLÓGICO", $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 7);
$pdf->Ln(1);

$pdf->MultiCell(40, 5, 'NOMBRE DEL PRODUCTO', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(145, 5, $nomprod, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 7);
$pdf->Ln(1);

$pdf->MultiCell(40, 0, 'No. REGISTRO SANITARIO', 0, 'R', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(30, 5, $regnum, $box, 'L', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(40, 5, 'FECHA DE APROBACION', 0, 'R', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(20, 5, $date1, $box, 'L', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(25, 5, 'VIGENTE HASTA', 0, 'R', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(22, 5, $date2, $box, 'L', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->Ln(7);

$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(65, 5, 'NOMBRE(S) GENERICO(S)/PRINCIPIO(S) ACTIVO(S)', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(120, 5, $formula, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 7);
$pdf->Ln(1);

$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(65, 5, 'REPRESENTANTE / TITULAR DEL REGISTRO', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(120, 5, $representante, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 7);
$pdf->Ln(1);

$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(65, 5, 'FARMACÉUTICO PATROCINANTE', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(120, 5, $farmaceutico, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 7);
$pdf->Ln(1);

$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(65, 5, 'PROPIETARIO', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(120, 5, $propietario, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 7);
$pdf->Ln(1);

$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(65, 5, 'ALMACENADOR', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(120, 5, $almacenador, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 9);
$pdf->Ln(1);

$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(65, 5, 'DISTRIBUIDOR', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 7);
$pdf->MultiCell(120, 5, $distribuidor, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 9);
$pdf->Ln(5);

$final='El registro del producto autorizado queda sometido a todo lo previsto en la Ley de Medicamentos y cualquier otra Normativa Legal que regule la materia.
';
$pdf->MultiCell(190, 25, $final, 0, 'J', 0, 1, '', '', true);
$pdf->Ln(8);

$pdf->setFont('helvetica', '', 9);

$pdf->MultiCell(132, 3, '', 0, 'L', 0, 0, '', '', true);
$pdf->MultiCell(60 ,3, 'Caracas, '.$fecha, 0, 'L', 0, 0, '', '', true);

$pdf->Ln(25);
$pdf->setFont('helvetica', 'B', 12);
$pdf->MultiCell(190 ,3, 'DRA. ESPERANZA BRICEÑO GODOY', 0, 'C', 0, 0, '', '', true);
$pdf->Ln(5);
$pdf->setFont('helvetica', '', 7);
$pdf->MultiCell(190 ,3, $firma, 0, 'C', 0, 0, '', '', true);


// add a page
// $pdf->AddPage('P', 'LETTER');
// $pdf->setFont('helvetica', '', 13);

// // set cell padding
// $pdf->setCellPaddings(1, 1, 1, 1);
// $pdf->Ln(35);

// $pdf->setFont('helvetica', '', 7);
// $pdf->MultiCell(40 , 3, 'Registration Number', 0, 'R', 0, 0, '', '', true);
// $pdf->setFont('helvetica', 'B', 7);
// $pdf->MultiCell(120, 5, $regnum, 0, 'L', 0, 1, '', '', true);

// $pdf->Ln(5);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


// move pointer to last page
$pdf->lastPage();

// ---------------------------------------------------------

//Close and output PDF document

$filename2=$dirpath.'View_pb_'.$regnum.'_DR-01_1.pdf';
$pdf->Output($filename, 'F');
$pdf->Output($filename2, 'I');

//$pdf->Output('DrugCertificate'.$regnum.'.pdf', 'I');
// $pdf->Output('/var/www/html/dsoft/v5/lao/adm/temp/example_005.pdf', 'F');

//============================================================+
// END OF FILE
//============================================================+
