<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PoslajuSetting extends Model
{
    protected $fillable = [
        'user_id',
        // Old authentication (deprecated but kept for backward compatibility)
        'api_key',
        'secret_key',
        // OAuth 2.0 Credentials
        'app_code',
        'secret_code',
        'client_id',
        'client_secret',
        'access_token',
        'token_expires_at',
        // Account info
        'account_number',
        'poslaju_account_id',
        // API Required Fields
        'product_code',
        'subscription_code',
        'item_type',
        'service_level',
        'order_validity',
        'webhook_required',
        // Sender info
        'sender_name',
        'sender_phone',
        'sender_address',
        'sender_postcode',
        'sender_city',
        'sender_state',
        'poslaju_logo_path',
        'company_logo_path',
        'default_weight',
        'default_dimension_l',
        'default_dimension_w',
        'default_dimension_h',
        'is_active',
        'hide_product_names',
        'test_mode',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'hide_product_names' => 'boolean',
        'test_mode' => 'boolean',
        'webhook_required' => 'boolean',
        'default_weight' => 'decimal:2',
        'order_validity' => 'integer',
        'token_expires_at' => 'datetime',
    ];

    /**
     * Get the user that owns the Poslaju settings.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Check if OAuth token is valid and not expired
     */
    public function hasValidToken(): bool
    {
        return $this->access_token &&
               $this->token_expires_at &&
               $this->token_expires_at->isFuture();
    }

    /**
     * Check if OAuth credentials are configured
     */
    public function hasOAuthCredentials(): bool
    {
        return $this->client_id && $this->client_secret;
    }
}
