<?php

namespace Modules\ClinicCore\Entities\Services;

use Modules\ClinicCore\Entities\ClcPrescription;
use Carbon\Carbon;

class PrescriptionService
{
    public function generateRefNo(): string
    {
        return 'RX-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -5));
    }

    public function getActivePrescriptions(int $businessId, int $patientId): \Illuminate\Database\Eloquent\Collection
    {
        return ClcPrescription::with(['doctor', 'items'])
            ->where('business_id', $businessId)
            ->where('patient_id', $patientId)
            ->where('status', 'active')
            ->where(function ($q) {
                $q->whereNull('valid_until')
                  ->orWhere('valid_until', '>=', Carbon::today());
            })
            ->orderBy('prescribed_date', 'desc')
            ->get();
    }

    public function expireOldPrescriptions(int $businessId): int
    {
        return ClcPrescription::where('business_id', $businessId)
            ->where('status', 'active')
            ->whereNotNull('valid_until')
            ->where('valid_until', '<', Carbon::today())
            ->update(['status' => 'completed']);
    }
}
