<?php
set_time_limit(0);
include_once '../../vendor/autoload.php';
require_once '../../conexiones/conexion.php';

$dbcon = new Conexion;
$conexion = $dbcon->conectar();

$usuario =  !empty($_POST['usuario']) && isset($_POST['usuario']) ? $_POST['usuario'] : "";

$folioGuthrie = !empty($_POST['folioGuthrie']) && isset($_POST['folioGuthrie']) ? strtoupper(trim($_POST['folioGuthrie'])) : "";
$nomMadre  = !empty($_POST['nomMadre']) && isset($_POST['nomMadre']) ? strtoupper(trim($_POST['nomMadre'])) : "";
$cve_region  = !empty($_POST['cve_region']) && isset($_POST['cve_region']) ? $_POST['cve_region'] : "";
$cve_estado  = !empty($_POST['cve_estado']) && isset($_POST['cve_estado']) ? $_POST['cve_estado'] : "";
$cve_matriz  = !empty($_POST['cve_matriz']) && isset($_POST['cve_matriz']) ? $_POST['cve_matriz'] : "";
$cve_unidad  = !empty($_POST['cve_unidad']) && isset($_POST['cve_unidad']) ? $_POST['cve_unidad'] : "";
$analito  = !empty($_POST['cve_analito']) && isset($_POST['cve_analito']) ? $_POST['cve_analito'] : "";
$estatus_muestra = !empty($_POST['estatus_muestra']) && isset($_POST['estatus_muestra']) ? $_POST['estatus_muestra'] : "";
$num_notificacion = !empty($_POST['num_notificacion'])? $_POST['num_notificacion'] : "";

$fecha_toma_inicio  = !empty($_POST['fecha_inicio_toma'])? $_POST['fecha_inicio_toma'] : "";
$fecha_toma_fin  = !empty($_POST['fecha_fin_toma'])? $_POST['fecha_fin_toma'] : "";
$fecha_inicio = !empty($_POST['fecha_inicio']) && isset($_POST['fecha_inicio']) ? $_POST['fecha_inicio'] : "";
$fecha_fin = !empty($_POST['fecha_fin']) && isset($_POST['fecha_fin']) ? $_POST['fecha_fin'] : "";
$fecha_inicio_reporte = !empty($_POST['fecha_inicio_reporte'])? $_POST['fecha_inicio_reporte'] : "";
$fecha_fin_reporte = !empty($_POST['fecha_fin_reporte'])? $_POST['fecha_fin_reporte'] : "";
$fecha_notificacion_inicio  = !empty($_POST['fecha_inicio_notificacion'])? $_POST['fecha_inicio_notificacion'] : "";
$fecha_notificacion_fin  = !empty($_POST['fecha_fin_notificacion'])? $_POST['fecha_fin_notificacion'] : "";



