<?php

namespace App\Models;

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

class Transaction extends Model
{
    protected $fillable = [
        'order_id',
        'user_id',
        'gateway',
        'gateway_name',
        'amount',
        'status',
        'track_id',
        'ref_number',
        'card_number',
        'gateway_response',
        'error_code',
        'error_message',
        'paid_at',
    ];

    protected $casts = [
        'gateway_response' => 'array',
        'paid_at'          => 'datetime',
    ];

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

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

    public function statusLabel(): string
    {
        return match ($this->status) {
            'pending' => 'در انتظار',
            'success' => 'موفق',
            'failed'  => 'ناموفق',
            default   => $this->status,
        };
    }

    public function statusColor(): string
    {
        return match ($this->status) {
            'pending' => 'warning',
            'success' => 'success',
            'failed'  => 'danger',
            default   => 'secondary',
        };
    }

    public function shamsiCreatedAt(): string
    {
        return Order::toJalaliString($this->created_at)
            . ' ' . $this->created_at->format('H:i');
    }

    public function shamsiPaidAt(): ?string
    {
        if (!$this->paid_at) {
            return null;
        }

        return Order::toJalaliString($this->paid_at)
            . ' ' . $this->paid_at->format('H:i');
    }
}
