<?php
/**
 * Print System Helper Functions
 * WAMP Environment Compatible
 * Handles print operations, device management, and print modes
 */

class PrintHelper {
    private static $conn;
    
    public static function init($connection) {
        self::$conn = $connection;
    }
    
    /**
     * Get print method setting
     */
    public static function getPrintMethod() {
        $result = self::$conn->query("SELECT value FROM settings WHERE code = 'print_method' AND is_active = 1 LIMIT 1");
        if ($result && $row = $result->fetch_assoc()) {
            return $row['value'];
        }
        return 'popup'; // default
    }
    
    /**
     * Get global print mode setting
     */
    public static function getGlobalPrintMode() {
        $result = self::$conn->query("SELECT value FROM settings WHERE code = 'global_print_mode' AND is_active = 1 LIMIT 1");
        if ($result && $row = $result->fetch_assoc()) {
            return $row['value'];
        }
        return 'ask'; // default
    }
    
    /**
     * Get device print mode for specific print type
     */
    public static function getDevicePrintMode($print_type) {
        $result = self::$conn->query("SELECT print_mode FROM print_devices WHERE print_type = '$print_type' AND is_active = 1 AND is_default = 1 LIMIT 1");
        if ($result && $row = $result->fetch_assoc()) {
            return $row['print_mode'];
        }
        return 'auto'; // default
    }
    
    /**
     * Get default device for print type
     */
    public static function getDefaultDevice($print_type) {
        $result = self::$conn->query("SELECT * FROM print_devices WHERE print_type = '$print_type' AND is_active = 1 AND is_default = 1 LIMIT 1");
        if ($result && $row = $result->fetch_assoc()) {
            return $row;
        }
        return null;
    }
    
    /**
     * Get all devices for print type
     */
    public static function getDevicesForType($print_type) {
        $devices = [];
        $result = self::$conn->query("SELECT * FROM print_devices WHERE (print_type = '$print_type' OR print_type = 'all') AND is_active = 1 ORDER BY is_default DESC, name");
        while ($row = $result->fetch_assoc()) {
            $devices[] = $row;
        }
        return $devices;
    }
    
    /**
     * Determine final print mode (device overrides global)
     */
    public static function getFinalPrintMode($print_type) {
        $device_mode = self::getDevicePrintMode($print_type);
        $global_mode = self::getGlobalPrintMode();
        
        // Device mode overrides global mode unless device mode is 'auto'
        return ($device_mode !== 'auto') ? $device_mode : $global_mode;
    }
    
    
    /**
     * Test printer connectivity
     */
    public static function testPrinter($device_id) {
        $result = self::$conn->query("SELECT * FROM print_devices WHERE id = $device_id");
        if (!$result || !$device = $result->fetch_assoc()) {
            return ['success' => false, 'message' => 'Device not found'];
        }
        
        // Test based on connection type
        if ($device['connection_type'] === 'lan') {
            return self::testLANPrinter($device);
        } else {
            return self::testUSBPrinter($device);
        }
    }
    
    /**
     * Test LAN printer connectivity
     */
    private static function testLANPrinter($device) {
        if (empty($device['ip_address'])) {
            return ['success' => false, 'message' => 'IP address not configured'];
        }
        
        // Test network connectivity
        $connection = @fsockopen($device['ip_address'], 9100, $errno, $errstr, 5);
        if ($connection) {
            fclose($connection);
            return ['success' => true, 'message' => 'LAN printer is reachable'];
        } else {
            return ['success' => false, 'message' => "Cannot connect to printer: $errstr"];
        }
    }
    
    /**
     * Test USB printer (browser-based)
     */
    private static function testUSBPrinter($device) {
        // For USB printers, we can only check if the printer name is configured
        if (empty($device['printer_name'])) {
            return ['success' => false, 'message' => 'Printer name not configured'];
        }
        
        return ['success' => true, 'message' => 'USB printer configured (test via browser)'];
    }
    
    
    /**
     * Get system print settings
     */
    public static function getPrintSettings() {
        $settings = [];
        $result = self::$conn->query("SELECT code, value FROM settings WHERE code IN ('print_method', 'global_print_mode', 'auto_detect_printers', 'print_timeout') AND is_active = 1");
        while ($row = $result->fetch_assoc()) {
            $settings[$row['code']] = $row['value'];
        }
        return $settings;
    }
    
    /**
     * Update system print settings
     */
    public static function updatePrintSettings($settings) {
        foreach ($settings as $code => $value) {
            $value_escaped = self::$conn->real_escape_string($value);
            self::$conn->query("UPDATE settings SET value = '$value_escaped' WHERE code = '$code' AND is_active = 1");
        }
        return true;
    }
}

// Initialize with database connection
if (isset($conn)) {
    PrintHelper::init($conn);
}
?>