$sql = "SELECT 
        ns.cve_not_sospechosa,  sol.cve_solicitud_recuperacion, rmu.cve_recepcion_muestra,
        ces.desc_estado, 
        cma.desc_matriz,
        cum.desc_unidad_medica,
        dpa.nombre_completo_paciente, 
        COALESCE(sol.ns_nombre_madre,COALESCE(dma.nombre,''))||' '||
        COALESCE(sol.ns_paterno_madre,COALESCE(dma.apellido_paterno,''))||' '||
        COALESCE(sol.ns_materno_madre,COALESCE(dma.apellido_materno,'')) nombrecompleto,
        COALESCE(sol.folio_solicitud,dmu.folio) folio,
        rmu.estatus_muestra,
        to_char(sol.fecha_solicitud,'dd/mm/yyyy') fecha_solicitud,
        to_char(sol.log_entrega_fechaentrega,'dd/mm/yyyy') log_entrega_fechaentrega,
        to_char(sol.log_fecha_envio_transito,'dd/mm/yyyy') log_fecha_envio_transito,
        to_char(sol.sos_rcp_fecharecibe,'dd/mm/yyyy') sos_rcp_fecharecibe,
        sol.log_entrega_nombrerecibe, 
        sol.log_proveedor_paqueteria||(case when sol.log_proveedor_paqueteria = 'OTRO' THEN ': '||sol.log_otro_proveedorpaqueteria else '' end) paqueteria, 
        sol.log_entrega_numeroguia,
        sol.estatus_recuperacion, 
        sol.motivo_cancelacion,
        string_agg((select string_agg(desc_enfermedad::text,', ') from cat_enfermedades WHERE cve_enfermedad in (select unnest(string_to_array(COALESCE(sol.ns_enfermedades,rmu.enfermedades_sospechosas) , ','))::numeric)),'') enfermedades,
        string_agg((select string_agg(desc_tipo_muestra::text,', ') from cat_tipo_muestras WHERE cve_tipo_muestra in (select unnest(string_to_array(COALESCE(sol.ns_tipomuestra,rmu.tipo_muestras_sospechosas), ','))::numeric)),'') tipomuestras
        FROM
        recepciones_muestras rmu 
        left join notificaciones_sospechosas ns on rmu.cve_recepcion_muestra = ns.cve_recepcion_muestra 
        join pacientes pac on rmu.cve_recepcion_muestra = pac.cve_recepcion_muestra 
        join datos_madres dma on pac.cve_dato_madre = dma.cve_dato_madre
        join datos_pacientes dpa on pac.cve_dato_paciente = dpa.cve_dato_paciente
        join datos_muestras dmu on dmu.cve_dato_muestra = pac.cve_dato_muestra
        left join solicitudes_recuperaciones sol on rmu.cve_recepcion_muestra = sol.cve_recepcion_muestra and sol.estatus_registro = 'VIG'
        left join cat_unidades_".$usuario." cum on COALESCE(sol.cve_unidad_medica,dmu.cve_unidad_medica) = cum.cve_unidad_medica
        left join cat_matrizes cma on cum.cve_matriz = cma.cve_matriz
        left join cat_estados ces on cma.cve_estado = ces.cve_estado
        WHERE 1 = 1
        and rmu.confirmatoria = true ";

if(!empty($folioGuthrie)){
    $sql .= " and dmu.folio like '%$folioGuthrie%' ";
}
if(!empty($nomMadre)){
    $sql .= " and ( dma.nombre||' '||dma.apellido_paterno||' '||dma.apellido_materno like '%$nomMadre%' ";
    $sql .= "   or dma.apellido_paterno||' '||dma.apellido_materno||' '||dma.nombre like '%$nomMadre%' ) ";
}
if(!empty($cve_region)){
    $sql .= " and cum.cve_region = ". $cve_region ." ";
}
if(!empty($cve_estado)){
    $sql .= " and cum.cve_estado = ". $cve_estado ." ";
}
if(!empty($cve_matriz)){
    $sql .= " and cum.cve_matriz = ". $cve_matriz ." ";
}
if(!empty($cve_unidad)){
    $sql .= " and cum.cve_unidad_medica = ". $cve_unidad ." ";
}
if(!empty($analito)){
   $sql .= " and mrd.cve_enfermedad = ". $analito ." ";
}
if(!empty($estatus_muestra)){
    $sql .= " and rmu.estatus_muestra = '". $estatus_muestra."' ";
}
if(!empty($num_notificacion)){
    $sql .= " and ns.cve_not_sospechosa = '". $num_notificacion ."' ";
}
if(!empty($fecha_toma_inicio)){
    $sql .= " and dmu.fecha_muestra::date >= to_date('$fecha_toma_inicio','dd/mm/yyyy') ";
}
if(!empty($fecha_toma_fin)){
    $sql .= " and dmu.fecha_muestra::date <= to_date('$fecha_toma_fin','dd/mm/yyyy') ";
}
if(!empty($fecha_inicio)){
    $sql .= " and pac.fecha_registro::date >= to_date('$fecha_inicio','dd/mm/yyyy') ";
}
if(!empty($fecha_fin)){
    $sql .= " and pac.fecha_registro::date <= to_date('$fecha_fin','dd/mm/yyyy') ";
}
if(!empty($fecha_inicio_reporte)){
    $sql .= " and mrd.fecha_registro::date >= to_date('$fecha_inicio_reporte','dd/mm/yyyy') ";
}
if(!empty($fecha_fin_reporte)){
    $sql .= " and mrd.fecha_registro::date <= to_date('$fecha_fin_reporte','dd/mm/yyyy') ";
}
if(!empty($fecha_notificacion_inicio)){
    $sql .= " and ns.fecha_notificacion::date >= to_date('$fecha_notificacion_inicio','dd/mm/yyyy') ";
}
if(!empty($fecha_notificacion_fin)){
    $sql .= " and ns.fecha_notificacion::date <= to_date('$fecha_notificacion_fin','dd/mm/yyyy') ";
}

