<?php
header('Content-Type: application/json');
include '../db.php';

try {
    $printers = [];
    
    // Method 1: Use Windows WMI to get installed printers
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        // Use PowerShell to get printer information
        $command = 'powershell -Command "Get-WmiObject -Class Win32_Printer | Select-Object Name, DriverName, PortName, WorkOffline | ConvertTo-Json"';
        
        $output = shell_exec($command);
        
        if ($output) {
            $printerData = json_decode($output, true);
            
            if (is_array($printerData)) {
                // Handle single printer (not in array)
                if (isset($printerData['Name'])) {
                    $printerData = [$printerData];
                }
                
                foreach ($printerData as $printer) {
                    if (isset($printer['Name']) && !empty($printer['Name'])) {
                        $status = 'available';
                        if (isset($printer['WorkOffline']) && $printer['WorkOffline']) {
                            $status = 'offline';
                        }
                        
                        $printers[] = [
                            'name' => $printer['Name'],
                            'driver' => $printer['DriverName'] ?? 'Unknown',
                            'port' => $printer['PortName'] ?? 'Unknown',
                            'status' => $status
                        ];
                    }
                }
            } else {
                // If JSON decode failed, try to parse the output manually
                $lines = explode("\n", $output);
                foreach ($lines as $line) {
                    if (strpos($line, '"Name":') !== false) {
                        // Extract printer name from JSON-like output
                        if (preg_match('/"Name":\s*"([^"]+)"/', $line, $matches)) {
                            $printers[] = [
                                'name' => $matches[1],
                                'driver' => 'Unknown',
                                'port' => 'Unknown',
                                'status' => 'unknown'
                            ];
                        }
                    }
                }
            }
        }
    }
    
    // Method 2: Fallback - try to get printers from registry (Windows)
    if (empty($printers) && strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $command = 'reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers" /s /f "Printer" 2>nul';
        $output = shell_exec($command);
        
        if ($output) {
            $lines = explode("\n", $output);
            foreach ($lines as $line) {
                if (strpos($line, 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers\\') !== false) {
                    $printerName = trim(str_replace('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers\\', '', $line));
                    if (!empty($printerName) && !in_array($printerName, array_column($printers, 'name'))) {
                        $printers[] = [
                            'name' => $printerName,
                            'driver' => 'Unknown',
                            'port' => 'Unknown',
                            'status' => 'unknown'
                        ];
                    }
                }
            }
        }
    }
    
    // Method 3: Try using wmic command
    if (empty($printers) && strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $command = 'wmic printer get name,drivername,portname /format:csv 2>nul';
        $output = shell_exec($command);
        
        if ($output) {
            $lines = explode("\n", $output);
            $headers = null;
            
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) continue;
                
                $data = str_getcsv($line);
                if ($headers === null) {
                    $headers = $data;
                    continue;
                }
                
                if (count($data) >= 3 && !empty($data[1])) { // data[1] is usually the name
                    $printers[] = [
                        'name' => $data[1],
                        'driver' => $data[2] ?? 'Unknown',
                        'port' => $data[3] ?? 'Unknown',
                        'status' => 'unknown'
                    ];
                }
            }
        }
    }
    
    // Remove duplicates
    $uniquePrinters = [];
    $seenNames = [];
    foreach ($printers as $printer) {
        if (!in_array($printer['name'], $seenNames)) {
            $uniquePrinters[] = $printer;
            $seenNames[] = $printer['name'];
        }
    }
    
    echo json_encode([
        'success' => true,
        'printers' => $uniquePrinters,
        'count' => count($uniquePrinters)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to detect printers: ' . $e->getMessage(),
        'printers' => []
    ]);
}
?>
