<?php
session_start();
include 'db.php';
include 'includes/payment_methods.php';
include 'includes/print_helpers.php';

// Check if this is an AJAX request for print data
if (isset($_GET['ajax']) && $_GET['ajax'] === '1') {
    header('Content-Type: application/json');
    
    $sale_id = intval($_GET['sale_id'] ?? 0);
    if (!$sale_id) {
        echo json_encode(['success' => false, 'message' => 'Sale ID required']);
        exit;
    }
    
    // Load sale data
    $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()) {
        echo json_encode(['success' => false, 'message' => 'Sale not found']);
        exit;
    }
    
    // Load sale items
    $items = [];
    $items_result = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
    while ($item = $items_result->fetch_assoc()) {
        $items[] = $item;
    }
    
    // Load branch info
    $branch_info = null;
    $branch_result = $conn->query("SELECT * FROM branch_info LIMIT 1");
    if ($branch_result && $branch_result->num_rows > 0) {
        $branch_info = $branch_result->fetch_assoc();
    }
    
    // Prepare print data
    $print_data = [
        'type' => 'receipt',
        'sale_id' => $sale_id,
        'receipt_number' => $sale['receipt_number'] ?? $sale_id,
        'sale' => $sale,
        'items' => $items,
        'branch_info' => $branch_info,
        'total' => $sale['total_amount'],
        'tax' => $sale['tax_amount'],
        'discount' => $sale['discount_amount'],
        'payment_method' => $sale['payment_method'],
        'created_at' => $sale['created_at']
    ];
    
    echo json_encode(['success' => true, 'print_data' => $print_data]);
    exit;
}

// Original receipt display code (for backward compatibility)
$last_sale = null;
$last_items = [];
$fbr_enabled = false;
$branch_info = null;

$receipt_font_size = 16; // default
$result = $conn->query("SELECT value FROM settings WHERE code = 'receipt_font_size' AND is_active = 1 LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $receipt_font_size = intval($row['value']);
}

// Load FBR config
$fbr_result = $conn->query("SELECT is_enabled FROM fbr_config LIMIT 1");
if ($fbr_result && $fbr_row = $fbr_result->fetch_assoc()) {
    $fbr_enabled = intval($fbr_row['is_enabled']) === 1;
}

// Load branch info
$branch_result = $conn->query("SELECT * FROM branch_info LIMIT 1");
if ($branch_result && $branch_result->num_rows > 0) {
    $branch_info = $branch_result->fetch_assoc();
}

// Load sale + items
if (!empty($_GET['sale_id'])) {
    $sale_id = intval($_GET['sale_id']);
    $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_result->num_rows > 0) {
        $last_sale = $sale_result->fetch_assoc();
    }

    $items_result = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
    $sale_remarks = []; // Array to collect all remarks from sale items
    while ($item = $items_result->fetch_assoc()) {
        $last_items[] = $item;
        // Collect remarks if they exist
        if (!empty($item['remarks'])) {
            $sale_remarks[] = $item['remarks'];
        }
    }
}

// Load print settings
$print_customer_name = true; // default
$print_customer_number = true; // default  
$print_customer_address = true; // default
$print_datetime = true; // default
$print_remarks = true; // default

// Load dealer branding setting
$dealer_branding = 'IT Resources | 📞 0311-391-7777'; // default
$dealer_result = $conn->query("SELECT value FROM settings WHERE code = 'dealer_branding' AND is_active = 1 LIMIT 1");
if ($dealer_result && $dealer_row = $dealer_result->fetch_assoc()) {
    $dealer_branding = $dealer_row['value'];
}

$result = $conn->query("SELECT code, value FROM settings WHERE code IN ('print_cus_name', 'print_cus_number', 'print_cus_address', 'print_datetime', 'print_remarks') AND is_active = 1");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        switch ($row['code']) {
            case 'print_cus_name':
                $print_customer_name = $row['value'] === '1';
                break;
            case 'print_cus_number':
                $print_customer_number = $row['value'] === '1';
                break;
            case 'print_cus_address':
                $print_customer_address = $row['value'] === '1';
                break;
            case 'print_datetime':
                $print_datetime = $row['value'] === '1';
                break;
            case 'print_remarks':
                $print_remarks = $row['value'] === '1';
                break;
        }
    }
}

