<?php

  $Position   = '../../../';
  require_once($Position.'config/config.php');
  require_once($Position.'config/conexion.php');
  require_once($Position.'config/user.php');
  require_once($Position.'funciones/acces.php');
  require_once($Position.'funciones/logout.php');
  require_once($Position.'funciones/funciones.php');

  //PDF
  require_once $Position.'dompdf/lib/html5lib/Parser.php';
  require_once $Position.'dompdf/lib/php-font-lib/src/FontLib/Autoloader.php';
  require_once $Position.'dompdf/lib/php-svg-lib/src/autoload.php';
  require_once $Position.'dompdf/src/Autoloader.php';
  Dompdf\Autoloader::register();
  use Dompdf\Dompdf;
  $pdf = new Dompdf();
  $Id = $_POST[IdFac];
  $PdfFile = $Position."facturacion/facturas/pdf/pdf-html.php";
  ob_start();
  include($PdfFile);
  $html = ob_get_clean();
  $pdf->loadHtml($html);

  // (Optional) Setup the paper size and orientation
  $pdf->setPaper('Letter', 'portrait');

  // Render the HTML as PDF
  $pdf->render();
  injectPageCount($pdf);

  // Output the generated PDF to Browser
  //$pdf->stream();
  $pdfString = $pdf->output();
  //$pdf->stream("Factura.pdf", array("Attachment" => false));

  function injectPageCount(Dompdf $pdf): void
  {
      /** @var CPDF $canvas */
      $canvas = $pdf->getCanvas();
      $pdf = $canvas->get_cpdf();

      foreach ($pdf->objects as &$o) {
          if ($o['t'] === 'contents') {
              $o['c'] = str_replace('DOMPDF_PAGE_COUNT_PLACEHOLDER', $canvas->get_page_count(), $o['c']);
          }
      }
  }
  //End PDF

  //Valida Envio
  //$Correo = 'fernando.ramirez.garcia@gmail.com';
  //$SendMail = 'Ok';
  if( $_POST['SendMail'] == 'Ok' && $_POST['Correo'] ){
    //if( $SendMail == 'Ok' && $Correo ){

    $IdFac    = $_POST[IdFac];
    //$IdFac    = $Id;

    //Factura
    $Query = "
      SELECT
        fac.Id, fac.Pdf, fac.RfcReceptor, fac.Receptor,
        fac.Serie, fac.Folio,
        fac.Xml
      FROM Facturas fac
      WHERE fac.Id = '$IdFac'
        AND fac.Fk_Cuenta = '$Cuenta[Id]'
    ";
    $Result = mysqli_query($mysqli, $Query);
    $Fac = mysqli_fetch_assoc($Result);

    if( $Fac[Id] ){

      //Malin Config
      $Query = "
  			SELECT
  				mai.Id,
          mai.From_Name, mai.From_Email, mai.From_Replayto,
          mai.Debug, mai.SMTPAuth, mai.SMTPSecure,
          mai.Host, mai.Port, mai.User, mai.Pass
  			FROM MailingConfig mai
  			WHERE mai.Active = '1'
  		";
  	  $Result = mysqli_query($mysqli, $Query);
  	  $MailerConfig = mysqli_fetch_assoc($Result);

      //Variables
      $subject  = 'Envio de Factura';
      $Correo   = addslashes($_POST['Correo']);
      $message  = addslashes($_POST['Mensaje']);

      if( $MailerConfig[Id] ){

        $from_name = $MailerConfig[From_Name];
        $from_mail = $MailerConfig[From_Email];
        $replyto   = $MailerConfig[From_Replayto];
        $mailto		 = $Correo;

        require($RootServer."/PHPMailer-master/src/PHPMailer.php");
        require($RootServer."/PHPMailer-master/src/Exception.php");
        require($RootServer."/PHPMailer-master/src/SMTP.php");

        $mail = new PHPMailer\PHPMailer\PHPMailer();
        $mail->IsSMTP(); // enable SMTP

        $mail->SMTPDebug = $MailerConfig[Debug]; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = $MailerConfig[SMTPAuth]; // authentication enabled
        $mail->SMTPSecure = $MailerConfig[SMTPSecure]; // secure transfer enabled REQUIRED for Gmail
        $mail->SMTPOptions = array(
          'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
          )
        );
        $mail->Host = $MailerConfig[Host];
        $mail->Port = $MailerConfig[Port]; // or 587 , 465, 25
        $mail->IsHTML(true);
        $mail->Username = $MailerConfig[User];
        $mail->Password = $MailerConfig[Pass];
        $mail->SetFrom($from_mail);
        $mail->IsHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $message;
        $mail->AddAddress($mailto);

        if( $pdfString ){
          $mail->addStringAttachment($pdfString, 'Factura-'.$Fac[Serie].'-'.$Fac[Folio].'.pdf');
        }

        if( $Fac[Xml] ){

          /*$contact_image_data="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA";
          $data = substr($contact_image_data, strpos($contact_image_data, ","));
          $filename="test.png";
          $encoding = "base64";
          $type = "image/png";
          $mail->AddStringAttachment(base64_decode($data), $filename, $encoding, $type);*/
          
          $mail->AddStringAttachment(base64_decode($Fac[Xml]), 'Factura-'.$Fac[Serie].'-'.$Fac[Folio].'.xml', 'base64', 'application/xml');
        }

      }

      //If Send Email
      if(!$mail->Send()){

        //Log MailSend
        $FechaHora = date('Y-m-d H:i:s');
        $Query = "
          INSERT INTO FacturasMailLogs (
            Fk_Usuario, Fk_Cuenta, Fk_Factura,
            Mail, Cc, Fecha
          )VALUES(
            '$User[Id]', '$Cuenta[Id]', '$Fac[Id]',
            '$Correo', '$Cc', '$FechaHora'
          )
        ";
        $Result = mysqli_query($mysqli, $Query);
        $IdSendMail = mysqli_insert_id($mysqli);
        //End Log MailSend

        $MailSended = 'Error';
        $Data = array('Sended' => 'Error', 'LogId' => $Id);
        echo json_encode($Data);

      }else{

        //Log MailSend
        $FechaHora = date('Y-m-d H:i:s');
        $Query = "
          INSERT INTO FacturasMailLogs (
            Fk_Usuario, Fk_Cuenta, Fk_Factura,
            Mail, Cc, Fecha
          )VALUES(
            '$User[Id]', '$Cuenta[Id]', '$Fac[Id]',
            '$Correo', '$Cc', '$FechaHora'
          )
        ";
        $Result = mysqli_query($mysqli, $Query);
        $IdSendMail = mysqli_insert_id($mysqli);
        //End Log MailSend

        $MailSended = 'Ok';
        $Data = array('Sended' => 'Ok', 'LogId' => $Id);
        echo json_encode($Data);

      }
      //End If Send Email

    }

  }
  //End Valida Envio

?>
