<?php

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

use Mtc\Core\Models\CountryState;
use Mtc\Shop\OrderStatusEmailText;

$order_id = null;

if (!empty($_REQUEST['order_id']) && is_numeric($_REQUEST['order_id'])) {
    $order_id = $_REQUEST['order_id'];
}

if(empty($order_id)) {
    $temp_order = \Mtc\Shop\Order::query()
        ->where('status', '=', $_REQUEST['id'])
        ->orderBy('id', 'desc')
        ->first()
    ;

    if ($temp_order) {
        $order_id = $temp_order->id;
    }
}

if (! $order_id) {
    exit('No orders available');
}

$order = Order::getById($order_id);

$preorder = false;

// Items

$line_items = $order->getItems();

foreach ($order->getItems() as $order_item_id => $i) {

    $line_item = new Item();
    $line_item->Get_Item($i['item_id']);

    if (!empty($line_item->images[$line_item->image_default]['name'])) {
        $line_items[$order_item_id]['item_image'] = SITE_URL . $image_folders['product_folders']['thumbs']['path'] . $line_item->images[$line_item->image_default]['name'];
    }

    $line_items[$order_item_id]['epos_code'] = $line_item->epos_code;

}

$tracking_no = '';
if ((int)$_REQUEST['id'] === \Mtc\Shop\Order::STATUS_SHIPPED) {
    $shipment = $order->eloquent()
        ->shipments()
        ->where('tracking_no', '!=', '')
        ->first();
    if (!empty($shipment)) {
        $tracking_no = $shipment->tracking_no;
    }
}

$options = [
    'order' => $order, // order details
    'line_items' => $line_items, // Order items with additional up to date information pulled from the item class
    'cost_subtotal' => $order->getSubtotalCost(),
    'order_subtotal' => $order->getSubtotalCost(),
    'vat_cost' => $order->getVatCost(), // Total VAT cost of the order
    'order_date' => $order->getOrderDate('Y-m-d H:i:s'), // order date sent in full... twig can re-render into any date format from here
    'delivery_cost' => $order->getDelivery()->cost, // Delivery Cost
    'delivery_name' => $order->getDelivery()->name, // Delivery Name
    'order_status_text' => $order->getOrderStatusText($_REQUEST['id']), // Order status text as defined in admin under shop/order status text
    'countries' => $countries,
    'tracking_no' => $tracking_no,
    'state_list' => CountryState::getCountryStateList(),
    'order_total' => $order->getTotalCost(), // orders total cost
];

echo $twig->render($status_send_mail[$_REQUEST['id']], $options);
