<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class TransactionPlan extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_id',
        'user_id',
        'transaction_type',
        'reference_id',
        'amount',
        'status',
        'payment_type',
        'payment_due_date',
        'snap_token',
    ];

    protected $casts = [
        'payment_due_date' => 'datetime',
        'amount' => 'decimal:2',
    ];

    /**
     * Relasi ke User yang melakukan transaksi
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Helper untuk cek apakah ini transaksi plan
     */
    public function isPlan()
    {
        return $this->transaction_type === 'plan';
    }

    public function isExpired()
    {
        if ($this->status === 'pending' && now()->gt($this->payment_due_date)) {
            return true;
        }
        return $this->status === 'expired';
    }

    public function plan()
    {
        // Hubungkan reference_id di transaksi ke id di tabel plans
        return $this->belongsTo(Plan::class, 'reference_id');
    }
}