<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    protected $fillable = [
        'user_id', 'payment_id', 'reference_id', 'gateway', 'amount', 'fee', 'currency', 'status', 'sender_number', 'trx_id', 'redirect_url', 'cancel_url', 'metadata'
    ];

    protected $casts = [
        'metadata' => 'array',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->payment_id)) {
                $model->payment_id = \Illuminate\Support\Str::random(12);
            }
            if (empty($model->user_id)) {
                $model->user_id = \App\Models\User::first()->id ?? 1;
            }
        });

        static::created(function ($model) {
            if (function_exists('sync_customer_from_transaction')) {
                sync_customer_from_transaction($model);
            }
            if ($model->status === 'SUCCESS') {
                if (function_exists('send_telegram_notification')) {
                    send_telegram_notification($model);
                }
                if (function_exists('send_payment_email_notification')) {
                    send_payment_email_notification($model);
                }
            }
        });

        static::updated(function ($model) {
            if (function_exists('sync_customer_from_transaction')) {
                sync_customer_from_transaction($model);
            }
            if ($model->isDirty('status') && $model->status === 'SUCCESS') {
                if (function_exists('send_telegram_notification')) {
                    send_telegram_notification($model);
                }
                if (function_exists('send_payment_email_notification')) {
                    send_payment_email_notification($model);
                }
            }
        });
    }

    public function getRouteKeyName()
    {
        return 'payment_id';
    }

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