<?php

namespace App\Custom;

use App\Custom\AlphaPDF;

use Illuminate\Support\Facades\Session;
class MarkerPDF {

	private static function addWatermark($x, $y, $watermarkText, $angle, $pdf)
	{
		$angle = $angle * M_PI / 180;
		$c = cos($angle);
		$s = sin($angle);
		$cx = $x * 1;
		$cy = (300 - $y) * 1;
		$pdf->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm', $c, $s, - $s, $c, $cx, $cy, - $cx, - $cy));
		$pdf->Text($x, $y, $watermarkText);
		$pdf->_out('Q');
	}

	public static function marcarPdf(string $inputPdf, string $outputPdf){
		$pdf = new AlphaPDF();
		$pageCount = $pdf->setSourceFile($inputPdf); // Replace with your input PDF

		for ($i = 1; $i <= $pageCount; $i++) {
			$templateId = $pdf->importPage($i);
			$size = $pdf->getTemplateSize($templateId);
			$pageWidth = $size['width'];
			$pageHeight = $size['height'];
			$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
			$pdf->useTemplate($templateId);
			if ( isset(Session::get('usuario')->first_name) && isset(Session::get('usuario')->last_name) ){
				$name = Session::get('usuario')->first_name.' '.Session::get('usuario')->last_name;
				// Convertir a ISO-8859-1 para evitar problemas con caracteres especiales
				$pdfName = mb_convert_encoding($name, 'ISO-8859-1', 'UTF-8');
			} else {
				$name = Session::get('usuario')->username;
				// Convertir a ISO-8859-1 para evitar problemas con caracteres especiales
				$pdfName = mb_convert_encoding($name, 'ISO-8859-1', 'UTF-8');
			}
			
			$fecha = new \DateTime();
			$fecha = $fecha->format('Y-m-d H:i');
			// Add text watermark
			$pdf->SetAlpha(0.5);
			$pdf->SetTextColor(135, 135, 135); // Light gray color

			$start_x = -50;
			$start_y = -20;
			$x_spacing = 70; // Horizontal spacing between watermarks
			$y_spacing = 50; // Vertical spacing between lines of watermarks
			$num_watermarks_per_line = ceil($pageWidth / $x_spacing) + 2;
			$num_lines = ceil($pageHeight / $y_spacing) + 2;
			
			for ($line = 0; $line < $num_lines*2; $line++) {
				for ($wm_count = 0; $wm_count < $num_watermarks_per_line*2; $wm_count++) {
					$x = $start_x + ($wm_count * $x_spacing);
					$y = $start_y + ($line * $y_spacing);
					$pdf->SetFont('Arial', 'B', 24);
					self::addWatermark($x,$y,$pdfName,45,$pdf);
					$pdf->SetFont('Arial', 'B', 12);
					self::addWatermark($x+30,$y+30,$fecha,45,$pdf);
					// Optional: Reset rotation
					// $pdf->_rotate(0);
				}
			}

			/* for($i=0;$i <= $size['width'];$i+=10){
				for($j=0;$j <= $size['height'];$j+=50){
					$this->addWatermark($i,$j,$name,45,$pdf);
					$this->addWatermark($i,$j,$fecha,45,$pdf);
				}
			} */
		}
		//Fuerzo borrado en caso de que exista
		if(file_exists($outputPdf)){
			unlink($outputPdf);
		}
		// 'F' to save to filesystem
		// 'D' to force download
		$pdf->Output($outputPdf, 'F');
	}
}