<?php
session_start();
include 'db.php';
include 'includes/payment_methods.php'; // Include payment methods functions

$hold_id = intval($_GET['id'] ?? 0);
$hold_order = null;
$hold_items = [];
$fbr_enabled = false;
$branch_info = null;

if ($hold_id <= 0) {
    die('Invalid hold order ID');
}

// Load hold order data with customer information
$order_result = $conn->query("
    SELECT ho.*, dt.table_name, c.phone, c.address
    FROM hold_orders ho 
    LEFT JOIN dinein_tables dt ON ho.table_id = dt.id 
    LEFT JOIN customers c ON ho.customer_id = c.id
    WHERE ho.id = $hold_id LIMIT 1
");

if (!$order_result || !$hold_order = $order_result->fetch_assoc()) {
    die('Hold order not found');
}

// Load hold items
$items_result = $conn->query("SELECT * FROM hold_items WHERE hold_id = $hold_id ORDER BY id");
while ($item = $items_result->fetch_assoc()) {
    $hold_items[] = $item;
}

$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 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 | Phone: 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']);
}

// Calculate totals
$subtotal = 0;
$tax_amount = 0;
$total_amount = 0;

foreach ($hold_items as $item) {
    $line_total = $item['unit_price'] * $item['quantity'];
    $subtotal += $line_total;
    
    // Calculate tax for this item
    if (!empty($item['tax_rate']) && $item['tax_rate'] > 0) {
        $item_tax = ($line_total * $item['tax_rate']) / 100;
        $tax_amount += $item_tax;
    }
}

$total_amount = $subtotal + $tax_amount;

// Check if payment methods are active and get tax calculation method
$payment_methods_active = false;
$tax_calculation_method = 'item_wise';
$payment_tax_rates = [];

// Check if payment methods table exists and has active methods
$payment_methods_check = $conn->query("SHOW TABLES LIKE 'payment_methods'");
if ($payment_methods_check && $payment_methods_check->num_rows > 0) {
    $active_methods = $conn->query("SELECT COUNT(*) as count FROM payment_methods WHERE is_active = 1");
    if ($active_methods && $active_methods->fetch_assoc()['count'] > 0) {
        $payment_methods_active = true;
    }
}

// Get tax calculation method
$tax_method_result = $conn->query("SELECT value FROM settings WHERE code = 'tax_calculation_method' AND is_active = 1 LIMIT 1");
if ($tax_method_result && $tax_method_row = $tax_method_result->fetch_assoc()) {
    $tax_calculation_method = $tax_method_row['value'];
}

