<?php

namespace Modules\WhatsApp\Entities\Services;

use Modules\WhatsApp\Entities\WaTemplate;

/**
 * Seeds a business's starter WhatsApp templates. Idempotent — only creates a
 * template if one with that name doesn't already exist, so it's safe to call on
 * install, on first visit to the Templates/Settings pages, or before sending.
 *
 * Sales templates use the core {tag} engine (App\Utils\Util::replaceTags).
 * Appointment templates use the VetClinic appointment tags resolved by
 * WaNotifier::renderAppointment().
 */
class DefaultTemplates
{
    public static function defaults(): array
    {
        return [
            // ---- Sales / POS ----
            'invoice_created' => [
                'category'  => 'utility',
                'body'      => "🧾 *{business_name}*\n\n"
                             . "Hi {contact_name}, thank you for your purchase! 🙏\n\n"
                             . "*Invoice:* {invoice_number}\n"
                             . "*Total:* {total_amount}\n"
                             . "*Paid:* {paid_amount}\n"
                             . "*Balance due:* {due_amount}\n\n"
                             . "📄 View or download your invoice:\n{invoice_url}\n\n"
                             . "We appreciate your business — just reply to this message if you have any questions.",
                'variables' => ['business_name', 'contact_name', 'invoice_number', 'total_amount', 'paid_amount', 'due_amount', 'invoice_url'],
            ],
            'payment_received' => [
                'category'  => 'utility',
                'body'      => "✅ *Payment received* — {business_name}\n\n"
                             . "Hi {contact_name}, we've received your payment of *{received_amount}* for invoice {invoice_number}.\n\n"
                             . "*Remaining balance:* {due_amount}\n\n"
                             . "Thank you! Reply here if you need anything.",
                'variables' => ['business_name', 'contact_name', 'received_amount', 'invoice_number', 'due_amount'],
            ],
            'sale_return' => [
                'category'  => 'utility',
                'body'      => "↩️ *Return processed* — {business_name}\n\n"
                             . "Hi {contact_name}, your return for invoice {invoice_number} has been processed.\n\n"
                             . "*Updated balance:* {due_amount}\n\n"
                             . "Thank you for giving us the chance to help. Reply with any questions.",
                'variables' => ['business_name', 'contact_name', 'invoice_number', 'due_amount'],
            ],

            // ---- VetClinic appointments ----
            'appointment_booked' => [
                'category'  => 'utility',
                'body'      => "📅 *Appointment confirmed* — {clinic_name}\n\n"
                             . "Hi {owner_name}, the appointment for *{pet_name}* is booked:\n\n"
                             . "🗓 *Date:* {appointment_date}\n"
                             . "⏰ *Time:* {appointment_time}\n"
                             . "👨‍⚕️ *Doctor:* {doctor_name}\n"
                             . "📍 {location_name}\n"
                             . "Ref: {ref_no}\n\n"
                             . "Please arrive 10 minutes early. Reply to reschedule or cancel.",
                'variables' => ['clinic_name', 'owner_name', 'pet_name', 'appointment_date', 'appointment_time', 'doctor_name', 'location_name', 'ref_no'],
            ],
            'appointment_reminder' => [
                'category'  => 'utility',
                'body'      => "⏰ *Appointment reminder* — {clinic_name}\n\n"
                             . "Hi {owner_name}, a friendly reminder of *{pet_name}*'s appointment:\n\n"
                             . "🗓 {appointment_date} at ⏰ {appointment_time}\n"
                             . "👨‍⚕️ {doctor_name}\n"
                             . "📍 {location_name}\n\n"
                             . "See you soon! Reply to reschedule or cancel.",
                'variables' => ['clinic_name', 'owner_name', 'pet_name', 'appointment_date', 'appointment_time', 'doctor_name', 'location_name'],
            ],
            'appointment_cancelled' => [
                'category'  => 'utility',
                'body'      => "❌ *Appointment cancelled* — {clinic_name}\n\n"
                             . "Hi {owner_name}, the appointment for *{pet_name}* on {appointment_date} at {appointment_time} has been cancelled.\n\n"
                             . "Reply here to book a new time — we'd be happy to help.",
                'variables' => ['clinic_name', 'owner_name', 'pet_name', 'appointment_date', 'appointment_time'],
            ],
            'appointment_rescheduled' => [
                'category'  => 'utility',
                'body'      => "🔄 *Appointment rescheduled* — {clinic_name}\n\n"
                             . "Hi {owner_name}, the appointment for *{pet_name}* has been moved to:\n\n"
                             . "🗓 *{appointment_date}* at ⏰ *{appointment_time}*\n"
                             . "👨‍⚕️ {doctor_name}\n"
                             . "📍 {location_name}\n\n"
                             . "Reply if this time doesn't work for you.",
                'variables' => ['clinic_name', 'owner_name', 'pet_name', 'appointment_date', 'appointment_time', 'doctor_name', 'location_name'],
            ],
            'appointment_followup' => [
                'category'  => 'utility',
                'body'      => "💚 *Thank you for visiting* — {clinic_name}\n\n"
                             . "Hi {owner_name}, we hope *{pet_name}* is doing well after the visit with {doctor_name}.\n\n"
                             . "If you have any questions or concerns, just reply to this message — we're here to help. 🐾",
                'variables' => ['clinic_name', 'owner_name', 'pet_name', 'doctor_name'],
            ],

            // ---- Sales (additional) ----
            'quotation_sent' => [
                'category'  => 'utility',
                'body'      => "📝 *Your quotation* — {business_name}\n\n"
                             . "Hi {contact_name}, here is the quotation you requested.\n\n"
                             . "*Total:* {total_amount}\n\n"
                             . "📄 View the full quotation:\n{quote_url}\n\n"
                             . "Reply to confirm or if you'd like any changes.",
                'variables' => ['business_name', 'contact_name', 'total_amount', 'quote_url'],
            ],
            'payment_due_reminder' => [
                'category'  => 'utility',
                'body'      => "🔔 *Payment reminder* — {business_name}\n\n"
                             . "Hi {contact_name}, a friendly reminder that invoice {invoice_number} has an outstanding balance.\n\n"
                             . "*Amount due:* {due_amount}\n"
                             . "*Due date:* {due_date}\n\n"
                             . "📄 View invoice: {invoice_url}\n\n"
                             . "Please reply if you've already paid or need assistance. Thank you!",
                'variables' => ['business_name', 'contact_name', 'invoice_number', 'due_amount', 'due_date', 'invoice_url'],
            ],
            'shipment_status' => [
                'category'  => 'utility',
                'body'      => "🚚 *Delivery update* — {business_name}\n\n"
                             . "Hi {contact_name}, the status of your order {invoice_number} is now: *{shipping_status}*.\n\n"
                             . "Reply to this message if you have any questions.",
                'variables' => ['business_name', 'contact_name', 'invoice_number', 'shipping_status'],
            ],

            // ---- Purchasing (supplier-facing) ----
            'po_sent' => [
                'category'  => 'utility',
                'body'      => "📦 *Purchase Order* — {business_name}\n\n"
                             . "Hi {contact_name}, we've issued purchase order {order_ref_number}.\n\n"
                             . "*Total:* {total_amount}\n\n"
                             . "Please confirm receipt and expected delivery. Thank you for partnering with us.",
                'variables' => ['business_name', 'contact_name', 'order_ref_number', 'total_amount'],
            ],

            // ---- Lab ----
            'lab_results_ready' => [
                'category'  => 'utility',
                'body'      => "🔬 *Lab results ready* — {clinic_name}\n\n"
                             . "Hi {owner_name}, the lab results for *{pet_name}* (sample {sample_no}) are ready.\n\n"
                             . "Please contact the clinic or reply here to discuss the results with your veterinarian.",
                'variables' => ['clinic_name', 'owner_name', 'pet_name', 'sample_no'],
            ],

            // ---- Vet reminders / engagement ----
            'vaccination_due' => [
                'category'  => 'utility',
                'body'      => "💉 *Vaccination reminder* — {clinic_name}\n\n"
                             . "Hi {owner_name}, *{pet_name}*'s *{vaccine_name}* vaccination is due on *{due_date}*.\n\n"
                             . "Reply to book an appointment — keeping {pet_name} protected and healthy. 🐾",
                'variables' => ['clinic_name', 'owner_name', 'pet_name', 'vaccine_name', 'due_date'],
            ],
            // ---- Onboarding / welcome ----
            'contact_welcome' => [
                'category'  => 'marketing',
                'body'      => "👋 *Welcome to {business_name}!*\n\n"
                             . "Hi {contact_name}, thank you for joining us. We're glad to have you!\n\n"
                             . "You can reach us anytime by replying to this message. We're here to help. 🙌",
                'variables' => ['business_name', 'contact_name'],
            ],
            'pet_owner_welcome' => [
                'category'  => 'marketing',
                'body'      => "🐾 *Welcome to {clinic_name}!*\n\n"
                             . "Hi {owner_name}, thank you for trusting us with your pet's care. 💚\n\n"
                             . "We'll keep you updated about appointments, vaccinations and reminders right here on WhatsApp.\n"
                             . "Reply anytime — we're happy to help.",
                'variables' => ['clinic_name', 'owner_name'],
            ],
            'pet_welcome' => [
                'category'  => 'marketing',
                'body'      => "🎉🐾 *Welcome, {pet_name}!*\n\n"
                             . "Hi {owner_name}, *{pet_name}* has been added to your profile at {clinic_name}.\n\n"
                             . "We'll help you keep {pet_name} healthy with timely checkups, vaccinations and reminders.\n"
                             . "Reply anytime to book a visit. 💚",
                'variables' => ['clinic_name', 'owner_name', 'pet_name'],
            ],

            'pet_birthday' => [
                'category'  => 'marketing',
                'body'      => "🎉🐾 *Happy Birthday {pet_name}!* 🎂\n\n"
                             . "Hi {owner_name}, all of us at {clinic_name} are wishing *{pet_name}* a wonderful birthday!\n\n"
                             . "Thank you for trusting us with {pet_name}'s care. Reply for a birthday check-up. 💚",
                'variables' => ['clinic_name', 'owner_name', 'pet_name'],
            ],
        ];
    }

    /** Create any missing default templates for a business. */
    public static function ensure(int $businessId): void
    {
        foreach (self::defaults() as $name => $def) {
            $exists = WaTemplate::where('business_id', $businessId)->where('name', $name)->exists();
            if ($exists) {
                continue;
            }

            WaTemplate::create([
                'business_id' => $businessId,
                'name'        => $name,
                'language'    => 'en',
                'category'    => $def['category'],
                'meta_status' => 'none',
                'body'        => $def['body'],
                'variables'   => $def['variables'],
                'active'      => true,
            ]);
        }
    }
}
