<?php
require_once __DIR__ . '/vendor/autoload.php';

use setasign\Fpdi\Tcpdf\Fpdi;

class PdfController extends Fpdi
{
    private $currentTemplateId;
    private $pageSize;

    /**
     * Load a PDF page for modification
     * @param string $filePath - Path to source PDF
     * @param int $pageNumber - Page number to modify (default=1)
     */
    public function loadPage(string $filePath, int $pageNumber = 1)
    {
        $this->setSourceFile($filePath);
        $this->currentTemplateId = $this->importPage($pageNumber);
        $this->pageSize = $this->getTemplateSize($this->currentTemplateId);

        $orientation = ($this->pageSize['width'] > $this->pageSize['height']) ? 'L' : 'P';
        $this->AddPage($orientation, [$this->pageSize['width'], $this->pageSize['height']]);
        $this->useTemplate($this->currentTemplateId);
    }

    /**
     * Add text at specified position
     * @param float $x - X position in mm
     * @param float $y - Y position in mm
     * @param string $text - Text content
     * @param array $options - Styling options
     */
    public function addText(
        float $x,
        float $y,
        string $text,
        array $options = []
    ) {
        // Default options
        $defaults = [
            'font' => 'helvetica',
            'style' => '',
            'size' => 5,
            'color' => [0, 0, 0], // Black
            'align' => 'L', // L/C/R
            'width' => 0, // Auto width
            'height' => 5,
            'maxwidth' => 0,
            'rotation' => 0
        ];

        $config = array_merge($defaults, $options);

        // Apply styling
        $this->SetFont($config['font'], $config['style'], $config['size']);
        $this->SetTextColor($config['color'][0], $config['color'][1], $config['color'][2]);

        // Handle rotation
        if ($config['rotation'] != 0) {
            $this->StartTransform();
            $this->Rotate($config['rotation'], $x, $y);
        }

        // Position and add text
        $this->SetXY($x, $y);

        // Use MultiCell if maxwidth is specified
        if ($config['maxwidth'] > 0) {
            $this->MultiCell(
                $config['maxwidth'], // Width of the cell
                $config['height'],   // Line height
                $text,               // Text content
                0,                   // Border (none)
                $config['align']     // Alignment
            );
        } else {
            $this->Cell(
                $config['width'],
                $config['height'],
                $text,
                0,
                1,
                $config['align']
            );
        }
        if ($config['rotation'] != 0) {
            $this->StopTransform();
        }
    }

    /**
     * Add image at specified position
     * @param float $x - X position in mm
     * @param float $y - Y position in mm
     * @param string $imagePath - Path to image file
     * @param array $options - Sizing options
     */
    public function addImage(
        float $x,
        float $y,
        string $imagePath,
        array $options = []
    ) {
        $defaults = [
            'width' => 50,
            'height' => 0, // Auto maintain aspect
            'type' => '', // Image type (optional)
            'link' => ''  // URL link
        ];

        $config = array_merge($defaults, $options);
        $this->Image($imagePath, $x, $y, $config['width'], $config['height'], $config['type'], $config['link']);
    }

    /**
     * Draw rectangle at specified position
     * @param float $x - X position in mm
     * @param float $y - Y position in mm
     * @param float $width - Rectangle width
     * @param float $height - Rectangle height
     * @param array $options - Styling options
     */
    public function addRectangle(
        float $x,
        float $y,
        float $width,
        float $height,
        array $options = []
    ) {
        $defaults = [
            'color' => [0, 0, 0], // Border color
            'fill' => false,
            'fillColor' => [255, 255, 255] // Fill color
        ];

        $config = array_merge($defaults, $options);

        // Set colors
        $this->SetDrawColor($config['color'][0], $config['color'][1], $config['color'][2]);

        if ($config['fill']) {
            $this->SetFillColor($config['fillColor'][0], $config['fillColor'][1], $config['fillColor'][2]);
        }

        // Draw rectangle
        $this->Rect($x, $y, $width, $height, $config['fill'] ? 'DF' : 'D');
    }

    public function addQrCode(
        float $x,
        float $y,
        string $data,  // Data to encode in QR code
        array $options = []
    ) {
        // Default options
        $defaults = [
            'size' => 8.3,           // Size in mm
            'color' => [0, 0, 0],   // Foreground color (RGB)
            'bgcolor' => [255, 255, 255], // Background color
            'eclevel' => 'M',        // Error correction level: L, M, Q, H
            'align' => 'L',          // Alignment: L, C, R
        ];

        $config = array_merge($defaults, $options);


        // Set colors
        $fgColor = $this->convertColor($config['color']);
        $bgColor = $this->convertColor($config['bgcolor']);

        // Style array for QR code
        $style = [
            'border' => 0,
            'vpadding' => 0,
            'hpadding' => 0,
            'fgcolor' => $fgColor,
            'bgcolor' => $bgColor,
            'module_width' => 1,     // Size of single module in points
            'module_height' => 1
        ];

        // Convert mm to points (1 mm = 2.83465 points)
        $sizePoints = $config['size'] * 2.83465;

        // Write QR code
        $this->write2DBarcode(
            $data,              // Data to encode
            'QRCODE',           // Barcode type
            $x,              // X position (mm)
            $y,                 // Y position (mm)
            $sizePoints,        // Width (points)
            $sizePoints,        // Height (points)
            $style,             // Style array
            'N'                 // No text below QR code
        );
    }

    /**
     * Convert RGB array to TCPDF color format
     */
    private function convertColor(array $rgb): array
    {
        return [
            'r' => $rgb[0],
            'g' => $rgb[1],
            'b' => $rgb[2]
        ];
    }

    /**
     * Save modified PDF
     * @param string $outputPath - Output file path
     * @param string $mode - Output mode (I=inline, D=download, F=file)
     */
    public function savePdf(string $outputPath, bool $preview = true)
    {
        if (!$preview) {
            // Force download in browser
            $this->Output($outputPath, 'D');
        } else {
            // Output inline in browser
            $this->Output($outputPath, 'I');
        }
    }
}
