<?php

use Illuminate\Support\Facades\Event;
use Mtc\Shop\Events\OrderPaidEvent;

Event::listen(OrderPaidEvent::class, function(OrderPaidEvent $event) {
    // Get a nice Eloquent order class.
    /** @var \Mtc\Shop\Order $order */
    $order = \Mtc\Shop\Order::query()->find($event->getOrder()->getId());

    // We don't care if we don't have any prescriptions, so return if that's the case.
    if ($order->items->where('PLU', 'private_prescription')->isEmpty()) {
        return;
    }

    // Mark this as 'Pending Review'
    $event->getOrder()->updateStatus(\Mtc\Shop\Order::STATUS_PROCESSING);

    // Loop through the orders matching the name to the prescriptions
    $order->items->where('PLU', 'private_prescription')
        ->each(function ($order_item) {
            // Delete the original items
            /** @var \Mtc\Shop\Item $item */
            $item = \Mtc\Shop\Item::query()
                ->where('hidden', 1)
                ->where('id', $order_item->item_id)
                ->first();

            if ($item) {
                $item->sizes()->delete();
                $item->delete();
            }
        });

});
