<?php

use Illuminate\Support\Facades\Event;
use Mtc\Core\Permissions;
use Mtc\Plugins\Realex\Classes\OrderRealex;
use Mtc\Plugins\Judopay\Classes\Judopay;
use Mtc\Plugins\Refunds\Classes\Refund;
use Mtc\Plugins\RyftPay\Classes\RyftPay;
use Mtc\Shop\Order\Shipment;
use Mtc\Shop\Order\ShipmentItem;
use Mtc\Shop\OrderStatus;
use Mtc\Shop\OrderStatusLog;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$page_meta['title'] = 'Order Details';

init_request_values([
    'id' => null,
    'sent' => null,
    'epos_sent' => null,
]);

$epos_sent = false;


if (!$order = Order::getById($_REQUEST['id'])) {
    header('Location: /shop/admin/orders/manage.orders.php');
    exit();
}

$order_eloquent = $order->eloquent();


// load admin eloquent user and its allowed categories
$admin = \Mtc\Core\Admin\User::find($adminuser->user['id']);
$allowed_categories = $admin->allowedCategories->pluck('category_id');

// if admin is allowed only certain amount of categories, validate this order has items from those categories
if (count($allowed_categories)) {
    // make sure we include sub-categories for items
    $with_sub_categories = [];
    foreach ($allowed_categories as $category) {
        $with_sub_categories = array_merge($with_sub_categories, get_cat_ids($category));
    }
    $has_item = false;
    foreach ($order->getItems() as $line_item) {
        // Find if this item is bound to a category that the admin user can view
        $allowed_category_item = \Illuminate\Support\Facades\DB::table('items_categories')
            ->where('item_id', $line_item['item_id'])
            ->whereIn('cat_id', $with_sub_categories)
            ->count();

        // If item is from the allowed category we can grant user access to this order
        if ($allowed_category_item) {
            $has_item = true;
        }
    }

    // If user doesn't have access to any of the items in this order
    if (!$has_item) {
        header('Location: /shop/admin/orders/manage.orders.php');
        exit();
    }
}

if ($_REQUEST['action'] == 'edit') {

    if ($_REQUEST['shipping_firstname'] != $order->address['shipping']['firstname']
        || $_REQUEST['shipping_lastname'] != $order->address['shipping']['lastname']
        || $_REQUEST['shipping_gender'] != $order->address['shipping']['gender']
        || $_REQUEST['shipping_address1'] != $order->address['shipping']['address1']
        || $_REQUEST['shipping_address2'] != $order->address['shipping']['address2']
        || $_REQUEST['shipping_city'] != $order->address['shipping']['city']
        || $_REQUEST['shipping_country'] != $order->address['shipping']['country']
        || $_REQUEST['shipping_postcode'] != $order->address['shipping']['postcode']) {
        $note = 'Shipping address changed from ' . $order->address['shipping']['firstname'] . ' ' . $order->address['shipping']['lastname']
            . ', ' . $order->address['shipping']['address1']
            . ', ' . $order->address['shipping']['address2']
            . ', ' . $order->address['shipping']['city']
            . ', ' . $order->address['shipping']['country']
            . ', ' . $order->address['shipping']['postcode']
            . ' to ' . $_REQUEST['shipping_firstname'] . ' ' . $_REQUEST['shipping_lastname']
            . ', ' . $_REQUEST['shipping_address1']
            . ', ' . $_REQUEST['shipping_address2']
            . ', ' . $_REQUEST['shipping_city']
            . ', ' . $_REQUEST['shipping_country']
            . ', ' . $_REQUEST['shipping_postcode'];

        $order->address['shipping']['gender'] = $_REQUEST['shipping_gender'];
        $order->address['shipping']['firstname'] = $_REQUEST['shipping_firstname'];
        $order->address['shipping']['lastname'] = $_REQUEST['shipping_lastname'];
        $order->address['shipping']['address1'] = $_REQUEST['shipping_address1'];
        $order->address['shipping']['address2'] = $_REQUEST['shipping_address2'];
        $order->address['shipping']['city'] = $_REQUEST['shipping_city'];
        $order->address['shipping']['country'] = $_REQUEST['shipping_country'];
        $order->address['shipping']['postcode'] = $_REQUEST['shipping_postcode'];

        $order->updateCustomerOrderAddress();

        $order->addOrderNote($note);
    }

    if ($_REQUEST['billing_firstname'] != $order->address['billing']['firstname']
        || $_REQUEST['billing_lastname'] != $order->address['billing']['lastname']
        || $_REQUEST['billing_gender'] != $order->address['billing']['gender']
        || $_REQUEST['billing_address1'] != $order->address['billing']['address1']
        || $_REQUEST['billing_address2'] != $order->address['billing']['address2']
        || $_REQUEST['billing_city'] != $order->address['billing']['city']
        || $_REQUEST['billing_country'] != $order->address['billing']['country']
        || $_REQUEST['billing_postcode'] != $order->address['billing']['postcode']) {
        $note = 'Billing address changed from ' . $order->address['billing']['firstname'] . ' ' . $order->address['billing']['lastname']
            . ', ' . $order->address['billing']['address1']
            . ', ' . $order->address['billing']['address2']
            . ', ' . $order->address['billing']['city']
            . ', ' . $order->address['billing']['country']
            . ', ' . $order->address['billing']['postcode']
            . ' to ' . $_REQUEST['billing_firstname'] . ' ' . $_REQUEST['billing_lastname']
            . ', ' . $_REQUEST['billing_address1']
            . ', ' . $_REQUEST['billing_address2']
            . ', ' . $_REQUEST['billing_city']
            . ', ' . $_REQUEST['billing_country']
            . ', ' . $_REQUEST['billing_postcode'];

        $order->address['billing']['gender'] = $_REQUEST['billing_gender'];
        $order->address['billing']['firstname'] = $_REQUEST['billing_firstname'];
        $order->address['billing']['lastname'] = $_REQUEST['billing_lastname'];
        $order->address['billing']['address1'] = $_REQUEST['billing_address1'];
        $order->address['billing']['address2'] = $_REQUEST['billing_address2'];
        $order->address['billing']['city'] = $_REQUEST['billing_city'];
        $order->address['billing']['country'] = $_REQUEST['billing_country'];
        $order->address['billing']['postcode'] = $_REQUEST['billing_postcode'];

        $order->updateCustomerOrderAddress();

        $order->addOrderNote($note);
    }

    if ($_REQUEST['contact_no'] != $order->info['contact_no']) {
        $note = 'Telephone number changed from ' . $order->info['contact_no'] . ' to ' . $_REQUEST['contact_no'];

        $order->info['contact_no'] = $_REQUEST['contact_no'];

        $order->updateCustomerOrderInfo();

        $order->addOrderNote($note);
    }

    if ($_REQUEST['email'] != $order->info['email']) {
        $note = 'Email address changed from ' . $order->info['email'] . ' to ' . $_REQUEST['email'];

        $order->info['email'] = $_REQUEST['email'];

        $order->updateCustomerOrderInfo();

        $order->addOrderNote($note);
    }

    header("Location: manage.order.php?id=" . $order->getId());

}

