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

header('Content-Type: application/json');
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'] !== 'lan') {
        throw new Exception('Device is not a LAN printer');
    }
    
    if (empty($device['ip_address'])) {
        throw new Exception('Device IP address not configured');
    }
    
    // Generate print content
    $print_content = generatePrintContent($print_data, $device);
    
    // Send to LAN printer
    $success = sendToLANPrinter($device['ip_address'], $print_content);
    
    if ($success) {
        echo json_encode([
            'success' => true,
            'message' => 'Print sent to LAN printer successfully'
        ]);
    } else {
        throw new Exception('Failed to send print to LAN printer');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * Generate print content for LAN printer
 */
function generatePrintContent($print_data, $device) {
    // This would generate the actual print content based on print type
    // For now, return a simple text format
    
    $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;
}

/**
 * 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 = "";
    $content .= "================================\n";
    $content .= "        RECEIPT\n";
    $content .= "================================\n";
    $content .= "Date: " . date('Y-m-d H:i:s') . "\n";
    $content .= "Receipt #: " . ($print_data['receipt_number'] ?? 'N/A') . "\n";
    $content .= "--------------------------------\n";
    
    if (isset($print_data['items'])) {
        foreach ($print_data['items'] as $item) {
            $content .= sprintf("%-20s %6.2f\n", $item['name'], $item['total_price'] ?? $item['price'] ?? 0);
        }
    }
    
    $content .= "--------------------------------\n";
    $content .= "Total: " . ($print_data['total'] ?? '0.00') . "\n";
    $content .= "================================\n";
    $content .= "Thank you for your business!\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 = "";
    $content .= "================================\n";
    $content .= "        BARCODE LABEL\n";
    $content .= "================================\n";
    $content .= "Item: " . ($print_data['item_name'] ?? 'N/A') . "\n";
    $content .= "Code: " . ($print_data['barcode'] ?? 'N/A') . "\n";
    $content .= "Price: " . ($print_data['price'] ?? 'N/A') . "\n";
    $content .= "================================\n\n\n";
    
    return $content;
}

/**
 * Send content to LAN printer
 */
function sendToLANPrinter($ip_address, $content) {
    // For WAMP environment, we'll use socket connection
    $port = 9100; // Standard printer port
    
    $socket = @fsockopen($ip_address, $port, $errno, $errstr, 10);
    
    if (!$socket) {
        return false;
    }
    
    // Send content to printer
    fwrite($socket, $content);
    fclose($socket);
    
    return true;
}

/**
 * Generate test content for LAN 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 .= "    ITRPOS 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 .= "ITRPOS Print System\n";
    $content .= "Test completed successfully\n";
    $content .= "\n";
    $content .= "================================\n";
    $content .= "\n\n\n"; // Extra paper feed
    
    return $content;
}
?>
