<?php

namespace App\Models;

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

class TrialConfiguration extends Model
{
    use HasFactory;

    protected $fillable = [
        'plan_id',
        'trial_enabled',
        'trial_duration_days',
        'trial_requires_payment_method',
        'trial_auto_converts',
        'trial_conversion_action',
        'trial_extension_limit',
        'trial_feature_overrides',
        'trial_welcome_message',
        'trial_expiry_message',
    ];

    protected $casts = [
        'trial_enabled' => 'boolean',
        'trial_duration_days' => 'integer',
        'trial_requires_payment_method' => 'boolean',
        'trial_auto_converts' => 'boolean',
        'trial_conversion_action' => 'string',
        'trial_extension_limit' => 'integer',
        'trial_feature_overrides' => 'array',
    ];

    public const ACTION_UPGRADE_TO_PAID = 'upgrade_to_paid';

    public const ACTION_CANCEL = 'cancel';

    public const ACTION_NOTIFY = 'notify';

    public function plan(): BelongsTo
    {
        return $this->belongsTo(Plan::class);
    }

    public function scopeEnabled($query)
    {
        return $query->where('trial_enabled', true);
    }

    public function canExtendTrial(int $currentExtensions = 0): bool
    {
        return $this->trial_extension_limit > $currentExtensions;
    }

    public function getTrialEndDate(): \Carbon\Carbon
    {
        return now()->addDays($this->trial_duration_days);
    }

    public function hasFeatureOverride(string $featureName): bool
    {
        return isset($this->trial_feature_overrides[$featureName]);
    }

    public function getFeatureOverride(string $featureName)
    {
        return $this->trial_feature_overrides[$featureName] ?? null;
    }
}
