<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Transaction extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'invoice_number', 'user_id', 'cash_session_id',
        'customer_name', 'customer_phone',
        'subtotal', 'discount_amount', 'tax_percent', 'tax_amount', 'grand_total',
        'payment_method', 'amount_paid', 'change_amount',
        'status', 'notes', 'payment_details', 'transaction_date',
        'voided_at', 'voided_by', 'authorized_by', 'void_reason',
    ];

    protected $casts = [
        'subtotal'        => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'tax_percent'     => 'decimal:2',
        'tax_amount'      => 'decimal:2',
        'grand_total'     => 'decimal:2',
        'amount_paid'     => 'decimal:2',
        'change_amount'   => 'decimal:2',
        'payment_details' => 'array',
        'transaction_date'=> 'datetime',
        'voided_at'       => 'datetime',
    ];

    public function user()         { return $this->belongsTo(User::class); }
    public function voidedBy()     { return $this->belongsTo(User::class, 'voided_by'); }
    public function authorizedBy() { return $this->belongsTo(User::class, 'authorized_by'); }
    public function cashSession()  { return $this->belongsTo(CashSession::class); }
    public function items()        { return $this->hasMany(TransactionItem::class); }

    public function scopeCompleted($q) { return $q->where('status', 'completed'); }
    public function scopeToday($q)     { return $q->whereDate('transaction_date', today()); }
    public function scopeByDate($q, $start, $end) {
        return $q->whereBetween('transaction_date', [$start, $end]);
    }

    public function getProfitAttribute(): float {
        return $this->items->sum(fn($item) => ($item->unit_price - $item->cost_price) * $item->quantity);
    }

    // Generate nomor invoice: INV-20240101-0001
    public static function generateInvoice(): string
    {
        $date = now()->format('Ymd');
        $prefix = "INV-{$date}-";
        $last = self::where('invoice_number', 'like', $prefix . '%')->latest('id')->first();
        $seq = $last ? (int) substr($last->invoice_number, -4) + 1 : 1;
        return $prefix . str_pad($seq, 4, '0', STR_PAD_LEFT);
    }
}
