<?php

$adminUser = \Mtc\Core\Admin\User::find($adminuser->user['id']);

if ($order->address['billing']['country'] !== 'GB' && $order->address['billing']['country'] !== 'US' && $_SESSION['currency'] !== 'USD') {
    $worldwide = true;
}

if (! isset($order_preview_popup)) {
    $order_preview_popup = false;
}

if (! isset($line_colour)) {
    $line_colour = false;
}

?>

<div class="table-style-1">
    <table width="100%" class="<?= $order_preview_popup ? 'manage-items' : '' ?>">
        <tr class="row_heading">
            <?php
            if (!$order_preview_popup) {
            ?>
                <th style="text-align:left;" width="150">PLU</th>
            <?php
            }
            ?>
                <th style="text-align:left;" colspan="<?= $order_preview_popup ? '2' : '3'; ?>">Name</th>
            <?php
            if ($order_preview_popup) {
                ?>
                <th>Strength</th>
                <th>Quantity</th>
                <?php
            } else {
            ?>
                <th>Variation</th>
            <?php
            }
            ?>
            <?php
            if (!$order_preview_popup) {
                ?>
                <th width="50">Price</th>
                <th width="50">Quantity</th>
                <th width="80" align="right" style="text-align:right;">Total</th>
                <?php
            }
            ?>
        </tr>
        <tbody class="<?= $order_preview_popup ? 'tabular' : '' ?>">
        <?php
        $refund_total = 0;


        foreach ($order->getItems() as $order_item_id => $line) {
            $item = new Item();
            $item->Get_Item($line['item_id']);
            ?>
            <tr class="<?= $line_colour ?>">
                <?php
                if (!$order_preview_popup) {
                ?>
                    <td>
                        <a href="<?= $item->url; ?>" target="_blank"><?= clean_page($line['PLU']); ?></a>
                        <?php
                        if (! empty($line['shipped'])) {
                        ?>
                            - <span style="color:green;">shipped</span>
                        <?php
                        }
                        ?>
                    </td>
                <?php
                }
                ?>
                <?php
                if (!$order_preview_popup) {
                    ?>
                    <td>
                        <?php
                        if (!empty($item->images)) {
                            ?>
                            <a href="<?= $item->url; ?>" target="_blank">
                                <img src="/<?= $image_folders['product_folders']['thumbs']['path'] ?>/<?= $item->images[$item->image_default]['name'] ?>"
                                     width="100"/>
                            </a>
                            <?php
                        }
                        ?>
                    </td>
                    <?php
                }
                ?>
                <td colspan="2">
                    <a href="<?= $item->url; ?>" target="_blank">
                        <?= clean_page($line['item_name']); ?>
                        <?php
                        if ($line['PLU']) {
                        ?>
                            <br />(<?= clean_page($line['PLU']) ?>)
                        <?php
                        }
                        ?>
                    </a>
                    <?php
                    if (!$order_preview_popup) {
                            ?>
                            <a href="/shop/admin/orders/manage.order.item.php?<?=http_build_query([
                                'order_id' => $line['order_id'],
                                'id' => $line['id'],
                            ])?>"><i class="fa fa-pencil"></i></a>
                    <?php
                    }
                    if ($line['approved'] == 1) {
                        ?>
                        <div class="msg success">
                            <i class="fa fa-check"></i> Approved
                        </div>
                        <?php
                    } elseif ($line['approved'] == 2) {
                        ?>
                        <div class="msg error">
                            <i class="fa fa-remove"></i> Rejected
                        </div>
                        <?php
                    }
                    ?>

                </td>
                <?php
                if ($order_preview_popup) {
                    $size = \Mtc\Shop\Item\Size::query()->find($line['sizeid']);
                    ?>
                    <td><?= clean_page($size->strength ?? '-'); ?></td>
                    <td><?= clean_page($size->quantity ?? '-'); ?></td>
                    <td></td>
                    <?php
                } else {
                    ?>
                    <td><?= strip_tags(urldecode($line['size']), '<br>'); ?></td>
                    <?php
                }
                ?>
                <?php
                if (!$order_preview_popup) {
                    ?>
                    <td><?php printf("%.2f", clean_page($line['item_price'])) ?></td>
                    <td style="text-align:center;"><?= clean_page($line['quantity']) ?></td>
                    <td align="right" style="text-align:right;">
                        <?php

                        printf("%.2f", $line['line_total']);

                        if (!empty($line['refund'])) {
                            ?>
                            <span style="color:#ff0000;">-
                                <?php
                                printf("%.2f", $line['refund']);
                                $refund_total += $line['refund'];
                                ?>
                    </span>
                            <?php
                        }
                        ?>
                    </td>
                    <td>
                        <a href="/shop/admin/orders/manage.order.item.php?<?=http_build_query([
                            'order_id' => $line['order_id'],
                            'id' => $line['id'],
                            'action' => 'delete_order_item',
                        ])?>"
                           title="Are you sure you want to delete the order item?"
                           class="alert"
                        >
                            <i class="fa fa-remove red"></i>
                        </a>
                    </td>
                    <?php
                }
                    ?>

            </tr>

            <tr>
                <td colspan="8">
                    <table class="manage-items">
                        <?php foreach ($order->eloquent()->items as $order_item): ?>
                            <?php if ($order_item->id != $line['id']) continue; ?>
                            <?php $assessment_id = $order_item->assessment_id ?>
                            <?php include $path . 'shop/admin/orders/templates/order.assessment.view.php'; ?>
                        <?php endforeach ?>
                    </table>
                </td>
            </tr>
            <?php
        }
        ?>
        <?php
        if (!$order_preview_popup) {
            ?>
            <tr>
                <td colspan="5">
                    <a class="btn" href="manage.order.item.php?<?=http_build_query([
                        'order_id' => $line['order_id'],
                    ])?>">Add item</a>
                </td>
            </tr>
            <?php
        }
        ?>

        <?php
        // Consumables summary for this order
        if (!$order_preview_popup && class_exists(\Mtc\Plugins\Consumables\Models\ItemConsumable::class)) {
            $orderItemIds = array_column($order->getItems(), 'item_id');
            $orderConsumables = \Mtc\Plugins\Consumables\Models\ItemConsumable::whereIn('item_id', $orderItemIds)
                ->with('consumableItem')
                ->get();

            if ($orderConsumables->count() > 0) {
                // Calculate actual deductions based on order quantities
                $consumableTotals = [];
                foreach ($order->getItems() as $oItem) {
                    $itemConsumables = $orderConsumables->where('item_id', $oItem['item_id']);
                    foreach ($itemConsumables as $c) {
                        $cId = $c->consumable_item_id;
                        if (!isset($consumableTotals[$cId])) {
                            $consumableTotals[$cId] = [
                                'name' => $c->consumableItem ? $c->consumableItem->name : 'Unknown #' . $cId,
                                'stock' => $c->consumableItem ? $c->consumableItem->stock : null,
                                'total_qty' => 0,
                            ];
                        }
                        $consumableTotals[$cId]['total_qty'] += $c->quantity * (int) $oItem['quantity'];
                    }
                }
                ?>
                <tr>
                    <td colspan="9" style="padding: 10px 0 5px 0;">
                        <strong style="color: #666;"><i class="fa fa-box"></i> Consumables required for this order:</strong>
                    </td>
                </tr>
                <?php foreach ($consumableTotals as $cId => $cData) { ?>
                <tr style="background: #f9f6ee;">
                    <td></td>
                    <td colspan="4" style="color: #666;">
                        <i class="fa fa-cube"></i>
                        <?= clean_page($cData['name']) ?>
                    </td>
                    <td style="text-align: center; color: #666;">×<?= $cData['total_qty'] ?></td>
                    <td colspan="2" style="color: #999; font-size: 12px;">
                        <?php if ($cData['stock'] !== null) { ?>
                            Stock: <?= $cData['stock'] ?>
                            <?php if ($cData['stock'] <= \Mtc\Plugins\Consumables\Models\ItemConsumable::lowStockThreshold()) { ?>
                                <span style="color: #c00; font-weight: bold;">Low</span>
                            <?php } ?>
                        <?php } ?>
                    </td>
                </tr>
                <?php } ?>
                <?php
            }
        }
        ?>

        <?php

        //order_preview_popup used in manage.orders and manage.orders
        if ($order_preview_popup !== true) {
            ?>

            <tr>
                <td style="border-bottom:1px solid #ccc;" colspan="9">&nbsp;</td>
            </tr>

            <tr>
                <td colspan="9">&nbsp;</td>
            </tr>

        <?php
        }
        ?>

        <?php
        if (isset($show_totals) && $show_totals !== false) {
            ?>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <th colspan="4" style="text-align:right;">
                    Sub Total
                </th>
                <td align="right" style="text-align:right;">
                    &pound;
                    <?php
                    printf("%.2f", $order->getSubtotalCost());
                    ?>
                </td>
            </tr>

            <?php

            if (sizeof($order->discounts) > 0) {
                foreach ($order->discounts as $discount) {
                ?>
                 <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                     <th colspan="4" class="subfieldname" align="right" style="text-align:right; padding-right: 10px;">
                        <?= clean_page($discount['discount_name']);?>
                    </th>
                    <td align="right" style="text-align:right;">
                        <p>
                            -&pound;
                            <?php
                            printf("%.2f", $discount['discount_amount']);
                            ?>
                        </p>
                    </td>
                </tr>
                <?php
                }
            }
            ?>

            <?php
            if ($order->coupon_deduct > 0) {
                ?>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <th colspan="4" class="subfieldname" align="right" style="text-align:right; padding-right: 10px;">Discount</th>
                    <td align="right" style="text-align:right;"><p><?php printf("%.2f", $order->coupon_deduct); ?></p></td>
                </tr>
                <?php
            }

            if ($order->coupon_freedelivery) {
                ?>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <th colspan="4" class="subfieldname" align="right">Delivery</th>
                    <td align="right" style="text-align:right;">FREE</td>
                </tr>
                <?php
            } else {
                ?>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <th colspan="4" class="subfieldname" align="right" style="text-align:right;">
                        Shipping: <?= clean_page($order->getDelivery()->name) ?>

                    </th>
                    <td align="right" style="text-align:right;">
                        <?php
                        if ($order->getDelivery()->cost > 0) {
                            ?>&pound;<?php printf("%.2f", $order->getDelivery()->cost); ?>
                            <?php
                            if (!empty($order->delivery_refund)) {
                                ?>
                                <span style="color:#ff0000;">-<?php
                                    printf("%.2f", $order->delivery_refund);
                                    $refund_total+= $order->delivery_refund;
                                    ?></span>
                                <?php
                            }
                        } else {
                            echo "FREE";
                        }
                        ?>
                    </td>
                </tr>
                <?php
            }
            ?>
            <?php
              if (BASKET_SHOW_VAT) {
                ?>
                <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <th colspan="4" style="text-align:right;">VAT (inclusive)<?php if (!VAT_ENABLED) { ?>at <?= (VAT_RATE) ?>%<?php } ?></th>
                    <td align="right" style="text-align:right;">
                        <?php
                        if (($vat_cost = $order->getVatCost()) > 0) {
                            printf('&pound;%s', number_format($vat_cost, 2));
                        } else {
                            echo 'No Vat';
                        }
                        ?>
                    </td>
                </tr>
            <?php
            }
            ?>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <th colspan="3" class="subfieldname" align="right" style="text-align:right;">Total Cost</th>
                <td align="right" style="text-align:right;">
                    &pound;<?php printf("%.2f", $order->getTotalCost()); ?>
                </td>
            </tr>
            <?php
            if ($refund_total > 0) {
            ?>
                <tr style="color:#ff0000;">
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <th colspan="3" class="subfieldname" align="right" style="text-align:right;">Total Refunded</th>
                    <td align="right" style="text-align:right;">
                        <?php printf("%.2f", $refund_total); ?>
                    </td>
                </tr>
                <tr style="color:#ff0000;">
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <th colspan="3" class="subfieldname" align="right" style="text-align:right;">Total Paid</th>
                    <td align="right" style="text-align:right;">
                        <?php printf("%.2f", $order->getTotalCost() - $refund_total); ?>
                    </td>
                </tr>
                <?php
            }
        }
        ?>
        </tbody>
    </table>
</div>