// Get payment method tax rates if payment method tax calculation is enabled
if ($payment_methods_active && $tax_calculation_method === 'payment_method') {
    $tax_rates_result = $conn->query("SELECT payment_method, tax_rate FROM payment_method_tax_rates WHERE is_active = 1");
    while ($tax_rate_row = $tax_rates_result->fetch_assoc()) {
        $payment_tax_rates[$tax_rate_row['payment_method']] = (float)$tax_rate_row['tax_rate'];
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Proforma Invoice</title>
    <style>
body {
    font-family: Arial, sans-serif;
    font-size: <?= $receipt_font_size ?>px;
    margin: 0;
    padding: 0;
    background: #fff;
}

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

h6, p {
    margin: 0;
    padding: 0;
    font-size: <?= $receipt_font_size ?>px;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 6px;
    border: 0.5px solid #444;
}

td, th {
    padding: 3px;
    font-size: <?= $receipt_font_size ?>px;
    border: 0.5px solid #444;
}

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

.center {
    text-align: center;
}

.logo {
    margin-bottom: 5px;
}

.proforma-header {
    background: #000000;
    color: #000000;
    padding: 10px;
    margin: 8px 0;
    text-align: center;
    font-weight: bold;
    font-size: <?= $receipt_font_size + 6 ?>px;
    letter-spacing: 2px;
    border: 2px solid #000000;
}

.proforma-warning {
    background: #000000;
    border: 3px solid #000000;
    color: #000000;
    padding: 10px;
    margin: 8px 0;
    text-align: center;
    font-weight: bold;
    font-size: <?= $receipt_font_size + 3 ?>px;
    letter-spacing: 1px;
}

.summary-table {
    width: 100%;
    margin-top: 6px;
    border: none;
    font-size: <?= $receipt_font_size ?>px;
}

.summary-table td {
    padding: 2px 0;
    border: none;
   border-bottom: 1px solid #ccc; /* Underline each row */
}

.summary-table tr:last-child td {
    border-bottom: 2px solid #000; /* Stronger line under Total */
}

.summary-table .label {
    text-align: left;
}

.summary-table .value {
    text-align: right;
}

.summary-table .total {
    font-weight: bold;
    font-size: <?= $receipt_font_size + 1 ?>px;
    padding-top: 3px;
    border-top: 1px solid #ccc;
}

.remarks-section {
    margin: 8px 0;
    padding: 6px;
    background-color: #f9f9f9;
    border-left: 2px solid #007bff;
}

.payment-totals {
    margin: 8px 0;
    padding: 10px;
    background-color: #000000;
    border: 3px solid #000000;
}

.payment-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 2px solid #000000;
    font-weight: bold;
}

.payment-option:last-child {
    border-bottom: none;
}

.payment-label {
    color: #000000;
    font-size: <?= $receipt_font_size + 2 ?>px;
    font-weight: bold;
}

.payment-amount {
    color: #000000;
    font-size: <?= $receipt_font_size + 3 ?>px;
    font-weight: bold;
}

hr {
    border: 0.5px dashed #666;
    margin: 4px 0;
}

/* Print-specific layout fix for thermal printers */
@media print {
    @page {
        margin: 2mm; /* Minimal margins for thermal printers */
    }

    body {
        margin: 0;
        padding: 0;
        font-size: <?= $receipt_font_size ?>px;
    }

    .receipt-wrapper {
        margin: 0;
        padding: 4px;
        width: auto;
        max-width: none;
        box-sizing: border-box;
    }

    td, th, p, h6 {
        font-size: <?= $receipt_font_size ?>px;
    }

    .proforma-header {
        padding: 10px;
        margin: 8px 0;
        font-size: <?= $receipt_font_size + 5 ?>px;
        background: #000000 !important;
        color: #000000 !important;
        font-weight: bold !important;
        letter-spacing: 2px !important;
    }

    .proforma-warning {
        padding: 8px;
        margin: 8px 0;
        font-size: <?= $receipt_font_size + 2 ?>px;
        background: #000000 !important;
        color: #000000 !important;
        font-weight: bold !important;
        letter-spacing: 1px !important;
    }

    .payment-totals {
        margin: 8px 0;
        padding: 10px;
        background: #000000 !important;
        border: 3px solid #000000 !important;
    }

    .payment-option {
        padding: 6px 0;
    }

    .payment-label, .payment-amount {
        color: #000000 !important;
        font-weight: bold !important;
        font-size: <?= $receipt_font_size + 2 ?>px !important;
    }

    img {
        max-width: 100%;
        height: auto;
    }
}
    </style>
</head>
<body>

<div class="receipt-wrapper">

<div class="center">
    <img src="assets/img/branch_logo.png" width="<?= $receipt_logo_width ?>" alt="Logo" class="logo"><br>

    <?php if ($branch_info): ?>
        <h6><?= htmlspecialchars($branch_info['branch_name']) ?></h6>
        <p><?= nl2br(htmlspecialchars($branch_info['branch_address'])) ?></p>

        <?php if (!empty($branch_info['branch_phone'])): ?>
            <p><strong>Phone:</strong> <?= htmlspecialchars($branch_info['branch_phone']) ?></p>
        <?php endif; ?>

        <?php if (!empty($branch_info['ntn'])): ?>
            <p><strong>NTN:</strong> <?= htmlspecialchars($branch_info['ntn']) ?></p>
        <?php endif; ?>

        <?php if (!empty($branch_info['strn'])): ?>
            <p><strong>STRN:</strong> <?= htmlspecialchars($branch_info['strn']) ?></p>
        <?php endif; ?>
    <?php endif; ?>
</div>

<hr>

<!-- PROFORMA INVOICE HEADER -->
<div class="proforma-header">
    PROFORMA INVOICE
</div>

<div class="proforma-warning">
    THIS IS A PROFORMA INVOICE - NOT A FINAL BILL
</div>

<h6 class="center">Proforma Invoice</h6>

<?php if ($print_customer_name && !empty($hold_order['customer_name'])): ?>
    <p><strong>Name:</strong> <?= htmlspecialchars($hold_order['customer_name']) ?></p>
<?php endif; ?>

<?php if ($print_customer_number && !empty($hold_order['phone'])): ?>
    <p><strong>Phone:</strong> <?= htmlspecialchars($hold_order['phone']) ?></p>
<?php endif; ?>

<?php if ($print_customer_address && !empty($hold_order['address'])): ?>
    <p><strong>Address:</strong> <?= htmlspecialchars($hold_order['address']) ?></p>
<?php endif; ?>

<p><strong>Proforma #:</strong> PROFORMA-<?= str_pad($hold_order['id'], 6, '0', STR_PAD_LEFT) ?></p>

<?php if ($print_datetime): ?>
    <p><strong>Date:</strong> <?= date('d.m.Y', strtotime($hold_order['created_at'])) ?></p>
    <p><strong>Time:</strong> <?= date('H:i:s', strtotime($hold_order['created_at'])) ?></p>
<?php endif; ?>

<?php if (!empty($hold_order['order_mode'])): ?>
    <p><strong>Order Mode:</strong> <?= ucfirst(str_replace('_', ' ', $hold_order['order_mode'])) ?></p>
    <?php if ($hold_order['order_mode'] === 'dine_in' && !empty($hold_order['table_name'])): ?>
        <p><strong>Table:</strong> <?= htmlspecialchars($hold_order['table_name']) ?></p>
    <?php endif; ?>
<?php endif; ?>

<hr>

<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Item</th>
            <th>Qty</th>
            <th class="text-end">Unit Price</th>
            <th class="text-end">Total</th>
        </tr>
    </thead>
    <tbody>
    <?php
    $i = 1;
    $sale_remarks = []; // Array to collect all remarks from hold items
    
    foreach ($hold_items as $item):
        $line_total = $item['unit_price'] * $item['quantity'];
        
        // Collect remarks if they exist
        if (!empty($item['remarks'])) {
            $sale_remarks[] = $item['remarks'];
        }
    ?>
        <tr>
            <td><?= $i++ ?>.</td>
            <td>
                <?= htmlspecialchars($item['item_name']) ?>
                <?php if (!empty($item['modifiers'])): ?>
                    <?php 
                        $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)) {
                                echo '<br><small style="color: #666;">(' . htmlspecialchars($modifier_text) . ')</small>';
                            }
                        }
                    ?>
                <?php endif; ?>
            </td>
            <td><?= $item['quantity'] ?></td>
            <td class="text-end">Rs <?= number_format($item['unit_price'], 2) ?></td>
            <td class="text-end">Rs <?= number_format($line_total, 2) ?></td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<hr>

