<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\Auditable;

class Budget extends Model
{
    use SoftDeletes, Auditable;

    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'id',
        'code',
        'patients_id',
        'total',
        'status',
        'notes',
        'tax_percentage',
        'tax_amount',
        'total_with_tax',
        'created_by'
    ];

    protected $casts = [
        'total' => 'decimal:2',
        'tax_percentage' => 'decimal:2',
        'tax_amount' => 'decimal:2',
        'total_with_tax' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    public function patient()
    {
        return $this->belongsTo("App\Models\Patients", 'patients_id');
    }

    public function items()
    {
        return $this->hasMany("App\Models\BudgetItem", 'budget_id');
    }

    public function creator()
    {
        return $this->belongsTo("App\Models\User", 'created_by');
    }

    public function calculateTotal()
    {
        // Calcular subtotal
        $this->total = $this->items()->sum('subtotal');
        
        // Calcular impuesto
        $this->tax_amount = $this->total * ($this->tax_percentage / 100);
        
        // Calcular total con impuesto
        $this->total_with_tax = $this->total + $this->tax_amount;
        
        $this->save();
    }

    public static function generateCode()
    {
        $prefix = 'PRE-';
        $date = now()->format('Ymd');
        $lastBudget = self::whereDate('created_at', today())->latest()->first();
        
        if ($lastBudget) {
            $lastNumber = intval(substr($lastBudget->code, -4));
            $newNumber = str_pad($lastNumber + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNumber = '0001';
        }
        
        return $prefix . $date . '-' . $newNumber;
    }
} 