if ($_REQUEST['action'] == 'mark_paid' && !$order->paid) {
    $order->markPaid('manual');
    $order->sendOrderConfirmation();
}

if ($_REQUEST['action'] == 'update_status') {
    $order->updateStatus((int)$_REQUEST['status'], !empty($_REQUEST['send_status_mail']));
}

if (!empty($_REQUEST['generate_invoice'])) {
    $order->createInvoice($basket_countries, $twig);
}

if ($_REQUEST['action'] == 'add_note') {

    $order->addOrderNote($_REQUEST['note']);

    header("Location: manage.order.php?id=" . $order->getId());
    exit();
}

if ($_REQUEST['action'] == 'resend') {
    $order->sendOrderConfirmation();

    $note = sprintf('Order confirmation re-sent at %s on %s', date('H:i:s'), date('d-m-Y'));

    $order->addOrderNote($note);

    header("Location: manage.order.php?sent=1&id=" . $order->getId());
    exit();
}

if ($_REQUEST['action'] === 'trustpilot' && $order->trustpilot_sent === '0000-00-00 00:00:00') {
    $trustpilot = new \Mtc\Plugins\TrustpilotAPI\Classes\TrustpilotAPI();
    $response = $trustpilot->createReviewInvitation($order);

    if (!isset($response->id)) {
        if (!empty($response->fault->faultstring)) {
            $_SESSION['error'] = 'Trustpilot Invite Failed - ' . $response->fault->faultstring
                . "<a href='/plugins/TrustpilotAPI/admin/'>Click here to open TrustPilot authorize section</a>";

        } elseif (!empty($response->details)) {
            $_SESSION['error'] = 'Trustpilot Invite Failed - ' . $response->details;
        }
        header('Location: manage.order.php?id=' . $order->getId());
        exit;
    }

    $order->updateTrustpilotSent();
    \Mtc\Shop\Order\Note::query()
        ->create([
            'order_id' => $order->getId(),
            'note' => 'Trustpilot invitation sent on ' . date('Y-m-d H:i:s')
        ]);

    $_SESSION['message'] = 'Invite sent';
    header('Location: manage.order.php?id=' . $order->getId());
    exit;
}

if ($_REQUEST['action'] === 'create_shipment') {

    if ($order->hasShipmentsWithLabels() === false) {
        // If there's a shipment but it doesn't have a label, we delete it and try create a new one
        if ($order->hasShipments()) {
            \Mtc\Shop\Order\Shipment::query()
                ->where('order_id', '=', $order->getId())
                ->delete();
        }
        if (\Mtc\Plugins\DeliveryCouriers\Classes\Courier::sendOrder($order)) {
            $_SESSION['message'] = 'Shipment created successfully';
        } else {
            $_SESSION['error'] = 'Failed to create shipment.';
        }
    } else {
        $_SESSION['error'] = 'Order already has a shipment!';
    }

    header('Location: manage.order.php?id=' . $order->getId());
    exit;
}

