<?php

namespace Mtc\Plugins\Clinic\Http\Controllers\Admin;

use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Mtc\Shop\Order;

/**
 * Class MemberOrderController
 * @package App\Http\Controllers
 */
class MemberOrderController extends ClinicController
{
    /**
     * Loads member attributes
     *
     * @param $id
     * @return JsonResponse
     */
    public function load($id): JsonResponse
    {
        $orders = Order::query()
            ->with('orders.items.item')
            ->with('items.item')
            ->where('member', $id)
            ->whereNull('parent_id')
            ->orderByDesc('id')
            ->get()
            ->map(function (Order $order) {
                $this->mapOrderData($order);
                foreach ($order->orders as $k => $subOrder) {
                    $this->mapOrderData($subOrder);
                    $order->orders[$k] = $subOrder;
                }
                return $order;
            });

        return response()->json([
            'orders' => $this->getFlatOrderArray($orders),
        ]);
    }

    /**
     * Map order fields
     *
     * @param Order $order
     * @return void
     */
    protected function mapOrderData(Order $order): void
    {
        $order->status = Order::$statuses[$order->status];
        $order->cost_total = number_format($order->cost_total, '2');
        $order->datetime = Carbon::parse($order->date)->format('d.m.Y H:i:s');
    }

    /**
     * Get flat array with orders and suborders
     *
     * @param $orders
     * @return array
     */
    protected function getFlatOrderArray($orders): array
    {
        $ordersArray = [];
        foreach ($orders as $order) {
            $subOrders = $order->orders;
            unset($order->orders);
            $ordersArray[] = $order;
            foreach ($subOrders as $subOrder) {
                $ordersArray[] = $subOrder;
            }
        }
        return $ordersArray;
    }
}
