<?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
 */

// 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=172.16.0.21 port=5432 dbname=sivercADM 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";
} 

$sql="SELECT * FROM ctg_productos_{$tipo} WHERE adm_{$tipo}_numreg = '{$IntNumReg}' LIMIT 1 ";
$qTMP = pg_query($ADM, $sql);
    while ($rTMP = pg_fetch_assoc($qTMP)) {    
        switch ($tipo) {
            case 'ef':
                ////// MAIN DATA
                $numsol=$rTMP["adm__numsol"];
                $nomprod=$rTMP["adm_ef_nomprod"];
                $regnum=$rTMP["adm_ef_numreg"];
                $formid=$rTMP["adm_ef_forma"];
                $formDesc=$rTMP["adm_ef_forma"];
                $package=$rTMP["adm_ef_presenta"];
                $vencim=$rTMP["adm_ef_vencim"];
                $admin=$rTMP["adm_ef_admin"];
                $admin_oth=$rTMP["adm_ef_admin_oth"];
                $admin_val1=$rTMP["adm_ef_admin_val1"];
                $admin_val2=$rTMP["adm_ef_admin_val2"];
                $envaid=$rTMP["adm_ef_env_id"];
                $envaDesc=$rTMP["adm_ef_env_id"];
                $admusuario=$rTMP["adm_ef_usr"];
                $month=intval(substr($vencim,5,2)+1);
                if ($month>12)
                    $month=1;

                $date = new DateTime(date('Y').'-'.$month.'-01');
                $date->modify('last day of this month');
                $last_day_this_month = $date->format('Y-m-d');
                
                $fecha = substr($last_day_this_month,8,2)."-".substr($last_day_this_month,5,3).substr($vencim,0,4);
                
                $formula="";
                $manufacgurer="";
                $importer="";
                $desc = "";

                $issdate = "";
                switch ( substr($fecha,3,2)) {
                    case '01':
                        $issdate="January ";
                        break;
                    case '02':
                        $issdate="February ";
                        break;
                    case '03':
                        $issdate="March ";
                        break;
                    case '04':
                        $issdate="April ";
                        break;
                    case '05':
                        $issdate="May ";
                        break;
                    case '06':
                        $issdate="June ";
                        break;
                    case '07':
                        $issdate="July ";
                        break;
                    case '08':
                        $issdate="August ";
                        break;
                    case '09':
                        $issdate="September ";
                        break;
                    case '10':
                        $issdate="October ";
                        break;
                    case '11':
                        $issdate="November ";
                        break;
                    case '12':
                        $issdate="December ";
                        break;
                }
                $issdate1 =substr($last_day_this_month,8,2)." ".$issdate." ".substr($vencim,0,4);
                $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"];
                }
                $admin_oth=$rTMP["adm_ef_admin_oth"];
                $admin_val1=$rTMP["adm_ef_admin_val1"];
                $admin_val2=$rTMP["adm_ef_admin_val2"];
                switch ( $admin) {
                    case '1':
                        $desc=$admin_val1." ".$formDesc." per pack ";
                        break;
                    case '2':
                        $desc=$admin_val1." ".$envaDesc." / ".$admin_val2." ml";
                        break;
                    case '3':
                        $desc=$admin_val1." ".$formDesc." per pack";
                        break;
                    case '4':
                        $desc=$admin_val1." ".$formDesc." per pack ";
                        break;
                    case '5':
                        $desc=$admin_val1." ".$admin_oth." per pack ";
                        break;
                }        
                //// ACTIVE INGREDIENTS 
                $sql2="SELECT * FROM ctg_productos_ef_formula WHERE \"adm_efFOR_numreg\" = '{$IntNumReg}' AND \"adm_efFOR_tipo\"='1' ";
                $qTMP2 = pg_query($ADM, $sql2);
                while ($rTMP2 = pg_fetch_assoc($qTMP2)) {

                    if (!empty($formula))
                            $formula .= ", ";
                    $txt="";
                    $valor = $rTMP2["adm_efFOR_can"];
                    $valor = floatval($valor);
                    $txt .= $rTMP2["adm_efFOR_sus_nom"]." ".$rTMP2["adm_efFOR_cominfo"]." ".$valor;
                    $unimed=$rTMP2["adm_efFOR_ume_id"];
                    switch ($unimed) {
                        case '1':
                            $txt .= 'mg'; break;
                        case '2':
                            $txt .= 'mcg'; break;
                        case '3':
                            $txt .= 'IU'; break;
                        case '4':
                            $txt .= $rTMP2["adm_efFOR_ume_oth"]; break;
                    }
                    $formula .= $txt;            
                }
                //// INDICATIONS
                $sql3="SELECT * FROM \"ctg_productos_ef_FIT\"  WHERE \"adm_efFIT_numreg\" = '{$IntNumReg}' LIMIT 1";
                $qTMP3 = pg_query($ADM, $sql3);
                while ($rTMP3 = pg_fetch_assoc($qTMP3)) {
                    $indications=$rTMP3["adm_efFIT_fit_1"];         
                }        

                //// MANUFTURER
                $sql4="SELECT * FROM \"ctg_productos_ef_EMPRESAS\"  WHERE \"adm_efEMP_numreg\" = '{$IntNumReg}' AND \"adm_efEMP_rol_id\" ='FABPFI' LIMIT 1";
                $qTMP4 = pg_query($ADM, $sql4);
                while ($rTMP4 = pg_fetch_assoc($qTMP4)) {
                    $codemp=$rTMP4["adm_efEMP_rif"];
                    
                    $sql41="SELECT * FROM ctg_empresas WHERE ctg_emp_rif = '{$codemp}' LIMIT 1 ";
                    $qTMP41 = pg_query($ADM, $sql41);
                    while ($rTMP41 = pg_fetch_assoc($qTMP41)) {    
                        $manufacturer=$rTMP41["ctg_emp_nombre"]." Address:".$rTMP41["ctg_emp_dir"]." Telephone:".$rTMP41["ctg_emp_tels"]." Fax:".$rTMP41["ctg_emp_fax"];
                    }
                    
                }

                //// IMPORTER
                $sql5="SELECT * FROM \"ctg_productos_ef_EMPRESAS\"  WHERE \"adm_efEMP_numreg\" = '{$IntNumReg}' AND \"adm_efEMP_rol_id\" ='IMP' LIMIT 1";
                $qTMP5 = pg_query($ADM, $sql5);
                while ($rTMP5 = pg_fetch_assoc($qTMP5)) {
                    $codemp=$rTMP5["adm_efEMP_rif"];
                    
                    $sql51="SELECT * FROM ctg_empresas WHERE ctg_emp_rif = '{$codemp}' LIMIT 1 ";
                    $qTMP51 = pg_query($ADM, $sql51);
                    while ($rTMP51 = pg_fetch_assoc($qTMP51)) {    
                        $importer=$rTMP51["ctg_emp_nombre"]." Address:".$rTMP51["ctg_emp_dir"]." Telephone:".$rTMP51["ctg_emp_tels"]." Fax:".$rTMP51["ctg_emp_fax"];
                    }
                }      
                                break;
            
            default:
                # code...
                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"];
}      
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.'ef_'.$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."',
        '02',
        'AO',
        'DR',
        '".$admusuario."',
        '01',
        '1',
        '".$dirpath2."',
        'ef_".$IntNumReg."_DR-01_1.pdf',
        '".$IntNumReg."',
        '1',
        '".$admusuario."',
        now()
        )";
    $qTMP9 = pg_query($ADM, $sql9);

}

