<?php
include_once("../../../php/sessionStart.php"); 
include_once("../../../php/db/dbExec.php");
include_once('../../../php/functions.php');
include_once("../../../php/fpdf/functions.php");
include_once('../../../php/timezone.php');
include_once('../../../php/maxExecTime.php');

// email
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

include_once("../../../php/PHPMailer/src/PHPMailer.php");
include_once("../../../php/PHPMailer/src/SMTP.php");
include_once("../../../php/PHPMailer/src/Exception.php");
// email

$empCod=utf8_decode($_SESSION["empCod"]);
$empNom=utf8_decode($_SESSION["empNom"]);
$empNomc=utf8_decode($_SESSION["empNomc"]);

$numNum=$_POST["numNum"];
$numCoddm=(empty($_POST['numCoddm'])) ? 0 : $_POST['numCoddm'];
$dtFec=$_POST["dtFec"];

$arrayError=array();

$lineWidth=19;
$lineHeight=0.42;

class generatePDF extends PDF_MC_Table {
    function Header() {
    }
    
    function Footer() {
        // Posición: a 1,5 cm del final
        //$this->SetY(-2.5);
        //$this->SetFont("Arial","I",8);
        //$this->Cell(0,1,"PAGINA ".$this->PageNo(),0,0,"C");
    }
}

# QUERYS
if ($numCoddm==0) {
    $sNomper = "SELECT np.*, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape,
                TRIM(tpu.tpu_nom) AS tpu_nom
                FROM nomper np
                LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                WHERE np_emp='$empCod' AND np_numpla='$numNum'";
} else {
    $sNomper = "SELECT np.*, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape,
                TRIM(tpu.tpu_nom) AS tpu_nom
                FROM nomper np
                LEFT JOIN maestro mae ON np.np_emp=mae.mae_emp AND np.np_cod = mae.mae_cod 
                LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
                WHERE np_emp='$empCod' AND np_numpla='$numNum'  AND np_cod='$numCoddm'";
}

# EJECUCION DE QUERYS
$db = new dbExec();
$select["nomper"] = $db->query($sNomper);

