<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class LoyaltyTransaction extends Model
{
    protected $fillable = [
        'customer_id',
        'points',
        'type',
        'reference_type',
        'reference_id',
        'description',
        'date'
    ];

    protected $casts = [
        'points' => 'decimal:2',
        'date' => 'date',
    ];

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

    public function reference(): MorphTo
    {
        return $this->morphTo();
    }

    protected static function booted()
    {
        static::created(function ($transaction) {
            $customer = $transaction->customer;
            if ($customer) {
                // Assuming points can be positive (earned) or negative (redeemed)
                // If points are always stored as positive absolute value, we need to check type.
                // Based on view: $transaction->points > 0 ? '+' : ''
                // It suggests points carry the sign.
                $customer->increment('loyalty_points', $transaction->points);
            }
        });

        static::deleted(function ($transaction) {
            $customer = $transaction->customer;
            if ($customer) {
                $customer->decrement('loyalty_points', $transaction->points);
            }
        });

        static::updated(function ($transaction) {
            $customer = $transaction->customer;
            if ($customer) {
                // Revert original
                $customer->decrement('loyalty_points', $transaction->getOriginal('points'));
                // Apply new
                $customer->increment('loyalty_points', $transaction->points);
            }
        });
    }
}
