<?php
/**
 * Print to USB Device AJAX Handler
 * WAMP Environment Compatible
 */

// Suppress all output to prevent HTML errors from breaking JSON
ob_start();

// Suppress PHP warnings and errors
error_reporting(0);
ini_set('display_errors', 0);

// Set JSON header
header('Content-Type: application/json');

// Include database connection
include '../db.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid input data');
    }
    
    $device_id = $input['device_id'] ?? null;
    $print_data = $input['print_data'] ?? [];
    
    if (!$device_id) {
        throw new Exception('Device ID is required');
    }
    
    // Get device information
    $result = $conn->query("SELECT * FROM print_devices WHERE id = $device_id");
    if (!$result || !$device = $result->fetch_assoc()) {
        throw new Exception('Device not found');
    }
    
    if ($device['connection_type'] !== 'usb') {
        throw new Exception('Device is not a USB printer');
    }
    
    if (empty($device['printer_name'])) {
        throw new Exception('Printer name not configured');
    }
    
    // Generate print content
    $print_content = generatePrintContent($print_data, $device);
    
    // Send to USB printer using Windows print command
    $success = sendToUSBPrinter($device['printer_name'], $print_content);
    
    if ($success) {
        // Clear any output buffer and send JSON response
        ob_clean();
        echo json_encode([
            'success' => true,
            'message' => 'Print sent to USB printer successfully',
            'debug' => [
                'printer_name' => $device['printer_name'],
                'content_length' => strlen($print_content),
                'content_preview' => substr($print_content, 0, 100) . '...'
            ]
        ]);
    } else {
        throw new Exception('Failed to send print to USB printer');
    }
    
} catch (Exception $e) {
    // Clear any output buffer and send JSON error response
    ob_clean();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * Generate print content for USB printer
 */
function generatePrintContent($print_data, $device) {
    $content = "";
    
    switch ($print_data['type'] ?? 'receipt') {
        case 'receipt':
            $content = generateReceiptContent($print_data);
            break;
        case 'kot':
            $content = generateKOTContent($print_data);
            break;
        case 'barcode':
            $content = generateBarcodeContent($print_data);
            break;
        case 'test':
            $content = generateTestContent($print_data);
            break;
        default:
            $content = "Print content for " . ($print_data['type'] ?? 'unknown') . "\n";
    }
    
    return $content;
}

/**
 * Send content to USB printer using Windows print command
 */
function sendToUSBPrinter($printer_name, $content) {
    // Create a temporary file with the print content
    $temp_file = tempnam(sys_get_temp_dir(), 'itrpos_print_');
    file_put_contents($temp_file, $content);
    
    try {
        // Method 1: Try Windows print command
        $command = "print /D:\"$printer_name\" \"$temp_file\" 2>&1";
        $output = shell_exec($command);
        
        // Log the output for debugging
        error_log("Print command output: " . $output);
        
        // Check if the output indicates success
        if (strpos($output, 'is currently being printed') !== false || 
            strpos($output, 'printed') !== false ||
            empty(trim($output))) {
            
            // Clean up temp file
            unlink($temp_file);
            return true;
        }
        
        // If we get here, the print command failed, but let's try other methods
        error_log("Print command failed, trying PowerShell method");
        
        // Method 2: Try using PowerShell with more control
        $ps_command = "powershell -Command \"Get-Content '$temp_file' | Out-Printer -Name '$printer_name'\" 2>&1";
        $ps_output = shell_exec($ps_command);
        
        error_log("PowerShell print output: " . $ps_output);
        
        // If PowerShell succeeded (no error output), return true
        if (empty(trim($ps_output)) || strpos($ps_output, 'error') === false) {
            // Clean up temp file
            unlink($temp_file);
            return true;
        }
        
        error_log("PowerShell method failed, trying copy method");
        
        // Method 3: Try using copy command to printer port
        // This is a more direct approach for some printers
        $copy_command = "copy \"$temp_file\" \"$printer_name\" 2>&1";
        $copy_output = shell_exec($copy_command);
        
        error_log("Copy command output: " . $copy_output);
        
        // Clean up temp file
        unlink($temp_file);
        
        if (strpos($copy_output, '1 file(s) copied') !== false) {
            return true;
        }
        
        error_log("All print methods failed. Last outputs: Print='$output', PowerShell='$ps_output', Copy='$copy_output'");
        return false;
        
    } catch (Exception $e) {
        // Clean up temp file on error
        if (file_exists($temp_file)) {
            unlink($temp_file);
        }
        error_log("Print error: " . $e->getMessage());
        return false;
    }
}

/**
 * Generate test content for USB printer
 */
function generateTestContent($print_data) {
    $device_id = $print_data['device_id'] ?? 'Unknown';
    $timestamp = date('Y-m-d H:i:s');
    
    $content = "\n";
    $content .= "================================\n";
    $content .= "    ITR POS PRINTER TEST\n";
    $content .= "================================\n";
    $content .= "\n";
    $content .= "Device ID: " . $device_id . "\n";
    $content .= "Test Time: " . $timestamp . "\n";
    $content .= "Status: ✓ Printer Test Successful\n";
    $content .= "\n";
    $content .= "--------------------------------\n";
    $content .= "\n";
    $content .= "If you can see this printout,\n";
    $content .= "your printer is working correctly!\n";
    $content .= "\n";
    $content .= "This test confirms that:\n";
    $content .= "• Printer is connected and accessible\n";
    $content .= "• Printer driver is working properly\n";
    $content .= "• Print system is functioning correctly\n";
    $content .= "\n";
    $content .= "--------------------------------\n";
    $content .= "ITR POS Print System\n";
    $content .= "Test completed successfully\n";
    $content .= "\n";
    $content .= "================================\n";
    $content .= "\n\n\n"; // Extra paper feed
    
    return $content;
}

/**
 * Generate receipt content
 */
function generateReceiptContent($print_data) {
    global $conn;
    
    $sale_id = $print_data['sale_id'] ?? null;
    
    if (!$sale_id) {
        // Fallback to simple receipt
        return generateSimpleReceiptContent($print_data);
    }
    
    // Get sale data from database
    $sale_result = $conn->query("SELECT s.*, dt.table_name, c.phone, c.address, do.delivery_address 
                                 FROM sales s 
                                 LEFT JOIN dinein_tables dt ON s.table_id = dt.id 
                                 LEFT JOIN customers c ON s.customer_id = c.id
                                 LEFT JOIN delivery_orders do ON s.id = do.sale_id
                                 WHERE s.id = $sale_id LIMIT 1");
    
    if (!$sale_result || !$sale = $sale_result->fetch_assoc()) {
        return generateSimpleReceiptContent($print_data);
    }
    
    // Get sale items
    $items_result = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
    $items = [];
    while ($item = $items_result->fetch_assoc()) {
        $items[] = $item;
    }
    
    // Get branch info
    $branch_result = $conn->query("SELECT branch_name, branch_address FROM branch_info LIMIT 1");
    $branch_info = $branch_result ? $branch_result->fetch_assoc() : null;
    
    // Generate receipt content
    $content = "\n";
    $content .= "================================\n";
    $content .= "           RECEIPT\n";
    $content .= "================================\n";
    
    if ($branch_info) {
        $content .= "\n";
        $content .= $branch_info['branch_name'] . "\n";
        $content .= $branch_info['branch_address'] . "\n";
        $content .= "\n";
    }
    
    $content .= "Date: " . date('Y-m-d H:i:s') . "\n";
    $content .= "Receipt #: " . ($sale['invoice_number'] ?? $sale['id']) . "\n";
    $content .= "Customer: " . ($sale['customer_name'] ?? 'Walk-in') . "\n";
    
    if (!empty($sale['order_mode'])) {
        $content .= "Order Mode: " . ucfirst(str_replace('_', ' ', $sale['order_mode'])) . "\n";
        if ($sale['order_mode'] === 'dine_in' && !empty($sale['table_name'])) {
            $content .= "Table: " . $sale['table_name'] . "\n";
        }
    }
    
    $content .= "\n";
    $content .= "--------------------------------\n";
    $content .= "\n";
    
    // Add items
    foreach ($items as $item) {
        $content .= sprintf("%-20s %6.2f\n", $item['item_name'], $item['total_price']);
        if (!empty($item['remarks'])) {
            $content .= "  Note: " . $item['remarks'] . "\n";
        }
    }
    
    $content .= "\n";
    $content .= "--------------------------------\n";
    $subtotal = ($sale['total_amount'] ?? 0) - ($sale['tax_amount'] ?? 0);
    $content .= "Subtotal: " . number_format($subtotal, 2) . "\n";
    
    if (!empty($sale['tax_amount']) && $sale['tax_amount'] > 0) {
        $content .= "Tax: " . number_format($sale['tax_amount'], 2) . "\n";
    }
    
    $content .= "Total: " . number_format($sale['total_amount'] ?? 0, 2) . "\n";
    $content .= "Payment: " . ucfirst($sale['payment_method'] ?? 'Cash') . "\n";
    
    $content .= "\n";
    $content .= "Thank you for your business!\n";
    $content .= "\n";
    $content .= "================================\n";
    $content .= "\n\n\n";
    
    return $content;
}

/**
 * Generate simple receipt content (fallback)
 */
function generateSimpleReceiptContent($print_data) {
    $content = "\n";
    $content .= "================================\n";
    $content .= "           RECEIPT\n";
    $content .= "================================\n";
    $content .= "\n";
    $content .= "Date: " . date('Y-m-d H:i:s') . "\n";
    $content .= "Receipt #: " . ($print_data['receipt_number'] ?? 'N/A') . "\n";
    $content .= "\n";
    $content .= "--------------------------------\n";
    $content .= "\n";
    $content .= "Total: $" . number_format($print_data['total'] ?? 0, 2) . "\n";
    $content .= "\n";
    $content .= "Thank you for your business!\n";
    $content .= "\n";
    $content .= "================================\n";
    $content .= "\n\n\n";
    
    return $content;
}

/**
 * Generate KOT content
 */
function generateKOTContent($print_data) {
    global $conn;
    
    $hold_id = $print_data['hold_id'] ?? null;
    $new_item_ids = $print_data['new_items'] ?? [];
    
    if (!$hold_id) {
        return generateSimpleKOTContent($print_data);
    }
    
    // Get order data from database
    $order_result = $conn->query("SELECT * FROM hold_orders WHERE id = $hold_id LIMIT 1");
    if (!$order_result || !$order = $order_result->fetch_assoc()) {
        return generateSimpleKOTContent($print_data);
    }
    
    // Get items for this order
    $items_query = "SELECT * FROM hold_items WHERE hold_id = $hold_id";
    if (!empty($new_item_ids)) {
        $ids_list = implode(',', array_map('intval', $new_item_ids));
        $items_query .= " AND item_id IN ($ids_list)";
    }
    $items_result = $conn->query($items_query);
    
    // Get table info if available
    $table_name = '';
    if (!empty($order['table_id'])) {
        $table_result = $conn->query("SELECT table_name FROM dinein_tables WHERE id = " . intval($order['table_id']));
        if ($table_result && $table_row = $table_result->fetch_assoc()) {
            $table_name = $table_row['table_name'];
        }
    }
    
    // Get order taker info if available
    $order_taker_name = '';
    if (!empty($order['order_taker_id'])) {
        $order_taker_result = $conn->query("SELECT name FROM order_takers WHERE id = " . intval($order['order_taker_id']));
        if ($order_taker_result && $order_taker_row = $order_taker_result->fetch_assoc()) {
            $order_taker_name = $order_taker_row['name'];
        }
    }
    
    // Generate KOT content
    $content = "\n";
    $content .= "================================\n";
    $content .= "    KITCHEN ORDER TICKET\n";
    $content .= "================================\n";
    $content .= "\n";
    $content .= "Order #: " . $order['id'] . "\n";
    $content .= "Customer: " . ($order['customer_name'] ?? 'Walk-in') . "\n";
    $content .= "Time: " . date('H:i', strtotime($order['created_at'])) . "\n";
    
    if (!empty($order['order_mode'])) {
        $content .= "Mode: " . strtoupper($order['order_mode']) . "\n";
    }
    
    if (!empty($table_name)) {
        $content .= "Table: " . $table_name . "\n";
    }
    
    if (!empty($order_taker_name)) {
        $content .= "Order Taker: " . $order_taker_name . "\n";
    }
    
    $content .= "\n";
    $content .= "--------------------------------\n";
    $content .= "\n";
    
    // Add items
    if ($items_result && $items_result->num_rows > 0) {
        while ($item = $items_result->fetch_assoc()) {
            $content .= $item['item_name'] . "\n";
            
            // Add modifiers if available
            if (!empty($item['modifiers'])) {
                $modifiers = json_decode($item['modifiers'], true);
                if (is_array($modifiers) && !empty($modifiers)) {
                    $modifier_names = array_map(function($m) { return $m['name'] ?? ''; }, $modifiers);
                    $modifier_text = implode(', ', array_filter($modifier_names));
                    if (!empty($modifier_text)) {
                        $content .= "  (" . $modifier_text . ")\n";
                    }
                }
            }
            
            // Add remarks if available
            if (!empty($item['remarks'])) {
                $content .= "  💬 " . $item['remarks'] . "\n";
            }
            
            $content .= "  x " . intval($item['quantity']) . "\n";
            $content .= "\n";
        }
    } else {
        $content .= "No items found.\n";
    }
    
    $content .= "--------------------------------\n";
    $content .= "--- END OF KOT ---\n";
    $content .= "\n\n\n";
    
    return $content;
}

/**
 * Generate simple KOT content (fallback)
 */
function generateSimpleKOTContent($print_data) {
    $content = "\n";
    $content .= "================================\n";
    $content .= "        KITCHEN ORDER\n";
    $content .= "================================\n";
    $content .= "\n";
    $content .= "Order #: " . ($print_data['order_number'] ?? 'N/A') . "\n";
    $content .= "Time: " . date('H:i:s') . "\n";
    $content .= "\n";
    $content .= "--------------------------------\n";
    $content .= "\n";
    $content .= "Items:\n";
    if (isset($print_data['items']) && is_array($print_data['items'])) {
        foreach ($print_data['items'] as $item) {
            $content .= "• " . ($item['name'] ?? 'Item') . "\n";
        }
    }
    $content .= "\n";
    $content .= "================================\n";
    $content .= "\n\n\n";
    
    return $content;
}

/**
 * Generate barcode content
 */
function generateBarcodeContent($print_data) {
    $content = "\n";
    $content .= "================================\n";
    $content .= "         BARCODE LABEL\n";
    $content .= "================================\n";
    $content .= "\n";
    $content .= "Item: " . ($print_data['item_name'] ?? 'N/A') . "\n";
    $content .= "Code: " . ($print_data['barcode'] ?? 'N/A') . "\n";
    $content .= "Price: $" . number_format($print_data['price'] ?? 0, 2) . "\n";
    $content .= "\n";
    $content .= "================================\n";
    $content .= "\n\n\n";
    
    return $content;
}

// Ensure no extra output
ob_end_flush();
?>