$sql .= "GROUP BY 
        ns.cve_not_sospechosa,  sol.cve_solicitud_recuperacion, rmu.cve_recepcion_muestra,
        ces.desc_estado, 
        cma.desc_matriz,
        cum.desc_unidad_medica,
        dpa.nombre_completo_paciente, 
        COALESCE(sol.ns_nombre_madre,COALESCE(dma.nombre,''))||' '||COALESCE(sol.ns_paterno_madre,COALESCE(dma.apellido_paterno,''))||' '||COALESCE(sol.ns_materno_madre,COALESCE(dma.apellido_materno,'')),
        COALESCE(sol.folio_solicitud,dmu.folio),
        rmu.estatus_muestra,
        to_char(sol.fecha_solicitud,'dd/mm/yyyy'),
        to_char(sol.log_entrega_fechaentrega,'dd/mm/yyyy'),
        to_char(sol.log_fecha_envio_transito,'dd/mm/yyyy'),
        to_char(sol.sos_rcp_fecharecibe,'dd/mm/yyyy'),
        sol.log_entrega_nombrerecibe, 
        sol.log_proveedor_paqueteria||(case when sol.log_proveedor_paqueteria = 'OTRO' THEN ': '||sol.log_otro_proveedorpaqueteria else '' end) , 
        sol.log_entrega_numeroguia,
        sol.estatus_recuperacion, 
        sol.motivo_cancelacion
        ORDER BY ns.cve_not_sospechosa DESC, sol.cve_solicitud_recuperacion desc, rmu.cve_recepcion_muestra desc";

$vquery = $conexion->prepare($sql);
$vquery->execute();
$rows = $vquery->fetchAll(PDO::FETCH_ASSOC);

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

$titulos = [
    'font' => [ 'bold' => 'true', 'size' => 12 ],
    'alignment' =>[ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER ]
];

$subtitulos_principales = [
    'font' => [ 'bold' => 'true', 'size' => 12, 'color' => array('rgb' => 'FFFFFF') ],
    'alignment' =>[ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER ],
    'fill' => [
        'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
        'startColor' => array('rgb' => '2081C3')
    ]
];

$date = date('d/m/Y H:i:s');
$date2 = date('Y');

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('CNEG - Placas');
$spreadsheet->getActiveSheet()->mergeCells('A1:G1');
$sheet->setCellValue('A1', 'TAMIZ MAS DE QUIMICOS MALDONADO '.$date2);
$sheet->getStyle('A1')->applyFromArray($titulos);

$sheet
    ->setCellValue('A3', 'Usuario consultó:')
    ->setCellValue('B3', $usuario)
    ->setCellValue('C3', 'Fecha de consulta:')
    ->setCellValue('D3', $date);