$receipt_logo_width = 100; // default
$result = $conn->query("SELECT value FROM settings WHERE code = 'receipt_logo_width' AND is_active = 1 LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $receipt_logo_width = intval($row['value']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Receipt</title>
    <style>
body {
    font-family: Arial, sans-serif;
    font-size: <?= $receipt_font_size ?>px;
    margin: 0;
    padding: 0;
    background: #fff;
}

.receipt-wrapper {
    max-width: 700px;
    margin: auto;
    padding: 15px;
    border: 0.5px solid #444;
    box-sizing: border-box;
}

h6, p {
    margin: 0;
    padding: 0;
}

.center {
    text-align: center;
}

.logo {
    max-width: <?= $receipt_logo_width ?>px;
    height: auto;
    display: block;
    margin: 0 auto 10px;
}

.line {
    border-top: 1px solid #000;
    margin: 10px 0;
}

table {
    width: 100%;
    border-collapse: collapse;
}

table td {
    padding: 2px 0;
    border: none;
}

.text-right {
    text-align: right;
}

.text-left {
    text-align: left;
}

.bold {
    font-weight: bold;
}

.large {
    font-size: 1.2em;
}

@media print {
    body {
        margin: 0;
        padding: 0;
    }
    
    .receipt-wrapper {
        border: none;
        max-width: none;
        padding: 0;
    }
    
    .no-print {
        display: none !important;
    }
}

.print-controls {
    position: fixed;
    top: 10px;
    right: 10px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.9);
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.print-controls button {
    margin: 2px;
    padding: 5px 10px;
    border: 1px solid #ccc;
    background: #fff;
    cursor: pointer;
    border-radius: 3px;
}

.print-controls button:hover {
    background: #f0f0f0;
}
    </style>
</head>
<body>

<?php if ($last_sale): ?>
    <div class="print-controls no-print">
        <button onclick="handleEnhancedPrint()">🖨️ Enhanced Print</button>
        <button onclick="window.print()">🖨️ Browser Print</button>
        <button onclick="window.close()">❌ Close</button>
    </div>

    <div class="receipt-wrapper">
        <!-- Branch Logo -->
        <?php if ($branch_info && !empty($branch_info['logo_path']) && file_exists($branch_info['logo_path'])): ?>
            <img src="<?= htmlspecialchars($branch_info['logo_path']) ?>" alt="Branch Logo" class="logo">
        <?php endif; ?>

        <!-- Branch Name -->
        <h6 class="center bold large"><?= htmlspecialchars($branch_info['store_name'] ?? 'ITR POS') ?></h6>
        
        <!-- Branch Address -->
        <?php if ($branch_info && !empty($branch_info['address'])): ?>
            <p class="center"><?= htmlspecialchars($branch_info['address']) ?></p>
        <?php endif; ?>
        
        <!-- Branch Phone -->
        <?php if ($branch_info && !empty($branch_info['phone'])): ?>
            <p class="center">📞 <?= htmlspecialchars($branch_info['phone']) ?></p>
        <?php endif; ?>

        <div class="line"></div>

        <!-- Receipt Header -->
        <h6 class="center bold">RECEIPT</h6>
        
        <!-- Receipt Number -->
        <p class="center">Receipt #: <?= htmlspecialchars($last_sale['receipt_number'] ?? $last_sale['id']) ?></p>
        
        <!-- Date and Time -->
        <?php if ($print_datetime): ?>
            <p class="center">Date: <?= date('Y-m-d H:i:s', strtotime($last_sale['created_at'])) ?></p>
        <?php endif; ?>

        <div class="line"></div>

        <!-- Customer Information -->
        <?php if ($print_customer_name && !empty($last_sale['customer_name'])): ?>
            <p><strong>Customer:</strong> <?= htmlspecialchars($last_sale['customer_name']) ?></p>
        <?php endif; ?>
        
        <?php if ($print_customer_number && !empty($last_sale['phone'])): ?>
            <p><strong>Phone:</strong> <?= htmlspecialchars($last_sale['phone']) ?></p>
        <?php endif; ?>
        
        <?php if ($print_customer_address && !empty($last_sale['address'])): ?>
            <p><strong>Address:</strong> <?= htmlspecialchars($last_sale['address']) ?></p>
        <?php endif; ?>

        <!-- Table Information -->
        <?php if (!empty($last_sale['table_name'])): ?>
            <p><strong>Table:</strong> <?= htmlspecialchars($last_sale['table_name']) ?></p>
        <?php endif; ?>

        <div class="line"></div>

        <!-- Items -->
        <table>
            <thead>
                <tr>
                    <th class="text-left">Item</th>
                    <th class="text-right">Qty</th>
                    <th class="text-right">Price</th>
                    <th class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($last_items as $item): ?>
                    <tr>
                        <td class="text-left">
                            <?= htmlspecialchars($item['item_name']) ?>
                            <?php if ($print_remarks && !empty($item['remarks'])): ?>
                                <br><small style="color: #666; font-style: italic;">Note: <?= htmlspecialchars($item['remarks']) ?></small>
                            <?php endif; ?>
                        </td>
                        <td class="text-right"><?= intval($item['quantity']) ?></td>
                        <td class="text-right"><?= number_format($item['unit_price'], 2) ?></td>
                        <td class="text-right"><?= number_format($item['total_price'], 2) ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="line"></div>

        <!-- Totals -->
        <table>
            <tr>
                <td class="text-left">Subtotal:</td>
                <td class="text-right"><?= number_format($last_sale['subtotal'], 2) ?></td>
            </tr>
            <?php if ($last_sale['discount_amount'] > 0): ?>
                <tr>
                    <td class="text-left">Discount:</td>
                    <td class="text-right">-<?= number_format($last_sale['discount_amount'], 2) ?></td>
                </tr>
            <?php endif; ?>
            <?php if ($last_sale['tax_amount'] > 0): ?>
                <tr>
                    <td class="text-left">Tax:</td>
                    <td class="text-right"><?= number_format($last_sale['tax_amount'], 2) ?></td>
                </tr>
            <?php endif; ?>
            <tr class="bold large">
                <td class="text-left">Total:</td>
                <td class="text-right"><?= number_format($last_sale['total_amount'], 2) ?></td>
            </tr>
        </table>

        <div class="line"></div>

        <!-- Payment Method -->
        <p class="center"><strong>Payment Method:</strong> <?= strtoupper($last_sale['payment_method']) ?></p>

        <!-- Thank You Message -->
        <p class="center">Thanks for your business!</p>

        <!-- Dealer Branding -->
        <div style="margin-top: 10px; font-size: 11px; text-align: center; color: #666; border-top: 1px solid #eee; padding-top: 8px;">
            <p style="margin: 0;"><strong>ITR POS by:</strong> <?= htmlspecialchars($dealer_branding) ?></p>
        </div>
    </div>

    <script src="assets/js/print_system.js"></script>
    <script>
        // Enhanced print function
        async function handleEnhancedPrint() {
            try {
                const saleId = <?= $last_sale['id'] ?>;
                
                // Get print data
                const response = await fetch(`print_receipt_enhanced.php?ajax=1&sale_id=${saleId}`);
                const data = await response.json();
                
                if (!data.success) {
                    throw new Error(data.message);
                }
                
                // Handle print using new print system
                const result = await window.printSystem.handlePrint('receipt', data.print_data);
                
                if (result.success) {
                    Swal.fire({
                        title: 'Print Sent!',
                        text: result.message,
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    });
                } else {
                    Swal.fire({
                        title: 'Print Failed',
                        text: result.message,
                        icon: 'error'
                    });
                }
                
            } catch (error) {
                console.error('Enhanced print failed:', error);
                Swal.fire({
                    title: 'Print Error',
                    text: error.message,
                    icon: 'error'
                });
            }
        }

        // Auto-print on load (if not enhanced mode)
        window.onload = function () {
            // Only auto-print if not using enhanced system
            if (!window.printSystem || window.printSystem.printSettings?.print_method === 'popup') {
                window.print();
            }
        };
    </script>

<?php else: ?>
    <p class="center">No sale data found.</p>
<?php endif; ?>

</body>
</html>