if ($_REQUEST['action'] === 'optimize') {
    $path = SITE_PATH . '/uploads/files/invoices/' . $order->order_ref . '.pdf';
    $target = SITE_PATH . '/uploads/files/optimizedlabels/' . $order->order_ref . '.png';

    exec('convert -density 200 ' . $path . ' -resize 50% -trim ' . $target);
    exit;
}

if ($_REQUEST['action'] === 'blacklist') {
    $type = filter_var($_REQUEST['type'], FILTER_SANITIZE_NUMBER_INT);

    $data = [];

    switch ($type) {
        case 1:
            $data['email'] = $order->info['email'];
            break;

        case 2:
            $data['telephone'] = $order->info['contact_no'];
            break;

        case 3:
            $data['address'] = $order->address['billing']['postcode'];
            break;

        case 0:
        default:
            $data = [
                'email' => $order->info['email'],
                'telephone' => $order->info['contact_no'],
                'address' => $order->address['billing']['postcode']
            ];
            break;
    }

    \Mtc\Modules\BlackList\Classes\BlackList::create($data);
}

if (filter_input(INPUT_GET, 'action') === 'change_shipping_method' && !empty($_REQUEST['id'])) {

    if (\Mtc\Shop\Order::changeDeliveryMethod($_REQUEST['id'], $_POST['delivery_method_id'])) {
        $_SESSION['message'] = 'Delivery method changed successfully!';
    } else {
        $_SESSION['error'] = 'Delivery method has not been changed!';
    }
    $get = $_GET;
    unset($get['action']);
    header('location: /shop/admin/orders/manage.order.php?' . http_build_query($get));
    exit;
}


if ($_REQUEST['action'] === 'capture_realex') {
    $payment = OrderRealex::where('order_id', $order->getId())
        ->firstOrFail()
    ;

    $output = $payment->capture();
    if ($output['success']) {
        $_SESSION['message'] = $output['response_message'];
    } else {
        $_SESSION['error'] = $output['response_message'];
    }

    header('Location: manage.order.php?id=' . $order->getId());
    exit;
}


require_once $path . 'core/admin/templates/adminheader.html.php';

?>

    <script src="../js/shop_script.js"></script>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li><a href="manage.orders.php">Manage Orders</a> /</li>
        <li class="end">Order Details</li>
    </ul>

    <h1>Order <span class="black">
    <?= clean_page(
        !empty(
        $order->payment['VendorTxCode']) ? $order->payment['VendorTxCode']
            : $order->order_ref);
    ?>
</span>

        <?php
        if (!$order->failed) {
            if ($_REQUEST['edit'] != 1) {
                ?>
                <a href="?id=<?= $order->getId(); ?>&edit=1"><i class="fa fa-pencil"></i></a>
                <?php
            }
        }
        ?>
    </h1>

    <h5>Member ID: <a href="/modules/Members/admin/manage_member.php?id=<?= $order->member ?>" target="_blank"><?= $order->member ?></a></h5>

    <?php if ($order_eloquent->magento_entity_id) { ?>
        <h5>Magento Order Ref: <?= $order_eloquent->order_ref  ?> / <?= $order_eloquent->magento_entity_id ?></h5>
    <?php } ?>

<?php

if ($order->hasOutstandingDeferredPayment()) {
    echo showmsg("Payment on order has not been captured yet", "warning", $path);
}
if ($order_eloquent->failed_id_check) {
    echo showmsg("ID Check Failed. Please verify customer details manually", "error", $path);
}

if (!empty($_SESSION['message'])) {
    echo showmsg($_SESSION['message'], "success", $path);
    unset($_SESSION['message']);
}

if (!empty($_SESSION['error'])) {
    echo showmsg($_SESSION['error'], "error", $path);
    unset($_SESSION['error']);
}

if ($_REQUEST['sent'] == 1) {
    echo showmsg("Order confirmation re-sent", "success", $path);
}


