<?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) {
            \Mtc\Shop\Order\Item::query()
             ->where('id', $order_item_id)
             ->update([
                 'pharmacy_label_text' => $label_text
             ]);
        });
    header('Location: ' . request()->getRequestUri());
    exit();
}

if (request()->input('action') === 'save_label_settings') {
    if (! $adminuser->isMtcAdmin()) {
        http_response_code(403);
        exit('Forbidden');
    }
    if (! CSRF::checkToken('label_settings')) {
        http_response_code(403);
        exit('Invalid CSRF token');
    }
    Order::saveLabelSettings((array) request()->input('label_settings', []));
    header('Location: /shop/admin/orders/optimized_print.php?order_ids=' . urlencode(implode(',', $order_ids)));
    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();
}

if (filter_input(INPUT_GET, 'action') === 'preview_pharmacy_label') {
    if (! $adminuser->isMtcAdmin()) {
        http_response_code(403);
        exit('Forbidden');
    }
    echo Order::previewSampleLabel($twig);
    exit();
}

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

$prescriptions_to_print = $orders->contains(function ($order) {
    return $order->items->contains(function ($item) {
        return !empty($item->approval);
    });
});

$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,
    'is_mtc_admin' => $adminuser->isMtcAdmin(),
    'label_settings' => Order::loadLabelSettings(),
]);
