<?php

namespace App\Models;

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

class EtimsInvoice extends Model
{
    use HasFactory;

    protected $fillable = [
        'order_id',
        'invoice_number',
        'etims_invoice_number',
        'etims_status',
        'status_code',
        'status_message',
        'sent_at',
        'responded_at',
        'request_payload',
        'response_payload',
    ];

    protected function casts(): array
    {
        return [
            'sent_at' => 'datetime',
            'responded_at' => 'datetime',
        ];
    }

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

    public function scopePending($query)
    {
        return $query->where('etims_status', 'pending');
    }

    public function scopeFailed($query)
    {
        return $query->where('etims_status', 'failed');
    }

    public function markAsSent()
    {
        $this->update([
            'etims_status' => 'sent',
            'sent_at' => now(),
        ]);
    }

    public function markAsSuccess($response)
    {
        $this->update([
            'etims_status' => 'success',
            'responded_at' => now(),
            'response_payload' => json_encode($response),
        ]);
    }

    public function markAsFailed($code, $message, $response = null)
    {
        $this->update([
            'etims_status' => 'failed',
            'status_code' => $code,
            'status_message' => $message,
            'responded_at' => now(),
            'response_payload' => $response ? json_encode($response) : null,
        ]);
    }
}