# GENERAR PDF
//$pdf = new generatePDF("L","cm", "Letter");
//$pdf = new generatePDF("P","cm", "Letter");
//$pdf->AddPage();
$func = new functions();
$ti_clasi="XXX";
while ($rec = $db->fetchAssoc($select["nomper"])) {

    $pdf = new generatePDF("P","cm", "Letter");
    $pdf->AddPage();    
    $pdf->SetFont("ARIAL","B",16);
    $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("RECIBO DE PAGO"),0,1,"C");
    //.strftime("%d/%m/%Y")),0,1,"L");
    //$pdf->Ln();
    $pdf->SetFont("","",10);
    $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("RECIBI DE: ").$empNom,0,1,"L");
    $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("LA CANTIDAD DE: ------ Q. ").number_format($rec["np_liqrec"], 2, '.', ',')." ----",0,1,"L");
    $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("POR: Pago de Salario Correpondiente al periodo del  ").strftime("%d/%m/%Y", strtotime($rec["np_fini"]))."  al  ".strftime("%d/%m/%Y", strtotime($rec["np_ffin"])),0,1,"L");
    //$pdf->line($pdf->GetX()+0, $pdf->GetY(), 20.5, $pdf->GetY());
    $pdf->SetFont("","B",10);
    $pdf->MultiAlignCell($lineWidth/2, $lineHeight, utf8_decode("INGRESOS:"),1,0,"L");
    $pdf->MultiAlignCell($lineWidth/2, $lineHeight, utf8_decode("DESCUENTOS:"),1,0,"L");
    $pdf->SetFont("","",10);
    $pdf->Ln();
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Días Trabajados:  ").number_format($rec["np_dtra"], 2, '.', ','),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Días Suspendido:  ").number_format($rec["np_dsusi"], 2, '.', ','),0,1,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Días Vacaciones:  ").number_format($rec["np_dvaca"], 2, '.', ','),0,1,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("H/Extras Simples:  ").number_format($rec["np_hsim"], 2, '.', ','),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("H/Extras Dobles:   ").number_format($rec["np_hdob"], 2, '.', ','),0,1,"L");
    $pdf->Ln();
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Sueldo Ordinario: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_sord"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("IGSS: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_igss"], 2, '.', ','),0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Sueldo Extra Normal: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_sexts"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("ISR: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_isr"], 2, '.', ','),0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Sueldo Extra Feriado: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_sextd"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Anticipo: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_anti"], 2, '.', ','),0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Bonificación Ley: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_boni"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Prestamo Bancario: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_preb"], 2, '.', ','),0,1,"R");


    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Bonificación Incentivo: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_bonii"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Prestamo Farkelos: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_pree"], 2, '.', ','),0,1,"R");


    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Bono Extra: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_bonoe"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Bazar: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_unif"], 2, '.', ','),0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Comisiones S/Ventas: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_comi"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Aportaciones Farkelos: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_lent"], 2, '.', ','),0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Devolucion Isr: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_isrdevo"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Desc. Judicial: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_desj"], 2, '.', ','),0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Depreciacion Vehiculo: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_depre"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Descuentos Varios: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_otrd"], 2, '.', ','),0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Viaticos: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_viati"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, "",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, "",0,1,"R");

    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Otros Ingresos: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_otrp"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, "",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, "",0,1,"R");

    $pdf->line($pdf->GetX()+10, $pdf->GetY(), 19, $pdf->GetY());    
    $pdf->SetFont("","",10);
    $pdf->line($pdf->GetX()+0, $pdf->GetY(), 9, $pdf->GetY());    
    $pdf->SetFont("","B",9);
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("TOTAL DEVENGADO: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_totdev"], 2, '.', ','),0,0,"R");
    $pdf->MultiAlignCell($lineWidth/8, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("TOTAL DESCUENTOS: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_totdes"], 2, '.', ','),0,1,"R");
    $pdf->SetFont("","B",11);
    //$pdf->Ln();
    $pdf->MultiAlignCell($lineWidth/1.9, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("LIQUIDO A RECIBIR: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["np_liqrec"], 2, '.', ','),1,1,"R");
    $pdf->line($pdf->GetX()+0, $pdf->GetY(), 19, $pdf->GetY());    
    $pdf->SetFont("","",8);
    $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("Fecha de Emisión:  ").strftime("%d/%m/%Y", strtotime($dtFec)),0,1,"L");
    $pdf->Ln(1.5);
    $pdf->SetFont("","",9);
    $pdf->line($pdf->GetX()+6, $pdf->GetY(), 17, $pdf->GetY());    
    $pdf->MultiAlignCell($lineWidth/3, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/2, $lineHeight, $rec["np_cod"]." - ".$rec["mae_nom"]." ".$rec["mae_ape"],0,1,"C");
    $pdf->Ln(1);

    $emailAttachment = $pdf->Output('','S');


    // Enviar por email
    $mail = new PHPMailer(true);

    try {
        //Server settings
        $mail->SMTPDebug = 0;//SMTP::DEBUG_SERVER;
        $mail->isSMTP();

        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'gustavohernandezra@gmail.com';
        $mail->Password   = '110263';
        $mail->SMTPSecure = 'ssl';//PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 465;

        //Recipients
        $mail->setFrom('gustavohernandezra@gmail.com', utf8_decode($empNomc));
        $mail->addAddress($rec["mae_email"]);

/*        while ($rec = $db->fetchAssoc($select["cliencc"])) {
            $mail->addAddress($rec["cm_mail"]);
        }  */
//        $mail->addCC('facturaelectronica@megared.com.gt');
        $mail->AddStringAttachment($emailAttachment, utf8_decode('Recibo de Pago.pdf'), 'base64', 'application/pdf');
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = utf8_decode('Recibo de Pago.');
        $mail->Body    = utf8_decode('Buena día estimado Colaborador,<br><br>Adjunto Recibo de pago');

        $mail->send();
    } catch (Exception $e) {
        array_push($arrayError, array("cod"=>$rec["np_cod"], "ErrorInfo"=>''.$mail->ErrorInfo));
    }


    //La linea de abajo se desbloquea, si se puede configurar media carta en la impresora que usen
//    $pdf->AddPage();
}

$db->close();

//$pdf->Output(utf8_decode("Recibos").".pdf","I");
// Por si no se pudo guardar la factura de algún cliente
$sizeError = sizeof($arrayError);
$title = "";
$text = "";
if ($sizeError != 0) {
    $title = "email";
    $text .='<div style="margin: 0 auto"><b>No se pudo enviar todos los mensajes</b></div>';
    $text .='<table style="margin: 0 auto"><tr><td width="70">Código</td><td width="">Descripción</td>';
    foreach($arrayError as $row) {
        $text .="<tr><td class='text-center'>{$row['cod']}</td><td class='text-center'>{$row['ErrorInfo']}</td></tr>";
    }
    $text .='</table>';
    $resp = $db->rErrorPublic($title, $text);
} else {
    $resp = $db->rSuccess("Mensajes enviados con éxito");
}

//return $func->jsonEncodeArray($resp, "msg");
echo json_encode($resp);
?>