$sheet
    ->setCellValue('A4', '# Notificación Sospechosa')
    ->setCellValue('B4', 'Estado')
    ->setCellValue('C4', 'Jurisdicción')
    ->setCellValue('D4', 'Unidad médica')
    ->setCellValue('E4', 'Nombre del Paciente')
    ->setCellValue('F4', 'Nombre de la Madre')
    ->setCellValue('G4', 'Folio Muestra')
    ->setCellValue('H4', 'Estatus Muestra')
    ->setCellValue('I4', 'Muestra Recolectada')
    ->setCellValue('J4', 'Enfermedad Sospechosa')
    ->setCellValue('K4', 'Fecha de Solicitud')
    ->setCellValue('L4', 'Fecha Programada')
    ->setCellValue('M4', 'Fecha de Envió')
    ->setCellValue('N4', 'Fecha de Ingreso a Sospechas')
    ->setCellValue('O4', 'Nombre del Recolector')
    ->setCellValue('P4', 'Paquetería')
    ->setCellValue('Q4', 'Num. Guía')
    ->setCellValue('R4', 'Estatus Recolección')
    ->setCellValue('S4', 'Motivo de Cancelación');
    
$sheet->getStyle('A4:S4')->applyFromArray($subtitulos_principales);
$ln = 5;
foreach ($rows as $pa) {
    $sheet
        ->setCellValue('A'.$ln, !empty($pa['cve_not_sospechosa'])?$pa['cve_not_sospechosa']:'S/D')
        ->setCellValue('B'.$ln, !empty($pa['desc_estado'])?$pa['desc_estado']:'S/D')
        ->setCellValue('C'.$ln, !empty($pa['desc_matriz'])?$pa['desc_matriz']:'S/D')
        ->setCellValue('D'.$ln, !empty($pa['desc_unidad_medica'])?$pa['desc_unidad_medica']:'S/D')
        ->setCellValue('E'.$ln, !empty($pa['nombre_completo_paciente'])?$pa['nombre_completo_paciente']:'S/D') 
        ->setCellValue('F'.$ln, !empty($pa['nombrecompleto'])?$pa['nombrecompleto']:'S/D') 
        ->setCellValue('G'.$ln, !empty($pa['folio'])?$pa['folio']:'S/D') 
        ->setCellValue('H'.$ln, !empty($pa['estatus_muestra'])?$pa['estatus_muestra']:'S/D') 
        ->setCellValue('I'.$ln, !empty($pa['tipomuestras'])?$pa['tipomuestras']:'S/D')
        ->setCellValue('J'.$ln, !empty($pa['enfermedades'])?$pa['enfermedades']:'S/D')
        ->setCellValue('K'.$ln, !empty($pa['fecha_solicitud'])?$pa['fecha_solicitud']:'S/D')
        ->setCellValue('L'.$ln, !empty($pa['log_entrega_fechaentrega'])?$pa['log_entrega_fechaentrega']:'S/D')
        ->setCellValue('M'.$ln, !empty($pa['log_fecha_envio_transito'])?$pa['log_fecha_envio_transito']:'S/D')
        ->setCellValue('N'.$ln, !empty($pa['sos_rcp_fecharecibe'])?$pa['sos_rcp_fecharecibe']:'S/D')
        ->setCellValue('O'.$ln, !empty($pa['log_entrega_nombrerecibe'])?$pa['log_entrega_nombrerecibe']:'S/D') 
        ->setCellValue('P'.$ln, !empty($pa['paqueteria'])?$pa['paqueteria']:'S/D')
        ->setCellValue('Q'.$ln, !empty($pa['log_entrega_numeroguia'])?$pa['log_entrega_numeroguia']:'S/D')
        ->setCellValue('R'.$ln, !empty($pa['estatus_recuperacion'])?$pa['estatus_recuperacion']:'S/D') 
        ->setCellValue('S'.$ln, !empty($pa['motivo_cancelacion'])?$pa['motivo_cancelacion']:'S/D')
        ;
        $ln++;
}

for($i = 'A'; $i <= 'S'; $i++){
	$spreadsheet->getActiveSheet()->getColumnDimension($i)->setAutoSize(true);
}

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Recoleciones_Muestras.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
?>