<?php
namespace App\Http\Controllers;
use Illuminate\Support\Fluent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use LSNepomuceno\LaravelA1PdfSign\{ManageCert, SealImage, SignaturePdf};
use LSNepomuceno\LaravelA1PdfSign\ValidatePdfSignature;
use Illuminate\Support\Facades\Storage;
//use setasign\Fpdi\Fpdi;
use Carbon\Carbon;
//use SimpleSoftwareIO\QrCode\Facades\QrCode;
use setasign\Fpdi\Tcpdf\Fpdi;
use Illuminate\Support\Str;
class Actionsapi extends Controller
{
 
    public function generatesign(Request $request)
    {
        try {
            $cert = new ManageCert;
            $cert->fromPfx('C:\wamp64\www\signpdfcerdent\storage\app\public\certificados\ezavala.pfx', 'EGZC2021');
        } catch (\Throwable $th) {
            // TODO necessary
            return $th;
        }
        
        // FROM UPLOAD
        // try {
        //     $cert = new ManageCert;
        //     $cert->fromUpload($request->pfxUploadedFile, $request->password);
        //     dd($cert->getCert());
        // } catch (\Throwable $th) {
        //     // TODO necessary
        // }
        
        // Returning signed resource string
        // try {
        //     $pdf = new SignaturePdf('/home/i2zj71i4r01d/public_html/pruebapdf/storage/app/public/certificados/prueba.pdf', $cert, SignaturePdf::MODE_RESOURCE); // Resource mode is default
        //     $resource = $pdf->signature();
        //     return response()-> $resource;
        //     // TODO necessary
        // } catch (\Throwable $th) {
        //     // TODO necessary
        //     return $th;
        // }

        // It is possible to pass a file directly through the upload
        // try {
        //     $pdf = new SignaturePdf($request->file('PDFfile'), $cert, SignaturePdf::MODE_RESOURCE); // Resource mode is default
        //     $resource = $pdf->signature();
        //     // TODO necessary
        // } catch (\Throwable $th) {
        //     // TODO necessary
        // }
        
        // Downloading signed file
        // try {
        //     $pdf = new SignaturePdf('/home/i2zj71i4r01d/public_html/pruebapdf/storage/app/public/certificados/prueba.pdf', $cert, SignaturePdf::MODE_DOWNLOAD);
        //     return $pdf->signature(); // The file will be downloaded
        // } catch (\Throwable $th) {
        //      return $th;
        // }
        
         //$image = SealImage::fromCert($cert);

        // IMAGE STORAGE LOCATION
    //     $imagePath =  'C:\wamp64\www\signpdfcerdent\storage\app\public\certificados\firma.png';
    //    File::put($imagePath, $image);

    //     // Returning signed resource string
    //     $name="edwin";
    //      $location="san idrio";
    //       $reason="prueba";
    //       $contactInfo="43242343";
        try {
            $pdf = new SignaturePdf('C:\wamp64\www\signpdfcerdent\storage\app\public\certificados\20211227.pdf', $cert,SignaturePdf::MODE_RESOURCE);
              $resource = $pdf
            //   ->setImage($imagePath)
            //              ->setFileName('testeo.pdf')
            //              ->setInfo(
            //             $name,
            //              $location,
            //              $reason,
            //              $contactInfo 
            //              ) 
                         ->signature();
                 Storage::disk('public')->put('NUEVO_frima.pdf', $resource);         
          //  return $resource;             
            // TODO necessary
        } catch (\Throwable $th) {
            return  $th;  
        }
        
    }
        public function setImage(
        string $imagePath, // Image path location
        float  $pageX = 155, // X page position
        float  $pageY = 250, // Y page position
        float  $imageW = 0, // The image width, if set to 0, the original or proportional image size will be used
        float  $imageH = 0   // The image height, if set to 0, the original or proportional image size will be used
    ): SignaturePdf{}

    public function test(Request $request)
    {
        //  $results= 'path/to/certificate.pfx';
        // return $results;
        $url  = Storage::disk('public')->getDriver()->getAdapter()->getPathPrefix();
       // $url = Storage::disk('public')->path('/documents/K_001.pdf');
return $url;
    }
     public function validateSign(Request $request)
    {
        try {
           $pdf2=ValidatePdfSignature::from('C:\wamp64\www\signpdfcerdent\storage\app\prueba.pdf');
            return response()->json($pdf2);
        } catch (\Throwable $th) {
           return $th;
        }
    }


    public function process(Request $request)
    {
        // download sample file.
        //Storage::disk('local')->put('test.pdf', file_get_contents('http://www.africau.edu/images/default/sample.pdf'));
 
        $outputFile = Storage::disk('public')->path('prueba_sign.pdf');
        // fill data
        $this->fillPDF(Storage::disk('public')->path('TE_34D.pdf'), $outputFile);
        //output to browser
        return response()->file($outputFile);
    }
 
    public function fillPDF($file, $outputFile)
    {
       
      
      // $imagefile=Storage::disk('local')->path('QR.png'); 
 

        //carga imagen qr
       // $imagefile=Storage::disk('local')->path('QR.png');
        $fpdi = new FPDI;
        $count = $fpdi->setSourceFile($file);
        for ($i=1; $i<=$count; $i++) {       
                $date = Carbon::now()->format('d/m/Y H:i');
                $template   = $fpdi->importPage($i);
                $size       = $fpdi->getTemplateSize($template);
               $fpdi->SetPrintHeader(false);
                $fpdi->SetPrintFooter(false);
                $fpdi->AddPage($size['orientation'], array($size['width'], $size['height']));
                $fpdi->useTemplate($template);
                //'file://'.realpath('C:/objects/dummy_cert.cert');
                $info = array(
                    'Name' => 'TCPDF',
                    'Location' => 'Office',
                    'Reason' => 'Testing TCPDF',
                    'ContactInfo' => 'http://www.tcpdf.org',
                    );
 
                    
               if($i==$count){
                $fpdi-> SetAutoPageBreak(TRUE, 0);
                $style = array(
                    'border' => false,
                    'vpadding' => 'auto',
                    'hpadding' => 'auto',
                    'fgcolor' => array(0,0,0),
                    'bgcolor' => false, //array(255,255,255)
                    'module_width' => 1, // width of a single module in points
                    'module_height' => 1 // height of a single module in points
                );
                    $left = 45;
                    $top = 137;
                    $text=$date;
                    $fpdi->SetFont("helvetica", "", 12);
                    $fpdi->SetTextColor(0,0,0);
                    $fpdi->Text($left,$top,$text);
                    //if($count=$i){
                        $fpdi->write2DBarcode('estodsdk', 'QRCODE,H', 10, 245, 35, 35, $style, 'N');
                        $fpdi->SetFont("helvetica", "",8);
                        $code=Str::random(12);
                        $fpdi->Text(11, 280, 'FIRMADO DIGITALMENTE');
                        $fpdi->Text(11, 283, 'código: '.$code);
                        //$certificate = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix().'certificates\otro.crt';
                        //$certificateKey = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix().'certificates\nuevo.key';
                        $prepend = "file://C://publiCertmarco.pem";
                       $prependkey = "file://C://privateCertmarco.pem";
                      // echo  $prepend;
                    $fpdi->setSignature($prepend, $prependkey, 'A3QmXrVeXDivqhXZ', '', 2, $info,'A');
                    $fpdi->setSignatureAppearance(180, 60, 15, 15);
                       // $fpdi->Image($imagefile,150,230,40,40);    
                 }
                 //$fpdi->setSignature();
               
            
             }
               
           
       // }
          $fpdi->Output($outputFile, 'F');
        return true;
        //return 
    }
}
