<?php
/**
 * Generate Print Content 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');
    }
    
    $print_type = $input['type'] ?? 'receipt';
    $print_data = $input;
    
    // Generate HTML content for browser printing
    $html_content = generateHTMLContent($print_type, $print_data);
    
    echo json_encode([
        'success' => true,
        'content' => $html_content
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * Generate HTML content for browser printing
 */
function generateHTMLContent($print_type, $print_data) {
    $html = '<!DOCTYPE html>
<html>
<head>
    <title>Print ' . ucfirst($print_type) . '</title>
    <style>
        body { font-family: Arial, sans-serif; font-size: 12px; margin: 0; padding: 10px; }
        .receipt { max-width: 300px; margin: 0 auto; }
        .header { text-align: center; border-bottom: 1px solid #000; padding-bottom: 10px; margin-bottom: 10px; }
        .item { display: flex; justify-content: space-between; margin: 5px 0; }
        .total { border-top: 1px solid #000; padding-top: 10px; margin-top: 10px; font-weight: bold; }
        .footer { text-align: center; margin-top: 20px; font-size: 10px; }
        @media print { body { margin: 0; } }
    </style>
</head>
<body>';
    
    switch ($print_type) {
        case 'receipt':
            $html .= generateReceiptHTML($print_data);
            break;
        case 'kot':
            $html .= generateKOTHTML($print_data);
            break;
        case 'barcode':
            $html .= generateBarcodeHTML($print_data);
            break;
        case 'test':
            $html .= generateTestHTML($print_data);
            break;
        default:
            $html .= '<div class="receipt"><h3>Print Content</h3><p>Content not available</p></div>';
    }
    
    $html .= '
    <script>
        window.onload = function() {
            window.print();
            setTimeout(() => window.close(), 1000);
        };
    </script>
</body>
</html>';
    
    return $html;
}

/**
 * Generate receipt HTML
 */
function generateReceiptHTML($print_data) {
    $html = '<div class="receipt">
        <div class="header">
            <h3>RECEIPT</h3>
            <p>Date: ' . date('Y-m-d H:i:s') . '</p>
            <p>Receipt #: ' . ($print_data['receipt_number'] ?? 'N/A') . '</p>
        </div>';
    
    if (isset($print_data['items'])) {
        foreach ($print_data['items'] as $item) {
            $html .= '<div class="item">
                <span>' . htmlspecialchars($item['name']) . '</span>
                <span>' . number_format($item['price'], 2) . '</span>
            </div>';
        }
    }
    
    $html .= '<div class="total">
        <div class="item">
            <span>Total:</span>
            <span>' . number_format($print_data['total'] ?? 0, 2) . '</span>
        </div>
    </div>
    <div class="footer">
        <p>Thank you for your business!</p>
    </div>
</div>';
    
    return $html;
}

/**
 * Generate KOT HTML
 */
function generateKOTHTML($print_data) {
    $html = '<div class="receipt">
        <div class="header">
            <h3>KITCHEN ORDER TICKET</h3>
            <p>Order #: ' . ($print_data['order_number'] ?? 'N/A') . '</p>
            <p>Table: ' . ($print_data['table'] ?? 'N/A') . '</p>
            <p>Time: ' . date('H:i:s') . '</p>
        </div>';
    
    if (isset($print_data['items'])) {
        foreach ($print_data['items'] as $item) {
            $html .= '<div class="item">
                <span>' . htmlspecialchars($item['name']) . ' x' . $item['quantity'] . '</span>
            </div>';
            if (!empty($item['remarks'])) {
                $html .= '<div style="margin-left: 10px; font-style: italic;">Note: ' . htmlspecialchars($item['remarks']) . '</div>';
            }
        }
    }
    
    $html .= '<div class="footer">
        <p>END OF KOT</p>
    </div>
</div>';
    
    return $html;
}

/**
 * Generate barcode HTML
 */
function generateBarcodeHTML($print_data) {
    $html = '<div class="receipt">
        <div class="header">
            <h3>BARCODE LABEL</h3>
        </div>
        <div class="item">
            <span>Item:</span>
            <span>' . htmlspecialchars($print_data['item_name'] ?? 'N/A') . '</span>
        </div>
        <div class="item">
            <span>Code:</span>
            <span>' . htmlspecialchars($print_data['barcode'] ?? 'N/A') . '</span>
        </div>
        <div class="item">
            <span>Price:</span>
            <span>' . number_format($print_data['price'] ?? 0, 2) . '</span>
        </div>
    </div>';
    
    return $html;
}

/**
 * Generate test print HTML
 */
function generateTestHTML($print_data) {
    $device_id = $print_data['device_id'] ?? 'Unknown';
    $timestamp = date('Y-m-d H:i:s');
    
    $html = '<div class="receipt">
        <div class="header">
            <h2>ITR POS Printer Test</h2>
        </div>
        <div style="text-align: center; margin: 20px 0;">
            <div class="item">
                <span><strong>Device ID:</strong></span>
                <span>' . htmlspecialchars($device_id) . '</span>
            </div>
            <div class="item">
                <span><strong>Test Time:</strong></span>
                <span>' . $timestamp . '</span>
            </div>
            <div class="item">
                <span><strong>Status:</strong></span>
                <span style="color: green;">✓ Printer Test Successful</span>
            </div>
        </div>
        <hr style="border: 1px solid #000; margin: 20px 0;">
        <div style="text-align: center; margin: 20px 0;">
            <p><strong>If you can see this printout, your printer is working correctly!</strong></p>
            <p>This test confirms that:</p>
            <ul style="text-align: left; display: inline-block;">
                <li>Printer is connected and accessible</li>
                <li>Printer driver is working properly</li>
                <li>Print system is functioning correctly</li>
            </ul>
        </div>
        <div class="footer">
            <p>ITR POS Print System</p>
            <p>Test completed successfully</p>
        </div>
    </div>';
    
    return $html;
}
?>
