<?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"]);

$numAno=$_POST["numAno"];
$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
$sBono14 = "SELECT b14.*, TRIM(mae.mae_nom) AS mae_nom, TRIM(mae.mae_ape) AS mae_ape, mae_fing, TRIM(mae.mae_dpi) AS mae_dpi, 
            TRIM(mae.mae_email) AS mae_email, TRIM(tpu.tpu_nom) AS tpu_nom
            FROM bono14 b14
            LEFT JOIN maestro mae ON b14.b14_emp=mae.mae_emp AND b14.b14_cod = mae.mae_cod 
            LEFT JOIN tpuesto tpu ON mae.mae_tpue = tpu.tpu_cod 
            WHERE b14_emp='$empCod' AND b14_ano='$numAno'";

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

# 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["bono14"])) {
   $pdf = new generatePDF("P","cm", "Letter");
    $pdf->AddPage();    
    $lineHeight=0.5;
    $pdf->SetFont("ARIAL","B",16);
    $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("RECIBO DE PAGO BONO 14"),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["b14_liqrec"], 2, '.', ',')." ----",0,1,"L");
    $pdf->MultiAlignCell($lineWidth, $lineHeight, utf8_decode("POR: Pago Correpondiente al Bono 14 del  año: ").$numAno,0,1,"L");
    //$pdf->line($pdf->GetX()+0, $pdf->GetY(), 20.5, $pdf->GetY());
    $pdf->SetFont("","B",10);
    $lineHeight=0.62;
    $pdf->Ln();
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, "",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Fecha de ingreso:  "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, strftime("%d/%m/%Y", strtotime($rec["mae_fing"])),0,1,"L");
    $pdf->Ln();
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, "",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/4, $lineHeight, utf8_decode("Bono 14: "),0,0,"L");
    $pdf->MultiAlignCell($lineWidth/7, $lineHeight, number_format($rec["b14_bono"], 2, '.', ','),0,1,"R");

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

    $pdf->MultiAlignCell($lineWidth/4, $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["b14_liqrec"], 2, '.', ','),1,1,"R");
    $pdf->Ln(1);
    $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(3);
    $pdf->SetFont("","",9);
    $pdf->line($pdf->GetX()+6, $pdf->GetY(), 17, $pdf->GetY());
    $lineHeight=0.40;
    $pdf->MultiAlignCell($lineWidth/3, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/2, $lineHeight, $rec["b14_cod"]." - ".$rec["mae_nom"]." ".$rec["mae_ape"],0,1,"C");
    $pdf->MultiAlignCell($lineWidth/3, $lineHeight, " ",0,0,"L");
    $pdf->MultiAlignCell($lineWidth/2, $lineHeight, "DPI: ".$rec["mae_dpi"],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 Bono 14.');
        $mail->Body    = utf8_decode('Buena día estimado Colaborador,<br><br>Adjunto Recibo de pago Bono 14');

        $mail->send();
    } catch (Exception $e) {
        array_push($arrayError, array("cod"=>$rec["b14_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);
?>