<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Crypt;

class ETIMSCredential extends Model
{
    use SoftDeletes;

    // Explicitly define the table name
    protected $table = 'etims_credentials';

    protected $fillable = [
        'name',
        'tin',
        'consumer_key',
        'consumer_secret',
        'api_url',
        'environment',
        'branch_id',
        'branch_name',
        'is_active',
        'last_sync',
        'sync_status',
        'notes'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'last_sync' => 'datetime',
    ];

    protected $hidden = [
        'consumer_key',
        'consumer_secret',
        'tin'
    ];

    protected $appends = [
        'tin_masked',
        'environment_display'
    ];

    /**
     * Encrypt credentials before saving.
     */
    public function setConsumerKeyAttribute($value)
    {
        $this->attributes['consumer_key'] = Crypt::encryptString($value);
    }

    public function setConsumerSecretAttribute($value)
    {
        $this->attributes['consumer_secret'] = Crypt::encryptString($value);
    }

    public function setTinAttribute($value)
    {
        $this->attributes['tin'] = Crypt::encryptString($value);
    }

    /**
     * Decrypt credentials when needed.
     */
    public function getDecryptedConsumerKey()
    {
        try {
            return Crypt::decryptString($this->attributes['consumer_key']);
        } catch (\Exception $e) {
            return null;
        }
    }

    public function getDecryptedConsumerSecret()
    {
        try {
            return Crypt::decryptString($this->attributes['consumer_secret']);
        } catch (\Exception $e) {
            return null;
        }
    }

    public function getDecryptedTin()
    {
        try {
            return Crypt::decryptString($this->attributes['tin']);
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Accessors.
     */
    public function getTinMaskedAttribute()
    {
        try {
            $tin = $this->getDecryptedTin();
            if (!$tin) return 'Not configured';
            return substr($tin, 0, 3) . '*****' . substr($tin, -2);
        } catch (\Exception $e) {
            return 'Error';
        }
    }

    public function getEnvironmentDisplayAttribute()
    {
        return $this->environment === 'production' ? 'Production' : 'Sandbox';
    }

    /**
     * Scope active credentials.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for environment.
     */
    public function scopeEnvironment($query, $env)
    {
        return $query->where('environment', $env);
    }
}