<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

class Invoice extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'invoice_number',
        'customer_id',
        'invoice_date',
        'due_date',
        'status',
        'subtotal',
        'discount',
        'tax',
        'shipping_cost',
        'amount_paid',
        'total',
        'notes',
        'signature_path',
        'stamp_path',
    ];

    protected $casts = [
        'invoice_date' => 'date',
        'due_date'     => 'date',
        'subtotal'     => 'decimal:2',
        'discount'     => 'decimal:2',
        'tax'          => 'decimal:2',
        'shipping_cost'=> 'decimal:2',
        'amount_paid'  => 'decimal:2',
        'total'        => 'decimal:2',
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function items()
    {
        return $this->hasMany(InvoiceItem::class)->orderBy('sort_order');
    }

    public function receipt()
    {
        return $this->hasOne(Receipt::class);
    }

    /**
     * Generate invoice number otomatis: INV-2024-0001
     */
    public static function generateNumber(): string
    {
        $year  = date('Y');
        $month = date('m');
        $count = static::whereYear('invoice_date', $year)->count();
        $seq   = str_pad($count + 1, 2, '0', STR_PAD_LEFT);

        return "INV/RJ/{$seq}/{$month}/{$year}";
    }

    /**
     * Hitung ulang total invoice dari items
     */
    public function recalculate(): void
    {
        $subtotal = $this->items()->sum('total_price');
        $total    = $subtotal - $this->discount - $this->amount_paid + $this->tax + $this->shipping_cost;

        $this->update([
            'subtotal' => $subtotal,
            'total'    => max(0, $total),
        ]);
    }

    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'draft'     => 'Draft',
            'sent'      => 'Terkirim',
            'paid'      => 'Lunas',
            'cancelled' => 'Dibatalkan',
            default     => $this->status,
        };
    }

    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            'draft'     => 'secondary',
            'sent'      => 'primary',
            'paid'      => 'success',
            'cancelled' => 'danger',
            default     => 'secondary',
        };
    }
}
