<?php
$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
ini_set('memory_limit', '1024M');
$page_meta['title'] = 'Print Orders';

$order_ids = explode(',', $_REQUEST['order_ids']);

if (empty($order_ids)) {
    header('Location: /shop/admin/orders/manage.orders.php');
    exit();
}

if (request()->input('action') === 'save') {
    collect(request()->input('pharmacy_label_text'))
        ->each(function ($label_text, $order_item_id): void {
            \Mtc\Shop\Order\Item::query()
             ->where('id', $order_item_id)
             ->update([
                 'pharmacy_label_text' => $label_text
             ]);
        });
    header('Location: ' . request()->getRequestUri());
    exit();
}

if (filter_input(INPUT_GET, 'action') === 'print_prescriptions') {
    echo Order::batchPrescriptions($order_ids, $basket_countries, $twig);
    exit();
}

if (filter_input(INPUT_GET, 'action') === 'print_split_labels') {
    echo Order::batchSplitSideLabels($order_ids, $basket_countries, $twig);
    exit();
}

if (filter_input(INPUT_GET, 'action') === 'print_pharmacy_labels_multi') {
    echo Order::batchPharmacyLabelsPDF2($order_ids, $twig);
    exit();
}

$orders = \Mtc\Shop\Order::query()
    ->whereIn('id', $order_ids)
    ->with(['items.item', 'delivery.service'])
    ->get()
    ->map(function ($order) {
        $order->dx_order = false;
        return $order;
    });

$prescriptions_to_print = $orders->filter(function ($order) {
        return $order->items()->whereHas('approval')->exists();
    })->count() > 0;

$pharmacy_labels_to_print = true;

$twig->display('shop/admin/orders/optimized.twig', [
    'orders' => $orders,
    'page_meta' => $page_meta,
    'order_ids' => collect($order_ids),
    'request' => request(),
    'prescriptions_to_print' => $prescriptions_to_print,
    'pharmacy_labels_to_print' => $pharmacy_labels_to_print,
]);
