<?php

namespace Modules\VetAdmission\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetAdmission\Entities\Services\AdmissionBillingService;
use Modules\VetAdmission\Entities\VaAdmission;
use Modules\VetAdmission\Entities\VaAdmissionFluid;
use Modules\VetAdmission\Entities\VaAdmissionMedication;
use Modules\VetAdmission\Entities\VaDischargeTemplate;

/**
 * Discharge wizard: shows the current draft invoice + lets staff pick a
 * take-home template, generate the meds-to-go list, set a follow-up date,
 * and finalise. Finalising posts any remaining billable events, flips the
 * ERP sell to final, and stamps the admission.
 */
class VaDischargeController extends Controller
{
    private function biz() { return request()->session()->get('user.business_id'); }

    /** Wizard preview screen — review charges + pick template. */
    public function show(Request $request, $admissionId)
    {
        if (!auth()->user()->can('vet_admission.manage_admissions')) abort(403);

        $admission = VaAdmission::with(['pet', 'owner'])
            ->forBusiness((int) $this->biz())->findOrFail($admissionId);

        $templates = VaDischargeTemplate::forBusiness((int) $this->biz())
            ->where('status', 'active')
            ->where(function ($q) use ($admission) {
                $q->whereNull('species');
                if (optional($admission->pet)->species) {
                    $q->orWhere('species', strtolower($admission->pet->species));
                }
            })->orderBy('name')->get();

        $medications = VaAdmissionMedication::where('admission_id', $admission->id)->get();
        $fluids      = VaAdmissionFluid::where('admission_id', $admission->id)->get();

        return view('vetAdmission::admissions.discharge', compact('admission', 'templates', 'medications', 'fluids'));
    }

    /** AJAX: render a template body against the admission's vars. */
    public function preview(Request $request, $admissionId)
    {
        if (!auth()->user()->can('vet_admission.manage_admissions')) abort(403);
        $request->validate(['template_id' => 'required|integer', 'follow_up_date' => 'nullable|date', 'summary' => 'nullable|string']);

        $admission = VaAdmission::with(['pet', 'owner'])->forBusiness((int) $this->biz())->findOrFail($admissionId);
        $template  = VaDischargeTemplate::forBusiness((int) $this->biz())->findOrFail($request->template_id);

        $meds = VaAdmissionMedication::where('admission_id', $admission->id)->get()
            ->map(fn($m) => "• {$m->medicine_name} ({$m->route}) — q{$m->frequency_hours}h")
            ->implode("\n");

        $business = \App\Business::find($admission->business_id);

        $rendered = VaDischargeTemplate::render($template->body ?? '', [
            'pet.name'           => optional($admission->pet)->petname ?? '',
            'owner.name'         => optional($admission->owner)->name ?? '',
            'follow_up_date'     => $request->follow_up_date ? Carbon::parse($request->follow_up_date)->format('d M Y') : '',
            'discharge_summary'  => $request->summary ?: '',
            'medications_list'   => $meds,
            'clinic_name'        => optional($business)->name ?? '',
            'admission_no'       => $admission->admission_no,
            'today'              => now()->format('d M Y'),
        ]);

        return response()->json(['success' => true, 'rendered' => $rendered]);
    }

    /**
     * Finalise discharge: persists summary + final discharge timestamp,
     * posts any remaining daily-stay days, and finalises the draft sell.
     */
    public function finalise(Request $request, $admissionId)
    {
        if (!auth()->user()->can('vet_admission.manage_admissions')) abort(403);
        $request->validate([
            'discharged_at'     => 'required|date',
            'discharge_summary' => 'nullable|string',
            'status'            => 'required|in:discharged,transferred,deceased',
        ]);

        $admission = VaAdmission::forBusiness((int) $this->biz())->findOrFail($admissionId);
        if ($admission->status !== 'admitted') {
            return response()->json(['success' => false, 'msg' => 'Admission is already closed.'], 422);
        }

        $admission->update([
            'status'            => $request->status,
            'discharged_at'     => $request->discharged_at,
            'discharge_summary' => $request->discharge_summary,
        ]);

        $billing = app(AdmissionBillingService::class);
        // Top up daily-stay charges to discharge date if applicable
        $billing->postDailyStay($admission, Carbon::parse($request->discharged_at));
        $trx = $billing->finaliseDischarge($admission);

        return response()->json([
            'success'    => true,
            'msg'        => 'Discharge finalised. Invoice ready.',
            'sell_id'    => $trx?->id,
            'invoice_no' => $trx?->invoice_no,
        ]);
    }
}
