<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Kitchen Order Printer
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path
$base_path = null;

// Method 1: Try dirname(__DIR__, 3)
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: If still not found, use absolute path
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

if (file_exists($base_path . '/config/helpers.php')) {
    require_once $base_path . '/config/helpers.php';
}

// Require authentication
require_auth();

// Get sale ID from URL
$sale_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$sale_id) {
    die('Invalid sale ID');
}

// Get sale data
$sale = null;
try {
    $sale = db_fetch_one("
        SELECT 
            s.*,
            u.first_name, u.last_name,
            o.outlet_name, o.outlet_code
        FROM pos_sales s
        JOIN users u ON s.user_id = u.user_id
        JOIN pos_outlets o ON s.outlet_id = o.outlet_id
        WHERE s.sale_id = ?
    ", [$sale_id]);
} catch (Exception $e) {
    error_log("Error fetching sale: " . $e->getMessage());
    die('Error loading sale data');
}

if (!$sale) {
    die('Sale not found');
}

// Get sale items (only food items - you can filter by category if needed)
$items = [];
try {
    $items = db_fetch_all("
        SELECT si.*, p.product_name, p.product_code, c.category_name
        FROM pos_sale_items si
        LEFT JOIN pos_products p ON si.product_id = p.product_id
        LEFT JOIN pos_categories c ON p.category_id = c.category_id
        WHERE si.sale_id = ?
        ORDER BY c.category_name, p.product_name
    ", [$sale_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching sale items: " . $e->getMessage());
}

// Get resort settings
$resort = null;
try {
    $resort = db_fetch_one("SELECT * FROM resort_settings LIMIT 1");
} catch (Exception $e) {
    error_log("Error fetching resort settings: " . $e->getMessage());
}

// Get currency symbol
$currency_symbol = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'RWF';

// Generate order number if not exists
$order_number = 'KIT-' . date('Ymd') . '-' . str_pad($sale_id, 4, '0', STR_PAD_LEFT);

// Group items by category
$items_by_category = [];
foreach ($items as $item) {
    $category = $item['category_name'] ?? 'Other';
    if (!isset($items_by_category[$category])) {
        $items_by_category[$category] = [];
    }
    $items_by_category[$category][] = $item;
}

// Generate HTML for kitchen order with custom footer
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kitchen Order - <?php echo htmlspecialchars($order_number); ?></title>
    <style>
        body {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
            margin: 0;
            padding: 20px;
            width: 80mm; /* Standard thermal printer width */
            max-width: 100%;
        }
        .header {
            text-align: center;
            margin-bottom: 15px;
            border-bottom: 2px dashed #333;
            padding-bottom: 10px;
        }
        .header h1 {
            margin: 0;
            font-size: 18px;
            font-weight: bold;
        }
        .header h2 {
            margin: 5px 0;
            font-size: 16px;
        }
        .header p {
            margin: 3px 0;
        }
        .info-section {
            margin-bottom: 15px;
            border-bottom: 1px dashed #333;
            padding-bottom: 10px;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3px;
        }
        .order-number {
            font-size: 14px;
            font-weight: bold;
            text-align: center;
            margin: 10px 0;
            padding: 5px;
            border: 2px solid #333;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
        }
        .items-table th {
            text-align: left;
            border-bottom: 1px solid #333;
            padding: 5px 0;
        }
        .items-table td {
            padding: 3px 0;
        }
        .items-table .qty {
            text-align: center;
            width: 50px;
        }
        .items-table .item-name {
            padding-left: 5px;
        }
        .category-header {
            font-weight: bold;
            margin-top: 10px;
            padding-top: 5px;
            border-top: 1px dotted #333;
        }
        .special-notes {
            margin-top: 15px;
            padding: 10px;
            border: 1px dashed #333;
            font-style: italic;
        }
        .footer {
            margin-top: 20px;
            text-align: center;
            border-top: 2px dashed #333;
            padding-top: 10px;
            font-size: 11px;
        }
        .footer .company {
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }
        .footer .developed-by {
            color: #666;
            font-size: 9px;
            margin-top: 5px;
            font-style: italic;
        }
        .print-time {
            text-align: center;
            margin-top: 10px;
            font-size: 10px;
            color: #666;
        }
        @media print {
            body {
                padding: 0;
            }
            .no-print {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><?php echo !empty($resort['resort_name']) ? htmlspecialchars($resort['resort_name']) : 'Ruhondo Beach Resort'; ?></h1>
        <h2>ORDER</h2>
    </div>

    <div class="order-number">
        <?php echo htmlspecialchars($order_number); ?>
    </div>

    <div class="info-section">
        <div class="info-row">
            <span><strong>Date:</strong></span>
            <span><?php echo date('Y-m-d H:i', strtotime($sale['sale_time'] ?? 'now')); ?></span>
        </div>
        <div class="info-row">
            <span><strong>Outlet:</strong></span>
            <span><?php echo htmlspecialchars($sale['outlet_name'] ?? ''); ?></span>
        </div>
        <div class="info-row">
            <span><strong>Cashier:</strong></span>
            <span><?php echo htmlspecialchars(($sale['first_name'] ?? '') . ' ' . ($sale['last_name'] ?? '')); ?></span>
        </div>
        <div class="info-row">
            <span><strong>Customer:</strong></span>
            <span><?php echo htmlspecialchars($sale['customer_name'] ?? 'Walk-in'); ?></span>
        </div>
        <?php if (!empty($sale['reservation_id'])): ?>
        <div class="info-row">
            <span><strong>Room:</strong></span>
            <span>Room Charge</span>
        </div>
        <?php endif; ?>
    </div>

    <table class="items-table">
        <thead>
            <tr>
                <th class="qty">Qty</th>
                <th class="item-name">Item</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $current_category = '';
            foreach ($items as $item): 
                $category = $item['category_name'] ?? 'Other';
                if ($category !== $current_category):
                    $current_category = $category;
            ?>
                <tr>
                    <td colspan="2" class="category-header">--- <?php echo strtoupper(htmlspecialchars($category)); ?> ---</td>
                </tr>
            <?php endif; ?>
            <tr>
                <td class="qty"><?php echo $item['quantity']; ?>x</td>
                <td class="item-name"><?php echo htmlspecialchars($item['product_name'] ?? 'Product'); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!--<div class="special-notes">
        <strong>Special Instructions:</strong><br>
        - Please prepare items as ordered<br>
        - Notify server when ready<br>
        - Thank you!
    </div>-->

    <div class="footer">
        <div class="company">Ruhondo Beach Resort HMS</div>
        <div class="developed-by">Developed by JOACHIM'S INNOTECH</div>
        <p style="margin-top: 10px;">Printed: <?php echo date('Y-m-d H:i:s'); ?></p>
    </div>

    <div class="print-time no-print">
        <button onclick="window.print()" class="btn btn-primary">Print Order</button>
        <button onclick="window.close()" class="btn btn-secondary">Close</button>
    </div>

    <script>
        // Auto-print if requested
        <?php if (isset($_GET['print']) && $_GET['print'] == 1): ?>
        window.onload = function() {
            setTimeout(function() {
                window.print();
            }, 500);
        }
        <?php endif; ?>
    </script>
</body>
</html>