<?php if ($payment_methods_active && $tax_calculation_method === 'payment_method' && !empty($payment_tax_rates)): ?>
    <!-- Payment Method Totals -->
    <div class="payment-totals">
        <h6 style="text-align: center; margin-bottom: 10px; color: #000000; font-weight: bold; font-size: <?= $receipt_font_size + 4 ?>px; letter-spacing: 2px;">PAYMENT OPTIONS</h6>
        
        <?php 
        // Calculate totals for each payment method
        $cash_rate = $payment_tax_rates['cash'] ?? 0;
        $card_rate = $payment_tax_rates['card'] ?? 0;
        
        $cash_total = $subtotal + ($subtotal * ($cash_rate / 100));
        $card_total = $subtotal + ($subtotal * ($card_rate / 100));
        ?>
        
        <div class="payment-option">
            <span class="payment-label">Cash (<?= number_format($cash_rate, 1) ?>%):</span>
            <span class="payment-amount">Rs <?= number_format($cash_total, 2) ?></span>
        </div>
        
        <div class="payment-option">
            <span class="payment-label">Card (<?= number_format($card_rate, 1) ?>%):</span>
            <span class="payment-amount">Rs <?= number_format($card_total, 2) ?></span>
        </div>
        
        <?php if (isset($payment_tax_rates['upi']) && $payment_tax_rates['upi'] > 0): ?>
        <?php 
        $upi_rate = $payment_tax_rates['upi'];
        $upi_total = $subtotal + ($subtotal * ($upi_rate / 100));
        ?>
        <div class="payment-option">
            <span class="payment-label">UPI (<?= number_format($upi_rate, 1) ?>%):</span>
            <span class="payment-amount">Rs <?= number_format($upi_total, 2) ?></span>
        </div>
        <?php endif; ?>
        
        <div style="margin-top: 8px; padding-top: 8px; border-top: 2px solid #000000; text-align: center;">
            <span style="color: #000000; font-weight: bold; font-size: <?= $receipt_font_size + 1 ?>px;">Subtotal: Rs <?= number_format($subtotal, 2) ?></span>
        </div>
    </div>
<?php else: ?>
    <!-- Standard Totals -->
    <table class="summary-table">
    <tr>
        <td class="label">Subtotal</td>
        <td class="value">Rs <?= number_format($subtotal, 2) ?></td>
    </tr>
    <?php if ($tax_amount > 0): ?>
    <tr>
        <td class="label">Tax</td>
        <td class="value">Rs <?= number_format($tax_amount, 2) ?></td>
    </tr>
    <?php endif; ?>
    <tr>
        <td class="label total">Total Amount</td>
        <td class="value total">Rs <?= number_format($total_amount, 2) ?></td>
    </tr>
    </table>
<?php endif; ?>

<?php if ($print_remarks && !empty($sale_remarks)): ?>
    <hr>
    <div class="remarks-section">
        <p><strong>Remarks:</strong></p>
        <?php foreach ($sale_remarks as $remark): ?>
            <p style="margin: 5px 0; padding-left: 20px;">- <?= htmlspecialchars($remark) ?></p>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<div class="center">
    <p><strong>Hold Order #<?= $hold_order['id'] ?></strong></p>
    <p>This is a proforma invoice for estimation purposes only.</p>
    <p>Final bill will be generated upon payment.</p>
</div>

<script>
    window.onload = function () {
        window.print();
    };
</script>

</body>
</html>
