<?php

namespace App\Services;
use Illuminate\Support\Facades\Log;

class PrinterService
{
    public function getPrinters(): array
    {
        $printers = [];
        $os = strtoupper(substr(PHP_OS, 0, 3));
        
        if ($os === 'WIN') {
            // Windows implementation
            $output = shell_exec('wmic printer get name');
            if ($output != "") {
                $lines = explode(PHP_EOL, trim($output));
                $start = 1; // Skip header on Windows
                for ($i = $start; $i < count($lines); $i++) {
                    // Remove all control characters and non-printable characters, then trim
                    $printerName = trim(preg_replace('/[[:cntrl:]]/', '', $lines[$i]));
                    if (!empty($printerName)) {
                        $printers[$printerName] = $printerName;
                    }
                }
            }
        } elseif ($os === 'DAR' || $os === 'LIN') {
            // macOS and Linux implementation
            $output = shell_exec('lpstat -p 2>/dev/null');
            if ($output !== null) {
                $lines = explode(PHP_EOL, trim($output));
                foreach ($lines as $line) {
                    if (preg_match('/printer\s+(.*?)\s+is/', $line, $matches)) {
                        $printerName = trim($matches[1]);
                        if (!empty($printerName)) {
                            $printers[$printerName] = $printerName;
                        }
                    }
                }
            }
        }

        return $printers;
    }

    public function printImage(string $imagePath, string $printerName, int $copies = 1): bool
    {
        $os = strtoupper(substr(PHP_OS, 0, 3));
        
        if ($os === 'WIN') {
            // Windows implementation
            $magickPath = base_path('bin/imagick/win64/magick.exe');

            if (!file_exists($magickPath)) {
                Log::error('PrinterService: ImageMagick executable not found.', ['path' => $magickPath]);
                return false;
            }

            $success = true;
            for ($i = 0; $i < $copies; $i++) {
                // Ensure imagePath is absolute and properly quoted
                $quotedImagePath = escapeshellarg($imagePath);
                $quotedPrinterName = escapeshellarg("printer:$printerName"); // "printer:printerName" needs to be one argument

                $command = "{$magickPath} {$quotedImagePath} {$quotedPrinterName}";
                
                Log::debug('PrinterService: Executing print command:', ['command' => $command]);
                $output = shell_exec($command);
                
                // Log::debug('PrinterService: Executing print command:', ['command' => $command]);
                $output = shell_exec($command);
                Log::debug('PrinterService: Print command output:', ['output' => $output]);

                // Check for errors. shell_exec returns NULL on command failure.
                if ($output === null) {
                    Log::error('PrinterService: Print command failed.', ['command' => $command, 'output' => $output]);
                    $success = false;
                    break; // Stop if one copy fails
                }
            }

            return $success;
        } elseif ($os === 'DAR' || $os === 'LIN') {
            // macOS and Linux implementation
            if (!file_exists($imagePath)) {
                Log::error('PrinterService: Image file not found.', ['path' => $imagePath]);
                return false;
            }

            // Use the lp command to print the image
            $success = true;
            for ($i = 0; $i < $copies; $i++) {
                $quotedImagePath = escapeshellarg($imagePath);
                $quotedPrinterName = escapeshellarg($printerName);
                
                // For image printing on Linux/macOS, we might need to convert to a printable format first
                // Using lp command directly with the image file
                $command = "lp -d {$quotedPrinterName} {$quotedImagePath} 2>&1";
                
                Log::debug('PrinterService: Executing print command:', ['command' => $command]);
                $output = shell_exec($command);
                Log::debug('PrinterService: Print command output:', ['output' => $output]);

                // Check for errors
                if ($output === null || (strpos($output, 'Error') !== false)) {
                    Log::error('PrinterService: Print command failed.', ['command' => $command, 'output' => $output]);
                    $success = false;
                    break; // Stop if one copy fails
                }
            }

            return $success;
        } else {
            Log::error('PrinterService: Unsupported operating system.');
            return false;
        }
    }
}

