<?php

namespace App\Models;

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

class MpesaTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'transaction_id',
        'merchant_request_id',
        'checkout_request_id',
        'phone_number',
        'amount',
        'account_reference',
        'transaction_desc',
        'transaction_type',
        'status',
        'response_code',
        'response_description',
        'customer_message',
        'request_data',
        'response_data',
        'transaction_time',
        'order_id',
        'user_id'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'request_data' => 'array',
        'response_data' => 'array',
        'transaction_time' => 'datetime'
    ];

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

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

    // Status helpers
    public function isPending()
    {
        return $this->status === 'pending';
    }

    public function isSuccessful()
    {
        return $this->status === 'success';
    }

    public function isFailed()
    {
        return $this->status === 'failed';
    }

    public function markAsSuccess($data = [])
    {
        $this->update([
            'status' => 'success',
            'response_code' => $data['ResultCode'] ?? '0',
            'response_description' => $data['ResultDesc'] ?? 'Success',
            'transaction_id' => $data['TransactionID'] ?? $this->transaction_id,
            'transaction_time' => isset($data['TransactionDate']) ? 
                Carbon::createFromFormat('YmdHis', $data['TransactionDate']) : 
                ($data['transaction_time'] ?? now()),
            'response_data' => $data
        ]);
    }

    public function markAsFailed($data = [])
    {
        $this->update([
            'status' => 'failed',
            'response_code' => $data['ResultCode'] ?? '1',
            'response_description' => $data['ResultDesc'] ?? 'Failed',
            'response_data' => $data
        ]);
    }
    
    // Scope for filtering
    public function scopeSuccessful($query)
    {
        return $query->where('status', 'success');
    }
    
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }
    
    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }
}