<?php

namespace App\Models;

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

class MpesaConfig extends Model
{
    use HasFactory;

    protected $fillable = [
        'consumer_key',
        'consumer_secret',
        'shortcode',
        'passkey',
        'callback_url',
        'confirmation_url',
        'validation_url',
        'is_active',
        'is_production',
        'manual_recording',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'is_production' => 'boolean',
            'manual_recording' => 'boolean',
        ];
    }

    public static function getActiveConfig()
    {
        return self::where('is_active', true)->first();
    }

    public static function isConfigured(): bool
    {
        $config = self::getActiveConfig();

        return $config && $config->consumer_key && $config->consumer_secret && $config->shortcode;
    }

    public function getAuthBaseUrl(): string
    {
        return $this->is_production
            ? 'https://api.safaricom.co.ke'
            : 'https://sandbox.safaricom.co.ke';
    }

    public function getMpesaBaseUrl(): string
    {
        return $this->is_production
            ? 'https://api.safaricom.co.ke'
            : 'https://sandbox.safaricom.co.ke';
    }

    public function generatePassword(): string
    {
        $timestamp = now()->format('YmdHis');
        $password = base64_encode($this->shortcode.$this->passkey.$timestamp);

        return $password;
    }

    public function getCallbackUrl(): string
    {
        return $this->callback_url ?? route('mpesa.callback');
    }
}
