<?php

namespace App\Modules\Clinical\Services;

use App\Core\Base\BaseService;
use App\Models\Prescription;
use Barryvdh\DomPDF\Facade\Pdf;

class PrescriptionService extends BaseService
{
    public function generatePdf(int|string $prescriptionId)
    {
        $prescription = Prescription::with(['encounter.patient', 'encounter.visit.chamber'])->findOrFail($prescriptionId);

        $pdf = Pdf::loadView('prescriptions.pdf', [
            'prescription' => $prescription,
            'encounter' => $prescription->encounter,
            'patient' => $prescription->encounter->patient
        ]);

        return $pdf->download("Prescription-{$prescription->encounter->patient->patient_id}.pdf");
    }

    public function getWhatsAppLink(Prescription $prescription): string
    {
        $patient = $prescription->encounter->patient;
        $phone = $patient->phone;
        // Clean phone number
        $phone = preg_replace('/[^0-9]/', '', $phone);
        if (strlen($phone) == 11 && str_starts_with($phone, '0')) {
            $phone = '88' . $phone;
        }

        $message = urlencode("Hello {$patient->name}, your prescription has been generated. View it here: " . url("/prescriptions/view/{$prescription->id}"));

        return "https://wa.me/{$phone}?text={$message}";
    }
}
