<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Migrations\Migration;

/**
 * Seeds system-default discharge templates (business_id NULL — available
 * to every clinic). Each template uses the merge tags supported by
 * VaDischargeTemplate::render():
 *   {{pet.name}}, {{owner.name}}, {{clinic_name}}, {{admission_no}},
 *   {{today}}, {{follow_up_date}}, {{discharge_summary}},
 *   {{medications_list}}
 *
 * Re-running the migration is safe — each template is keyed by name and
 * skipped if already present.
 */
class SeedDefaultDischargeTemplates extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('va_discharge_templates')) return;

        $seeds = [
            [
                'name'    => 'Standard discharge — general',
                'species' => null,
                'body'    => "Dear {{owner.name}},

{{pet.name}} was admitted to {{clinic_name}} under reference {{admission_no}} and has now been cleared for discharge.

CLINICAL SUMMARY
{{discharge_summary}}

MEDICATIONS TO CONTINUE AT HOME
{{medications_list}}

HOME CARE
• Rest in a quiet area for the next 48 hours.
• Offer small, frequent meals and free access to clean water.
• Monitor appetite, water intake, urination and bowel movements daily.
• Restrict strenuous activity until cleared by the veterinarian.

WHEN TO CALL US IMMEDIATELY
• Refusal to eat or drink for more than 24 hours
• Repeated vomiting or diarrhoea
• Lethargy, collapse, or laboured breathing
• Bleeding from any wound or surgical site
• Sudden change in behaviour

FOLLOW-UP
A re-check appointment has been scheduled for {{follow_up_date}}.
Please call {{clinic_name}} on the number on this discharge sheet if you cannot keep it or have any concerns.

Thank you for trusting us with {{pet.name}}'s care.

{{clinic_name}}
{{today}}",
            ],
            [
                'name'    => 'Post-operative discharge',
                'species' => null,
                'body'    => "Dear {{owner.name}},

{{pet.name}} has recovered from anaesthesia and is being discharged following the procedure performed today at {{clinic_name}} (admission {{admission_no}}).

WHAT WE DID
{{discharge_summary}}

MEDICATIONS PRESCRIBED
{{medications_list}}

WOUND / SURGICAL SITE CARE
• Check the incision twice daily for redness, swelling, discharge or the wound opening.
• Keep the area clean and DRY — no bathing for 10 days.
• Use the e-collar (cone) AT ALL TIMES to prevent licking, including overnight.
• Do not allow {{pet.name}} to scratch or chew at sutures.

ACTIVITY RESTRICTION (10–14 days)
• Lead-walks only for toilet breaks — no free running, jumping, stairs, or play.
• Crate or small-room confinement when unsupervised.
• Use a harness rather than a collar if there are neck/throat sutures.

DIET
• Offer a small amount of bland food (boiled chicken + rice / prescription recovery diet) this evening.
• Return to the normal diet tomorrow if there is no vomiting.

CALL US URGENTLY IF YOU SEE
• The incision opening, bleeding, or discharging pus
• Persistent vomiting, refusal to eat, or marked lethargy after 24 hours
• Significant pain not relieved by the prescribed analgesia

SUTURE REMOVAL / RE-CHECK
{{follow_up_date}} — please bring {{pet.name}} back for wound assessment and suture removal.

{{clinic_name}}
{{today}}",
            ],
            [
                'name'    => 'GI illness recovery (vomiting / diarrhoea)',
                'species' => null,
                'body'    => "Dear {{owner.name}},

{{pet.name}} has responded well to treatment and is well enough to continue recovery at home (admission {{admission_no}}, {{clinic_name}}).

WHAT WE TREATED
{{discharge_summary}}

MEDICATIONS TO GIVE
{{medications_list}}

FEEDING THE NEXT 5 DAYS
1. TODAY — Offer 1–2 tablespoons of a bland diet (boiled white chicken + plain rice, or the prescription GI diet provided) every 2–3 hours.
2. TOMORROW — Increase portion size if tolerated; still little and often.
3. DAYS 3–5 — Gradually mix the normal food back in (25% → 50% → 75% → 100%).
4. Offer water freely but in small amounts at a time to avoid triggering vomiting.

WATCH OUT FOR
• More than one vomit in 24 hours after discharge
• Diarrhoea lasting beyond 48 hours, or containing fresh blood
• Refusal to drink water
• Marked lethargy, weakness, or pale gums

CALL THE CLINIC IMMEDIATELY if any of the above appear.

FOLLOW-UP
{{follow_up_date}} — please bring {{pet.name}} back for a recovery check.

{{clinic_name}}
{{today}}",
            ],
            [
                'name'    => 'In-patient parvovirus / severe infection (canine)',
                'species' => 'canine',
                'body'    => "Dear {{owner.name}},

{{pet.name}} has been treated at {{clinic_name}} for a severe infection requiring inpatient support (admission {{admission_no}}) and is now stable enough to recover at home.

WHAT WE TREATED
{{discharge_summary}}

MEDICATIONS — IMPORTANT
{{medications_list}}

ISOLATION
• Parvovirus and similar pathogens are shed for several weeks. Keep {{pet.name}} away from other dogs, especially puppies, for the next 4 weeks.
• Clean food/water bowls and bedding daily with a 1:30 dilution of household bleach.
• Discard or thoroughly disinfect any toys or fabric items the dog used while sick.
• Disinfect floors and crates with the same bleach dilution; allow 10 minutes of contact time.

HOME CARE
• Continue small frequent meals of the prescription recovery diet for 7 days.
• Offer water but watch for return of vomiting.
• Crate rest with short, lead-only toilet trips for 5 days.

CALL US IMMEDIATELY IF
• Vomiting or diarrhoea returns
• {{pet.name}} stops drinking water
• Marked lethargy, collapse, or pale gums
• Blood appears in stool or vomit

FOLLOW-UP
{{follow_up_date}} — recheck visit. Please also confirm/complete the vaccination schedule once recovery is full.

{{clinic_name}}
{{today}}",
            ],
            [
                'name'    => 'URI / cat-flu recovery (feline)',
                'species' => 'feline',
                'body'    => "Dear {{owner.name}},

{{pet.name}} has improved enough to continue recovery at home after treatment for upper respiratory infection at {{clinic_name}} (admission {{admission_no}}).

WHAT WE TREATED
{{discharge_summary}}

MEDICATIONS
{{medications_list}}

HOME CARE
• Keep {{pet.name}} indoors and warm; rest is the most important treatment.
• Wipe the eyes and nose gently with a soft cloth dampened in warm water two to three times a day.
• Offer strongly-scented food slightly warmed — cats with blocked noses won't eat what they can't smell.
• Provide a quiet, low-traffic spot to rest, away from other cats if possible (URI is contagious to other cats).
• Encourage water intake — wet food, water fountains, or chicken broth (no onion / garlic).

CALL US IF
• {{pet.name}} stops eating for more than 24 hours
• Breathing becomes laboured or noisy
• Eyes become red, swollen, or have thick discharge
• Lethargy worsens rather than improves

FOLLOW-UP
{{follow_up_date}} — recheck and, if applicable, complete the vaccination schedule.

{{clinic_name}}
{{today}}",
            ],
            [
                'name'    => 'Diabetic stabilisation discharge',
                'species' => null,
                'body'    => "Dear {{owner.name}},

{{pet.name}} has been stabilised on insulin during this admission ({{admission_no}}) and is now ready to continue daily management at home.

WHAT WE DID
{{discharge_summary}}

INSULIN & MEDICATIONS
{{medications_list}}

DAILY MANAGEMENT
• Give insulin AT THE SAME TIMES every day, immediately AFTER {{pet.name}} has eaten the meal we discussed.
• Always store insulin in the fridge; roll the vial gently before drawing up — do NOT shake.
• Use a fresh needle every time.
• Feed the prescribed diet ONLY — no table scraps, no treats unless they are diabetic-safe.

GLUCOSE MONITORING
• Watch for signs of LOW blood sugar (weakness, wobbliness, drooling, seizure). If you see any: rub honey or syrup on the gums and call the clinic immediately.
• Watch for signs of HIGH blood sugar (excess thirst, excess urination, weight loss). Call the clinic if these return.
• Keep a simple log of meals, insulin dose, and any signs noted.

CALL US RIGHT AWAY IF
• {{pet.name}} refuses food (do NOT give insulin on an empty stomach without checking with us)
• Any vomiting, diarrhoea, weakness, or collapse
• Sudden change in behaviour, drinking, or urination

FOLLOW-UP
{{follow_up_date}} — glucose curve / re-check. Long-term diabetic care requires regular adjustments; please keep this appointment.

{{clinic_name}}
{{today}}",
            ],
            [
                'name'    => 'Boarding stay — courtesy summary',
                'species' => null,
                'body'    => "Dear {{owner.name}},

Thank you for entrusting {{pet.name}} to {{clinic_name}} during their boarding stay ({{admission_no}}).

STAY SUMMARY
{{discharge_summary}}

ITEMS GOING HOME
{{medications_list}}

OBSERVATIONS DURING THE STAY
• Appetite, water intake, urination and bowel movements were monitored daily. No abnormalities were noted unless specifically mentioned above.
• Any medications given during the stay are listed above. Continue them at home until finished or instructed otherwise.

AT HOME
• Expect {{pet.name}} to be tired for 24–48 hours after a stay — this is normal.
• Offer the usual diet in smaller portions tonight and return to the normal routine tomorrow.
• Watch for any changes in appetite, behaviour or stool over the next 3 days and let us know.

NEXT VISIT
{{follow_up_date}} — your next planned appointment.

We look forward to seeing {{pet.name}} again.

{{clinic_name}}
{{today}}",
            ],
            [
                'name'    => 'Deceased pet — condolence letter',
                'species' => null,
                'body'    => "Dear {{owner.name}},

It is with great sadness that we write to confirm the passing of {{pet.name}} at {{clinic_name}} (admission {{admission_no}}).

CIRCUMSTANCES
{{discharge_summary}}

ARRANGEMENTS
• If you have chosen cremation, the practice will contact you when {{pet.name}}'s ashes are ready for collection.
• If you have chosen home burial or another arrangement, please follow the instructions provided to you in person at the clinic.

WE ARE HERE FOR YOU
The loss of a beloved companion is profoundly painful. Please do not hesitate to contact the clinic if you have any further questions about the care provided, or if there is anything we can do to support you at this time.

With our deepest condolences,
{{clinic_name}}
{{today}}",
            ],
        ];

        $now = now();
        foreach ($seeds as $s) {
            $exists = DB::table('va_discharge_templates')
                ->whereNull('business_id')
                ->where('name', $s['name'])
                ->exists();
            if ($exists) continue;

            DB::table('va_discharge_templates')->insert([
                'business_id' => null,
                'name'        => $s['name'],
                'species'     => $s['species'],
                'body'        => $s['body'],
                'status'      => 'active',
                'created_at'  => $now,
                'updated_at'  => $now,
            ]);
        }
    }

    public function down()
    {
        if (!Schema::hasTable('va_discharge_templates')) return;

        DB::table('va_discharge_templates')
            ->whereNull('business_id')
            ->whereIn('name', [
                'Standard discharge — general',
                'Post-operative discharge',
                'GI illness recovery (vomiting / diarrhoea)',
                'In-patient parvovirus / severe infection (canine)',
                'URI / cat-flu recovery (feline)',
                'Diabetic stabilisation discharge',
                'Boarding stay — courtesy summary',
                'Deceased pet — condolence letter',
            ])->delete();
    }
}
