<?php

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

    use Carbon\Carbon;
    use Illuminate\Http\JsonResponse;
    use Illuminate\Http\Request;
    use Mtc\Core\Admin\User;
    use Mtc\Plugins\Clinic\Src\Logger;
    use Mtc\Plugins\Clinic\Src\Models\Treatment;

    class TreatmentController extends ClinicController
    {
        /**
         * Load entries – minimal payload only.
         */
        public function load($id): JsonResponse
        {
            $treatments = Treatment::query()
                ->where('member_id', $id)
                // load only the columns we need from treatments
                ->select(['id', 'member_id', 'item_id', 'size_id', 'date_from', 'date_to', 'notes', 'created_at', 'updated_at'])
                ->with([
                    // load only id+name for item (don’t pull heavy relations)
                    'item:id,name',
                ])
                ->orderByDesc('date_from')
                ->get()
                ->map(function (Treatment $treatment) {
                    return [
                        'id'         => $treatment->id,
                        'member_id'  => $treatment->member_id,
                        'item_id'    => $treatment->item_id,
                        'size_id'    => $treatment->size_id,
                        'notes'      => $treatment->notes,
                        'date_from'  => $treatment->date_from ? Carbon::parse($treatment->date_from)->format('d/m/Y') : null,
                        'date_to'    => $treatment->date_to   ? Carbon::parse($treatment->date_to)->format('d/m/Y')   : null,
                        'product'    => optional($treatment->item)->name, // what the UI shows
                        'status'     => $treatment->getStatus(),
                    ];
                })
                ->values();

            return response()->json(['treatments' => $treatments]);
        }

        /**
         * Creates / updates entry in database
         */
        public function store($id, Request $request): JsonResponse
        {
            $data = $request->all();
            $data['member_id'] = $id;

            if ($errors = Treatment::validate($data)) {
                return response()->json(['errors' => $errors]);
            }

            /** @var Treatment $treatment */
            $treatment = Treatment::query()->firstOrNew([
                'id'        => $request->input('id'),
                'member_id' => $id,
            ]);

            // Parse dates (allow empty date_to)
            $data['date_from'] = Carbon::createFromFormat('d/m/Y', $data['date_from'])->format('Y-m-d');
            $data['date_to']   = !empty($data['date_to'])
                ? Carbon::createFromFormat('d/m/Y', $data['date_to'])->format('Y-m-d')
                : null;

            $action = !empty($treatment->id) ? Logger::ACTION_UPDATED : Logger::ACTION_CREATED;

            $treatment->fill($data);
            $treatment->save();

            // Load only what we need for logging (prevents heavy load)
            $treatment->loadMissing(['item:id,name', 'size:id,size']);

            $details = [
                'item_name' => optional($treatment->item)->name,
            ];
            if (!empty($treatment->size)) {
                $details['variation'] = $treatment->size->size;
            }

            (new Logger($treatment, User::getAdminUser(), $id))
                ->log(Logger::TREATMENT, $action, array_merge($treatment->toArray(), $details));

            return response()->json(['success' => 'Data saved successfully!']);
        }

        /**
         * Deletes entry in database
         */
        public function delete($id, Request $request): JsonResponse
        {
            /** @var Treatment $treatment */
            $treatment = Treatment::query()
                ->where('id', $request->input('id'))
                ->where('member_id', $id)
                ->firstOrFail();

            // Load only minimal relation data for logging
            $treatment->loadMissing(['item:id,name', 'size:id,size']);

            $details = [
                'item_name' => optional($treatment->item)->name,
            ];
            if (!empty($treatment->size)) {
                $details['variation'] = $treatment->size->size;
            }

            (new Logger($treatment, User::getAdminUser(), $id))
                ->log(Logger::TREATMENT, Logger::ACTION_DELETED, array_merge($treatment->toArray(), $details));

            $treatment->delete();

            return response()->json(['success' => 'Data deleted successfully!']);
        }
    }