// 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);

$number='90922';
class MYPDF extends TCPDF {

    //Page header
    public function Header() {
        // Logo
        $image_file = K_PATH_IMAGES.'logo_Ministerio.png';
        $this->Image($image_file, 20, 4, 25, '', 'PNG', '', 'T', false, 300, 'C', false, false, 0, false, false, false);
    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->setY(-15);
        // Set font
        $this->setFont('helvetica', 'I', 8);
        // Page number
        // $html = <<<EOD
        // Código de verificación
        // Ciudad Universitaria UCV, Los Chaguaramos, Caracas - República Bolivariana de Venezuela Cod. 1041
        // Teléfono (0058-0212) 219.1622 http://www.ihrr.gob.ve RIF: G-20000101-1
        // Este certificado puede ser verificado en la dirección electrónica http://www.inhrr.gob.ve/
        // EOD;

        $codveri="02902993";

        // $this->Cell(0, 10, $html, 0, false, 'L', 0, '', 0, false, 'T', 'M');
        $this->Cell(0, 10, 'Pagina '.$this->getAliasNumPage().'/'.$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);
}

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

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

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

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

// set cell margins
$pdf->setCellMargins(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 FARMACEUTICOS

EOD;
$txt2 = <<<EOD
El Instituto Nacional de Higiene “Rafael Rangel” de conformidad con lo previsto en el Artículo 60 del Reglamento de la Ley de Ejercicio de
la Farmacia, publicado en Gaceta Oficial Nº 4.582 Extraordinaria de fecha 21 de mayo de 1993 y concordancia con la Resolución del Ministerio
de Salud y Desarrollo Social (actual Ministerio del Poder Popular para la Salud) Nº 0033 del 25 de octubre de 1999, publicado en Gaceta Oficial
de la República Bolivariana de Venezuela Nº 36.817 del 28 de octubre de 1999, otorga la Renovación del Registo Sanitario del siguiente producto
farmadéutico, quedando actualizado como se indica a continuación:
EOD;
$pdf->Ln(25);

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

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

$pdf->setFont('helvetica', '', 6);
$pdf->MultiCell(190, 25, $number, 0, 'L', 0, 0, '', '', true);

$pdf->Ln(5);


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

//$txt1 = 'TEL: ( 856 21 ) 214013, 214014 FAX: ( 856 21 ) 214015';


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

$txt = <<<EOD
Certificado de Renovacion de Registro de Medicamentos
EOD;

$pdf->MultiCell(172, 25, $txt.": ".$regnum, 0, 'C', 0, 0, '', '', true);

$pdf->Ln(10);

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

$pdf->MultiCell(180, 8, $nomprod, 1, 'C', 0, 1, '', '', true);

$pdf->Ln(1);

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

// Multicell test
$pdf->MultiCell(40, 5, 'Forma farmacéutica', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 8);

$pdf->MultiCell(120, 5, $formDesc, 0, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 8);

$pdf->Ln(1);

$pdf->MultiCell(40, 5, 'Ingredientes activos', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 8);
$pdf->MultiCell(120, 5, $formula, 0, 'L', 0, 1, '', '', true);

$pdf->Ln(1);

// $pdf->setFont('helvetica', '', 8);
// $pdf->MultiCell(40, 5, 'Empaque', 0, 'R', 0, 0, '', '', true);
// $pdf->setFont('helvetica', 'B', 8);
// $pdf->MultiCell(120, 5, $package, 0, 'L', 0, 1, '', '', true);

// $pdf->Ln(1);

// $pdf->setFont('helvetica', '', 8);
// $pdf->MultiCell(40, 2, 'Size of packaging unit', 0, 'R', 0, 0, '', '', true);
// $pdf->setFont('helvetica', 'B', 8);
// $pdf->MultiCell(120, 2, $desc, 0, 'L', 0, 1, '', '', true);

$pdf->Ln(1);
$pdf->setFont('helvetica', '', 8);
$pdf->MultiCell(40, 2, 'Indicaciones', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 8);
$pdf->MultiCell(140, 2, $indications, 0, 'L', 0, 1, '', '', true);

// $pdf->Ln(1);

// $regperno ='Registration/Permit No (Issued by exporting country):';
// $regdata='029888';
// $regdata2='Germany';

// $pdf->Ln(1);
// $pdf->setFont('helvetica', '', 8);
// $pdf->MultiCell(40, 2, $regperno, 0, 'R', 0, 0, '', '', true);
// $pdf->setFont('helvetica', 'B', 8);
// $pdf->MultiCell(120, 2, $regdata." - ".$regdata2, 0, 'L', 0, 1, '', '', true);

$pdf->Ln(1);

$pdf->setFont('helvetica', '', 8);
$pdf->MultiCell(40, 5, 'Fabricado por', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 8);
$pdf->MultiCell(150, 5, $manufacturer, 0, 'L', 0, 1, '', '', true);

// $pdf->Ln(1);

// $pdf->setFont('helvetica', '', 8);
// $pdf->MultiCell(40, 5, 'Name of the importer in Lao PDR', 0, 'R', 0, 0, '', '', true);
// $pdf->setFont('helvetica', 'B', 8);
// $pdf->MultiCell(110, 5, $importer, 0, 'L', 0, 1, '', '', true);

$pdf->Ln(10);
$pdf->setFont('helvetica', '', 8);

$final='
Este Certificado se emite para atestiguar que el producto descrito anteriormente ha cumplido con los estándares mínimos requeridos para el registro de medicamentos realizado por el INHRR.';
$pdf->MultiCell(190, 5, $final, 0, 'L', 0, 1, '', '', true);

// $pdf->Ln(1);

$pdf->setFont('helvetica', '', 8);
$pdf->MultiCell(130, 3, 'Este certificado vence, a menos que haya sido suspendido o revocado previamente, el ', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 8);
$pdf->MultiCell(35, 3, $issdate1, 0, 'L', 0, 1, '', '', true);

// $pdf->Ln(1);

$pdf->setFont('helvetica', '', 8);
$pdf->MultiCell(130 , 3, 'Nota: Todas las cajas y embalajes para importaciones deben llevar el número de registro.', 0, 'R', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 8);
$pdf->MultiCell(35, 5, $regnum, 0, 'L', 0, 1, '', '', true);

$pdf->Ln(5);
$pdf->setFont('helvetica', '', 8);

$pdf->MultiCell(90, 3, '', 0, 'L', 0, 0, '', '', true);
$pdf->MultiCell(40 ,3, 'Caracas,', 0, 'L', 0, 0, '', '', true);

$pdf->Ln(5);
$pdf->MultiCell(90, 3, '', 0, 'L', 0, 0, '', '', true);
$pdf->MultiCell(40 ,3, 'Presidente INHRR', 0, 'L', 0, 0, '', '', true);


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

// $pdf->Ln(5);

// $pdf->setFont('helvetica', '', 8);
// $pdf->MultiCell(40 , 3, 'Registration Number', 0, 'R', 0, 0, '', '', true);
// $pdf->setFont('helvetica', 'B', 8);
// $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_ef_'.$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
//============================================================+
