<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder;

class Resep extends Model
{
    protected $fillable = [
        'no_resep',
        'user_id',
        'nama_dokter',
        'no_sip',
        'jenis_penjamin',
        'jenis_layanan',
        'nama_pasien',
        'no_rm',
        'umur_pasien',
        'berat_badan',
        'alamat_pasien',
        'jenis_kelamin',
        'tanggal_resep',
        'diagnosa',
        'catatan',
        'status',
        'is_read',
    ];

    protected $casts = [
        'tanggal_resep' => 'date',
        'berat_badan' => 'decimal:2',
        'is_read' => 'boolean',
    ];

    /**
     * Relasi ke User (Dokter yang membuat resep)
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Alias untuk dokter
     */
    public function dokter(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Relasi ke item-item resep
     */
    public function items(): HasMany
    {
        return $this->hasMany(ResepItem::class);
    }

    /**
     * Generate nomor resep otomatis
     */
    public static function generateNoResep(): string
    {
        $today = now()->format('Ymd');
        $lastResep = self::whereDate('created_at', today())
            ->orderBy('id', 'desc')
            ->first();

        if ($lastResep) {
            $lastNumber = (int) substr($lastResep->no_resep, -4);
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        return 'RSP-' . $today . '-' . str_pad($newNumber, 4, '0', STR_PAD_LEFT);
    }

    /**
     * Get status badge color
     */
    public function getStatusColorAttribute(): string
    {
        return match($this->status) {
            'selesai' => 'terkirim',
            'proses' => 'proses',
            'dibatalkan' => 'dibatalkan',
            default => 'proses',
        };
    }

    /**
     * Scope for unread prescriptions
     */
    public function scopeUnread(Builder $query): Builder
    {
        return $query->where('is_read', false);
    }

    /**
     * Mark prescription as read
     */
    public function markAsRead(): void
    {
        if (!$this->is_read) {
            $this->update(['is_read' => true]);
        }
    }
}

