<?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
    {
        // Fetch only top-level orders + their sub-orders and the minimal item fields
        $orders = Order::query()
            ->where('member', $id)
            ->whereNull('parent_id')
            ->orderByDesc('id')
            ->with([
                'items' => function ($q) {
                    $q->select([
                        'id','order_id','item_name','quantity','size','approved','clinic_checked'
                    ]);
                },
                'orders' => function ($q) {
                    $q->select([
                        'id','parent_id','paid','status','date','cost_total','member'
                    ])->with(['items' => function ($iq) {
                        $iq->select([
                            'id','order_id','item_name','quantity','size','approved','clinic_checked'
                        ]);
                    }]);
                },
            ])
            ->get(['id','parent_id','paid','status','date','cost_total','member']);

        // Flatten and transform (top-level + sub-orders)
        $flat = [];
        foreach ($orders as $order) {
            $flat[] = $this->transformOrderForUi($order);
            foreach ($order->orders as $sub) {
                $flat[] = $this->transformOrderForUi($sub);
            }
        }

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

    protected function transformOrderForUi(Order $o): array
    {
        return [
            'id'         => (int) $o->id,
            'parent_id'  => $o->parent_id ? (int) $o->parent_id : null,

            // Keep both for the UI: label for display, id for strict checks (e.g. === 8)
            'status'     => Order::$statuses[$o->status] ?? (string) $o->status, // label
            'status_id'  => (int) $o->status,                                    // numeric

            'paid'       => (int) $o->paid,  // UI uses "!order.paid"

            'datetime'   => Carbon::parse($o->date)->format('d.m.Y H:i:s'),
            'cost_total' => number_format((float) $o->cost_total, 2, '.', ''),

            // Minimal item fields used by the table
            'items' => $o->items->map(function ($it) {
                return [
                    'id'             => (int) $it->id,
                    'quantity'       => (int) $it->quantity,
                    'item_name'      => (string) $it->item_name,
                    'size'           => (string) ($it->size ?? ''),
                    'approved'       => is_null($it->approved) ? null : (int) $it->approved, // 1 approved, 2 rejected
                    'clinic_checked' => (bool) $it->clinic_checked,
                ];
            })->values()->all(),
        ];
    }

    /**
     * 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;
    }
}
