<?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=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_stringVUS = "host=localhost port=5432 dbname=sivercV user=postgresuser password=p05tgr35u53r";
 
// establecemos una conexion con el servidor postgresSQL
$VUS = pg_connect($conn_stringVUS);
 
// Revisamos el estado de la conexion en caso de errores. 

if(!$VUS) {
    echo "Connection to ADM Database error\n";
} 
$number='90922';
$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);

$sql="SELECT * FROM vus_tramites_{$tipo}2 WHERE vus_{$tipo}_numsol = '{$IntNumSol}' LIMIT 1 ";
$qTMP = pg_query($VUS, $sql);
    while ($rTMP = pg_fetch_assoc($qTMP)) {    
        switch ($tipo) {
            case 'ef':
                ////// MAIN DATA
                $numsol=$rTMP["vus_ef_tpt_id"]."-".$rTMP["vus_ef_numsol"];
                $nomprod=$rTMP["vus_ef_nomprod"];
                $regnum=$rTMP["vus_ef_numsol"];
                $formid=$rTMP["vus_ef_forma"];
                $formDesc=$rTMP["vus_ef_forma"];
                $package=$rTMP["vus_ef_presenta"];
                $autori=$rTMP["vus_ef_autori"];
                $vencim=$rTMP["vus_ef_vencim"];
                $admin=$rTMP["vus_ef_admin"];
                $admin_oth=$rTMP["vus_ef_admin_oth"];
                $admin_val1=$rTMP["vus_ef_admin_val1"];
                $admin_val2=$rTMP["vus_ef_admin_val2"];
                $envaid=$rTMP["vus_ef_env_id"];
                $envaDesc=$rTMP["vus_ef_env_id"];
                $admusuario=$rTMP["vus_ef_usr"];
                $farma_ci=trim($rTMP["vus_ef_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="";
                $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"];
                }
                $admin_oth=$rTMP["vus_ef_admin_oth"];
                $admin_val1=$rTMP["vus_ef_admin_val1"];
                $admin_val2=$rTMP["vus_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 vus_tramites_ef_formula WHERE \"vus_efFOR_numsol\" = '{$IntNumSol}' AND \"vus_efFOR_tipo\"='1' ";
                $qTMP2 = pg_query($ADM, $sql2);
                while ($rTMP2 = pg_fetch_assoc($qTMP2)) {

                    if (!empty($formula))
                            $formula .= ", ";
                    $txt="";
                    $valor = $rTMP2["vus_efFOR_can"];
                    $valor = floatval($valor);
                    $txt .= $rTMP2["vus_efFOR_sus_nom"]." ".$rTMP2["vus_efFOR_cominfo"]." ".$valor;
                    $unimed=$rTMP2["vus_efFOR_ume_id"];
                    switch ($unimed) {
                        case '1':
                            $txt .= 'mg'; break;
                        case '2':
                            $txt .= 'mcg'; break;
                        case '3':
                            $txt .= 'IU'; break;
                        case '4':
                            $txt .= $rTMP2["vus_efFOR_ume_oth"]; break;
                    }
                    $formula .= $txt;            
                }
                $sql4="SELECT * FROM \"vus_tramites_ef2_EMPRESAS\"  WHERE \"vus_efEMP_numsol\" = '{$IntNumSol}'AND \"vus_efEMP_rol_id\" ='REP' LIMIT 1";
                $qTMP4 = pg_query($VUS, $sql4);
                while ($rTMP4 = pg_fetch_assoc($qTMP4)) {
                    $codemp=$rTMP4["vus_efEMP_rif"];
                    $representante=$rTMP4["vus_efEMP_nombre"];//." Dirección:".$rTMP41["ctg_emp_dir"]." Teléfono:".$rTMP41["ctg_emp_tels"]." Fax:".$rTMP41["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;
            
            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"];
    $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.'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_numsol,
        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);
    // 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_4.png';//'water_mark_20.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='0';
// 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
$firma=<<<EOD
Directora General de Regulación Sanitaria de 
Productos de Uso y Consumo Humano (E)
Según Punto de Cuenta 144/2019 de fecha 17/05/2019
Delegación según Providencia N° PRESINHRR-007/2022 de fecha 11 de Agosto de 2022

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

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

$pdf->MultiCell(110, 3, '', 0, 'L', 0, 0, '', '', true);
$pdf->MultiCell(80 ,3, 'Caracas, '.$fecha, 0, 'L', 0, 0, '', '', true);
$pdf->Ln(10);

$pdf->MultiCell(40, 5, 'Ciudadano(a):', 0, 'L', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 12);
$pdf->Ln(5);
$pdf->MultiCell(40, 5, $farmaceutico, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '',10);

$pdf->MultiCell(60, 5, 'Farmacéutico Patrocinante', 0, 'L', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 12);
$pdf->Ln(5);
$pdf->MultiCell(145, 5, $representante, $box, 'L', 0, 1, '', '', true);
$pdf->setFont('helvetica', '', 12);
$pdf->MultiCell(40, 5, 'Presente.-', 0, 'L', 0, 0, '', '', true);
$pdf->setFont('helvetica', 'B', 12);
$pdf->Ln(15);

$pdf->setFont('helvetica', '',10);
$pdf->MultiCell(85, 0, 'En relacion a la solicitud de Registro Sanitario No.', 0, 'L', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', 'B', 12);
$pdf->MultiCell(40, 5, $numsol, 1, 'L', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', '', 12);
$pdf->MultiCell(60, 5, 'correspondiente al producto  ', 0, 'R', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->Ln(10);
$pdf->MultiCell(190, 5, $nomprod, 1, 'L', 0, 0, '', '', true, 0, false, true, 40,'T');
$pdf->setFont('helvetica', '', 12);
$pdf->Ln(10);
$txt=<<<EOD
el Instituto Nacional de Higiene “Rafael Rangel” le informa que la misma ha sido rechazada,  según lo establecido en el Capítulo IV, Grupo K, Numeral 1, Literal b, de la Norma de la Junta Revisora de Productos Farmacéuticos, por los motivos indicados a continuación:

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

$txt1=<<<EOD
1. Aqui va el motivo del rechazo, este texto estara en un campo tipo text para que pueda ser manipulado antes de la generacion del arhcivo pdf.

EOD;
$pdf->MultiCell(190 ,3, $txt1, 0, 'C', 0, 0, '', '', true);
$pdf->Ln(20);



$pdf->Ln(25);
$pdf->setFont('helvetica', 'B', 12);
$pdf->MultiCell(190 ,3, 'DRA. ALEXANDRA HERNANDEZ', 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_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
//============================================================+