if ($_REQUEST['edit'] == 1) {
    ?>
    <form action="manage.order.php" method="post">
        <?php
        }

        if ($order->paid == 0) {
            $errors[] = 'This order has not been paid for yet!';
            showerrors($errors);
        }

        // check if another currency and convert
        if (!empty($order->payment_bank_of_ireland)) {
            if ($order->payment_bank_of_ireland['currency'] == 'EUR') {
                // if euro, convert price paid from EUR to GBP
                $order->amount_paid = $order->amount_paid / (getCurrencyValue(1, 'EUR'));
            }
        }

        if (!$order->matchesTotal($order->amount_paid)) {
            $errors[] = 'The amount paid on this order (' . sprintf("%01.2f", $order->amount_paid) . ') is different than the order total (' . sprintf("%01.2f", $order->getTotalCost()) . ').';
            showerrors($errors);
        }
        ?>

        <div class="orderdetails ordersection el">
            <div class="el purchasedate">
                <table>
                    <tr>
                        <td>Purchase Date:</td>
                        <td><?= $order->getOrderDate('d/m/Y H:i:s') ?></td>
                    </tr>
                    <tr>
                        <td>Shipping Service:</td>
                        <td>
                            <div class="row">
                                <form action="manage.order.php?action=change_shipping_method&id=<?= clean_page($order->getId()); ?>"
                                      method="post">
                                    <div class="row selectInline">
                                        <select name="delivery_method_id">
                                            <option value="0">No delivery</option>
                                            <?php
                                            $delivery_methods = DeliveryMethod::query()
                                                ->where('disable', '=', '0')
                                                ->orderBy('id')
                                                ->get();
                                            foreach ($delivery_methods as $delivery_method) {
                                                $selected = $delivery_method->id === $order_eloquent->delivery_method_id ? 'selected' : '';
                                                echo "<option value='{$delivery_method->id}' {$selected}>{$delivery_method->name}</option>";
                                            }
                                            ?>
                                        </select>
                                        <button type="submit" class="btn">Save</button>
                                    </div>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php
                    if (!empty($order->tracking_no)) {
                        ?>
                        <tr>
                            <td>Tracking no:</td>
                            <td><?= $order->tracking_no ?: '-'; ?></td>
                        </tr>
                        <?php
                    } elseif ($order_eloquent->shipments()->exists()) {
                        $order_eloquent->shipments
                            ->each(function ($shipment) {
                                ?>
                                <tr>
                                    <td>Tracking no:</td>
                                    <td><?= $shipment->tracking_no ?: '-'; ?></td>
                                </tr>
                                <?php
                            });
                    }
                    ?>

                    <tr>
                        <td>Customer:</td>
                        <td>
                            <?php
                            if ($_REQUEST['edit'] == 1) {
                                ?>
                                <input type="email" name="email" value="<?= clean_page($order->info['email']) ?>"/>
                                <?php
                            } else {
                                ?>
                                <a href="<?= route('admin-patients-profile', ['id' => $order->member], false) ?>">
                                    <?= clean_page($order->getCustomerName()) ?>
                                </a>
                                <?php
                            }
                            ?>
                        </td>
                    </tr>

                    <?php
                    if (!empty($order->info['how_did_you_hear_about_us'])) {
                        ?>
                        <tr>
                            <td>How did you hear about us?</td>
                            <?php
                            if (!empty($order->info['how_did_you_hear_about_us_text'])) {
                                ?>
                                <td><?= clean_page($order->info['how_did_you_hear_about_us_text']) ?></td>
                                <?php
                            } else {
                                ?>
                                <td><?= clean_page($order->info['how_did_you_hear_about_us']) ?></td>
                                <?php
                            }
                            ?>
                        </tr>
                        <?php
                    }
                    ?>

                    <tr>
                        <td valign="top">Order Status</td>
                        <td>
                            <?php
                            // if user is not Doctor
                            if (
                                Permissions::can(Permissions::FULL_ORDER_ACCESS) &&
                                !in_array($order->status, [1, 2])
                            ) {
                                if (!$order->failed) {
                                    if ($_REQUEST['edit'] != '1') {
                                        ?>
                                        <form action="manage.order.php">
                                            <div class="row">
                                                <select name="status" id="orderStatusSelect" class="INPUT1"
                                                        data-email_statuses="<?= json_encode(array_keys($status_send_mail)) ?>">
                                                    <?php
                                                    foreach ($orders_statuses as $status_id => $status_name) {

                                                        if ($status_id == $order->status) {
                                                            ?>
                                                            <option value="<?= clean_page($status_id) ?>"
                                                                    selected><?= clean_page($status_name) ?></option>
                                                            <?php
                                                        } else {
                                                            ?>
                                                            <option value="<?= clean_page($status_id) ?>"><?= clean_page($status_name) ?></option>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                            <div class="row" id="sendStatusMailRow">
                                                <input type="checkbox" name="send_status_mail" value="1"
                                                       id="sendStatusMail"/>
                                                <label for="sendStatusMail" style="width: auto; margin-left: 5px;">Send
                                                    status update e-mail</label>
                                            </div>
                                            <div class="row">
                                                <input type="submit" value="Update"/>
                                                <input type="hidden" name="id"
                                                       value="<?= clean_page($order->getId()) ?>"/>
                                                <input type="hidden" name="action" value="update_status"/>
                                            </div>
                                        </form>
                                        <?php
                                    } else {
                                        ?>
                                        <div class="row">
                                            <?= clean_page($orders_statuses[$order->status]) ?>
                                        </div>
                                        <?php
                                    }
                                } else {
                                    ?>
                                    <span style="color:#ff0000;">FAILED</span>
                                    <?php
                                }
                            } else {
                                echo $orders_statuses[$order->status];
                            }
                            ?>
                        </td>
                    </tr>
                </table>
            </div><!-- end of uppertable -->

            <?php
            if (!$order->failed) {
                ?>
                <div class="el actions">
                    <?php
                    // if user not doctor
                    if (Permissions::can(Permissions::FULL_ORDER_ACCESS)) {
                        ?>

                        <table class="manage-items buttonGroups">
                            <tr>
                                <th>Process</th>
                                <th>Communication</th>
                                <th>Print</th>
                            </tr>
                            <tr>
                                <td>
                                    <?php

                                    if (!$order->paid) {
                                        ?>
                                        <a href="?action=mark_paid&id=<?= clean_page($order->getId()) ?>"
                                           data-amount="<?= clean_page($order->getTotalCost()) ?>"
                                           data-order_id="<?= clean_page($order->getId()) ?>"
                                           class="btn markPaidBtn"
                                        >
                                            Mark Paid
                                        </a>
                                        <?php
                                    }
                                    if ($order->status > 2) {
                                        ?>
                                        <?php if (file_exists(SITE_PATH . '/uploads/files/invoices/' . md5($order->getId()) . '.pdf') !== false) { ?>
                                            <a href="<?php echo SITE_URL . '/uploads/files/invoices/' . md5($order->getId()) . '.pdf'; ?>"
                                               class="btn"
                                               target="_blank"
                                            >
                                                View invoice
                                            </a>
                                        <?php } else { ?>
                                            <a href="manage.order.php?id=<?= $order->getId(); ?>&generate_invoice=true"
                                               class="btn"/>
                                            Generate PDF invoice
                                            </a>
                                        <?php } ?>
                                        <?php
                                    }

                                    if (empty($order->shipping_label)) {
                                        ?>
                                        <button type="button" id="createShipmentBtn" title="Are you sure you want to create the shipment?"
                                           class="alert btn" style="margin-bottom: 16px; width: 100%; text-align: center;" data-order-id="<?= clean_page($order->getId()); ?>">
                                            Create Shipment
                                        </button>
                                        <?php
                                    }

                                    if ($order_eloquent->failed_id_check) {
                                        ?>
                                        <a href="/shop/admin/orders/<?= clean_page($order->getId()); ?>/confirm-id-check"
                                           class="btn">
                                            Confirm Customer ID Check
                                        </a>
                                        <?php
                                    }

                                    foreach (Event::dispatch('shop.admin.manage_order.order_buttons', $order) as $action_button) {
                                        if (is_array($action_button)) {
                                        ?>
                                            <a href="<?= $action_button['url'] ?>" class="btn">
<?= $action_button['label'] ?>
                                            </a>
                                        <?php
                                        } else {
                                            echo $action_button;
                                        }
                                    }

                                    ?>
                                </td>
                                <td>
                                    <a href="manage.order.php?action=resend&id=<?= clean_page($order->getId()) ?>"
                                       title="Are you sure you want to resend the email?"
                                       class="alert btn"
                                    >
                                        ReSend Order Confirmation
                                    </a>

                                    <?php
                                    if (defined("TRUSTPILOT_API_ENABLED") &&
                                        TRUSTPILOT_API_ENABLED &&
                                        $order->trustpilot_sent == '0000-00-00 00:00:00'
                                    ) {
                                    ?>
                                        <a href="manage.order.php?action=trustpilot&id=<?= clean_page($order->getId()); ?>"
                                           title="Are you sure you want to send this order to trustpilot?"
                                           class="alert btn">
                                            Send TrustPilot invitation
                                        </a>
                                    <?php } ?>

                                    <div class="el"><label for="ordernotetext" class="el btn">New Note</label></div>
                                    <a href="/plugins/MembersMessaging/admin/view_member_thread.php?act=request_info&order_id=<?= clean_page($order->getId()); ?>"
                                       title="Send a message to user"
                                       class="btn"
                                    >Message User</a>

                                </td>
                                <td>
                                    <a href="#"
                                       data-id="<?= clean_page($order->getId()) ?>"
                                       class="btn printDespatchNote"
                                    >
                                        Print Despatch Note
                                    </a>

                                    <a href="/shop/admin/orders/optimized_print.php?order_ids=<?= $order->getId() ?>" class="btn">
                                        Open Print Section
                                    </a>
                            </tr>
                        </table>
                        <?php
                    }
                    ?>
                    <form action="manage.order.php?action=blacklist&id=<?= clean_page($order->getId()); ?>"
                          method="post">
                        <div class="row selectInline">
                            <select name="type">
                                <option value="0">All fields</option>
                                <option value="1">Customer email</option>
                                <option value="2">Customer telephone</option>
                                <option value="3">Customer address</option>
                            </select>
                            <button type="submit" class="btn">Blacklist</button>
                        </div>
                    </form>

                </div>
                <?php
            }
            ?>

        </div><!-- end of upper order page -->



        <?php if ($order_eloquent->subscriptions->count()): ?>
            <div class="el customerdetails ordersection">
                <h2>Subscriptions</h2>
                <ol>
                    <?php foreach ($order_eloquent->subscriptions as $order_subscription): ?>
                    <li><a href="<?= route('admin-subscriptions-edit', [ $order_subscription->id ], false) ?>">#<?= $order_subscription->id ?></a></li>
                    <?php endforeach ?>
                </ol>
            </div> <!-- .customerdetails.ordersection -->
        <?php endif ?>


        <div class="divider el"></div>

        <?php if ($order_eloquent->orders->count()): ?>
            <div class="el customerdetails ordersection">
                <h2>Grouped Order Details</h2>

                <ol>
                    <?php foreach ($order_eloquent->orders as $child_order): ?>
                        <li>
                            <a href="<?= $child_order->getAdminUrl() ?>">
                                Child order id:<?= $child_order->id ?>
                            </a>
                        </li>
                    <?php endforeach ?>
                </ol>
            </div> <!-- .customerdetails.ordersection -->

            <div class="divider el"></div>
        <?php elseif ($order_eloquent->parent_id): ?>
            <div class="el customerdetails ordersection">
                <h2>Grouped Order Details</h2>

                <a href="<?= $order_eloquent->parent->getAdminUrl() ?>">
                    Parent order id:<?= $order_eloquent->parent_id ?>
                </a>
            </div> <!-- .customerdetails.ordersection -->

            <div class="divider el"></div>
        <?php endif ?>


        <div class="el customerdetails ordersection">
            <h2>Customer Details</h2>

            <?php
            require_once $path . 'shop/admin/orders/templates/order.customer_details.php';
            ?>

        </div> <!-- .customerdetails.ordersection -->


        <?php
        // if user is not Admin
        if (Permissions::can(Permissions::FULL_ORDER_ACCESS)) {
        if ($_REQUEST['edit'] == 1) {
        ?>

        <div class="row">
            <input type="hidden" name="action" value="edit"/>
            <input type="hidden" name="id" value="<?= clean_page($order->getId()) ?>"/>
            <input type="submit" value="<?= (!empty($_REQUEST["edit"])) ? "Save" : "Edit"; ?> "/>
        </div>
    </form>
    <?php
    } else {
    ?>
    <div class="row el"><a href="?id=<?= clean_page($order->getId()) ?>&edit=1" class="btn">Edit</a></div>
    <?php
}
}
?>

        <div class="divider el"></div>

    <div class="el customerdetails ordersection">
        <h2>Customer Health Profile</h2>
        <table>
            <tr>
                <th width="33%">Allergies:</th>
                <th width="33%">Medications:</th>
                <th width="33%">Medical Conditions:</th>
            </tr>
            <tr>
                <td><?= $order_eloquent->customer->getAllergiesString('<br />') ?></td>
                <td><?= $order_eloquent->customer->getMedicationsString('<br />') ?></td>
                <td><?= $order_eloquent->customer->getConditionsString('<br />') ?></td>
            </tr>
        </table>

        <hr />

        <h2>Customer Health (from Order)</h2>
        <table>
            <tr>
                <th width="33%">Allergies:</th>
                <th width="33%">Medications:</th>
                <th width="33%">Medical Conditions:</th>
            </tr>
            <tr>
                <td><?= empty($order->info['member_allergies']) ? '' : implode('<br />', json_decode($order->info['member_allergies'])); ?></td>
                <td><?= empty($order->info['member_medications']) ? '' : implode('<br />', json_decode($order->info['member_medications'])); ?></td>
                <td><?= empty($order->info['member_conditions']) ? '' : implode('<br />', json_decode($order->info['member_conditions'])); ?></td>
            </tr>
        </table>
    </div> <!-- .customerdetails.ordersection -->

    <div class="divider el"></div>

    <div class="el ordersection" id="ordernote">
        <h2>Internal notes</h2>
        <form method="post" class="style">
            <fieldset>

                <div class="row">
                    <textarea name="note" id="ordernotetext"></textarea>
                </div>
                <div class="row">
                    <input type="submit" value="Save"/>
                </div>

                <input type="hidden" name="action" value="add_note"/>
                <input type="hidden" name="id" value="<?= clean_page($order->getId()) ?>"/>

            </fieldset>
        </form>

        <?php
        foreach ($order->getOrderNotes() as $note) {
            ?>
            <br/>
            <p>
                <b>
                    Message sent on <?= clean_page(convert_date($note['timestamp'], 'd/m/Y', '', 'Y-m-d H:i:s')) ?>
                    at <?= clean_page(convert_date($note['timestamp'], 'H:i', '', 'Y-m-d H:i:s')) ?>
                </b>
                <br/>
                <?= clean_page(nl2br($note['note'])) ?>
            </p>
            <?php
        }

        if (!empty($order->info['message'])) {
            ?>
            <b>Order Notes:</b>
            <p>
                <?= nl2br($order->info['message']) ?>
            </p>
            <?php
        }
        ?>
    </div> <!-- .ordersection -->

    <!-- Customer contact history -->
<?php
if (count($customer_contact_history = $order->getCustomerContactHistory()) > 0) {
    ?>

    <div class="divider el"></div>

    <div class="ordersection el orderitems">
        <h2>Customer contact history</h2>

        <?php
        if (!empty($customer_contact_history)) {
        ?>
        <ul class="customerContactHistory">
            <?php
            foreach ($customer_contact_history as $index => $contact_data) {
                ?>
                <li>
                    <div class="customerContactSubject">
                        <?= nl2br($contact_data['subject']) ?>
                    </div>
                    <div class="customerContactDate">
                        Message sent
                        on <?= clean_page(convert_date($contact_data['timestamp'], 'd/m/Y', '', 'Y-m-d H:i:s')) ?>
                        at <?= clean_page(convert_date($contact_data['timestamp'], 'H:i', '', 'Y-m-d H:i:s')) ?>
                    </div>
                    <div class="customerContactMessage">
                        <?= clean_page(nl2br(trim($contact_data['message']))) ?>
                    </div>
                </li>
                <?php
            }
            }
            ?>

            <div class="buttonGroup">
                <a href="order.contact.php?id=<?= clean_page($order->getId()) ?>" class="btn">
                    Send a new message
                </a>
            </div>
    </div>
    <?php
}
?>

    <div class="divider el"></div>

    <div class="ordersection el orderitems">
        <h2>Order items</h2>
        <?php
        $admin = true;
        $show_totals = true;

        require_once $path . 'shop/admin/orders/templates/order.basket.view.php';

        if ($order_eloquent->hasMagentoAssessment()) {
            require_once $path . 'shop/admin/orders/templates/order.assessment.magento.php';
        }

        $statusHistory = OrderStatusLog::query()
            ->where('order_id', '=', $order->getId())
            ->orderBy('id', 'desc')
            ->get();

        if ($statusHistory->count() > 0) {
            ?>
            <h2>Order status history</h2>
            <div class="form_bg">
                <?php
                $i = 0;
                foreach ($statusHistory as $statusHistoryRecord) {
                    $data = $statusHistoryRecord->toArray();
                    if ($i > 0) {
                        echo '<br/>';
                    }
                    ?>
                    <p>
                    <b>Status changed on <?= clean_page(date("d/m/Y", strtotime($data['timestamp']))) ?>
                        at <?= clean_page(date("H:i", strtotime($data['timestamp']))) ?></b><br/>
                    <?= clean_page($orders_statuses[$data['status']]) ?>
                    <?php
                    if ($data['status'] == \Mtc\Shop\Order::STATUS_SHIPPED) {
                        ?>
                        <br/>
                        <?php
                        $shipments = Shipment::query()
                            ->where('order_id', '=', $order->getId())
                            ->where('order_status_id', $data['id'])
                            ->get();

                        foreach ($shipments as $shipment) {
                            $data2 = $shipment->toArray();
                            if (!empty($data2['carrier'])) {
                                ?>
                                <b>Carrier:</b> <?= clean_page($data2['carrier']) ?><br/>
                                <?php
                            }

                            if (!empty($data2['service'])) {
                                ?>
                                <b>Service:</b> <?= clean_page($data2['service']) ?><br/>
                                <?php
                            }

                            if (!empty($data2['tracking_no'])) {
                                ?>
                                <b>Tracking no:</b> <?= clean_page($data2['tracking_no']) ?>
                                <?php
                            }

                            $shipmentItems = ShipmentItem::query()
                                ->where('order_shipment_id', '=', $data2['id'])
                                ->get();

                            if ($shipmentItems->count() > 0) {
                                ?>
                                <table>
                                    <tr>
                                        <th>Item</th>
                                        <th>Size</th>
                                        <th align="center">Quantity</th>
                                        <th>Price</th>
                                    </tr>
                                    <?php
                                    foreach ($shipmentItems as $shipmentItem) {
                                        $data3 = $shipmentItem->toArray();

                                        $orderItem = \Mtc\Shop\Order\Item::query()
                                            ->find($data3['order_item_id']);

                                        if (!empty($orderItem)) {
                                            ?>
                                            <tr>
                                                <td><?= clean_page($orderItem->item_name) ?> - <span
                                                            style="color:green;">shipped</span></td>
                                                <td><?= clean_page($orderItem->size) ?></td>
                                                <td align="center"><?= clean_page($orderItem->quantity) ?></td>
                                                <td><?= clean_page($orderItem->item_price) ?></td>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    ?>
                                </table>
                                <?php
                            }
                        }
                    }

                    if (in_array($data['status'], [
                            \Mtc\Shop\Order::STATUS_PART_REFUNDED,
                            \Mtc\Shop\Order::STATUS_REFUNDED,
                            ]
                        )
                    ) {
                        ?>
                        <br/>
                        <?php
                        $refund = Refund::query()
                            ->where('order_id', $order->getId())
                            ->with('items')
                            ->first();
                        ?>
                        <p>
                            <b>Reference:</b> <?= clean_page($refund->reference) ?>
                        </p>
                        <p>
                            <b>Note:</b> <?= clean_page($refund->note) ?>
                        </p>
                        <div class="row">
                            <p><strong>Details of refund:</strong></p>
                            <table>
                                <thead>
                                <tr>
                                    <th>Item</th>
                                    <th>Size</th>
                                    <th>Quantity</th>
                                    <th>Price</th>
                                    <th>Refunded</th>
                                </tr>
                                </thead>
                                <?php
                                $refund->items->each(function ($refund_item) {
                                    /** @var\Mtc\Plugins\Refunds\Classes\RefundItem $refund_item */
                                    ?>
                                    <tr>
                                        <td><?= clean_page($refund_item->orderItem->item_name) ?></td>
                                        <td><?= clean_page($refund_item->orderItem->size) ?></td>
                                        <td><?= clean_page($refund_item->quantity) ?></td>
                                        <td><?= clean_page($refund_item->orderItem->price_paid) ?></td>
                                        <td style="font-weight: bold; color:#ff0000;"><?= clean_page($refund_item->amount_refunded) ?></td>
                                    </tr>
                                    <?php

                                });

                                if ($refund->delivery_refund_amount > 0) {
                                    ?>
                                    <tr>
                                        <td>Delivery</td>
                                        <td></td>
                                        <td></td>
                                        <td>
                                            <?= clean_page($order->getDelivery()->cost) ?>
                                        </td>
                                        <td style="font-weight: bold; color:#ff0000;">
                                            <?= clean_page($refund->delivery_refund_amount) ?>
                                        </td>
                                    </tr>
                                    <?php
                                }
                                ?>
                            </table>

                        </div>
                        <?php
                    }
                    ?>
                    </p>
                    <?php
                    ++$i;
                }
                ?>
            </div>
            <?php
        }
        ?>

    </div><!-- end of order items -->

    <?php
    $originalBasket = $order_eloquent->basket()->with('items.shop_item')->first();
    $basketDiffersFromOrder = false;
    if ($originalBasket && $originalBasket->items->count() > 0) {
        $normalise = function ($items) {
            $rows = [];
            foreach ($items as $item) {
                $rows[] = [
                    'item_id' => (int) ($item['item_id'] ?? 0),
                    'sizeid' => (int) ($item['sizeid'] ?? 0),
                    'quantity' => (int) ($item['quantity'] ?? 0),
                ];
            }
            usort($rows, fn($a, $b) => [$a['item_id'], $a['sizeid']] <=> [$b['item_id'], $b['sizeid']]);
            return $rows;
        };
        $basketDiffersFromOrder = $normalise($originalBasket->items) !== $normalise($order->getItems());
    }

    if ($basketDiffersFromOrder) {
        ?>
        <div class="divider el"></div>

        <div class="ordersection el">
            <h2>Original basket (as ordered by customer)</h2>
            <p><em>The customer's original basket differs from the final order items above
                    (e.g. amended by the prescriber). Shown here for reference.</em></p>
            <div class="table-style-1">
                <table width="100%">
                    <tr class="row_heading">
                        <th style="text-align:left;" width="150">PLU</th>
                        <th style="text-align:left;">Name</th>
                        <th style="text-align:left;">Variation</th>
                        <th width="50">Quantity</th>
                    </tr>
                    <tbody>
                    <?php
                    foreach ($originalBasket->items as $basket_item) {
                        $basket_shop_item = $basket_item->shop_item;
                        ?>
                        <tr>
                            <td><?= clean_page($basket_item->PLU) ?></td>
                            <td><?= clean_page($basket_shop_item->name ?? '(item no longer available)') ?></td>
                            <td><?= strip_tags(urldecode((string) $basket_item->size), '<br>') ?></td>
                            <td style="text-align:center;"><?= clean_page($basket_item->quantity) ?></td>
                        </tr>
                        <?php
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php
    }
    ?>

    <div class="divider el"></div>

    <div class="ordersection el">
        <h2>Payment details</h2>

        <table>
            <tr>
                <td valign="top">
                    <?php
                    if (!empty($order->payment)) {
                        include($path . 'shop/admin/orders/templates/order.protx.php');
                    }

                    if (!empty($order->payment_paypal)) {
                        include($path . 'shop/admin/orders/templates/order.paypal.php');
                    }

                    if (!empty($order->payment_trade)) {
                        include($path . 'shop/admin/orders/templates/order.trade.php');
                    }

                    if (!empty($order->payment_worldpay)) {
                        include($path . 'shop/admin/orders/templates/order.worldpay.php');
                    }

                    if (!empty($order->payment_bank_of_ireland)) {
                        require_once($path . 'shop/admin/orders/templates/order.bank_of_ireland.php');
                    }

                    if (!empty($order->payment_realex)) {
                        require_once($path . 'shop/admin/orders/templates/order.realex.php');
                    }

                    if (!empty($order->payment_stripe)) {
                        require_once($path . 'shop/admin/orders/templates/order.stripe.php');
                    }

                    Judopay::displayPaymentDetails($order);

                    RyftPay::displayPaymentDetails($order);

                    if (!empty($order->coupon_code)) {
                        ?>
                        <h2>Coupon Code</h2>
                        <table>
                            <tr>
                                <td>Code Used</td>
                                <td><?= clean_page($order->coupon_code) ?></td>
                            </tr>
                            <tr>
                                <td>Free Delivery</td>
                                <td><?= ($order->coupon_freedelivery) ? "Yes" : "No"; ?></td>
                            </tr>
                            <tr>
                                <td>Amount Deducted</td>
                                <td><?= ($order->coupon_deduct > 0) ? printf("%.2f", $order->coupon_deduct) : "None"; ?></td>
                            </tr>
                        </table>
                        <?php
                    }
                    ?>
                </td>
            </tr>
        </table>
    </div>

    <div class="divider el"></div>

    <!-- PPC Tracking -->
<?php
$ref = $order->ref;
$keywords = $order->keywords;

if (!empty($ref)) {
    ?>
    <div class="ordersection el orderitems">
        <h2>PPC Tracking</h2>
        <p>
            <strong>Ref:</strong> <?= clean_page($ref) ?><br/>
            <strong>Keywords:</strong> <?= clean_page($keywords) ?><br/>
        </p>
    </div>
    <?php
}

require_once $path . 'core/admin/templates/adminfooter.html.php';
