<?php

namespace App\Models;

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

class PlanPermission extends Model
{
    use HasFactory;

    protected $fillable = [
        'plan_id',
        'plan_feature_id',
        'permission',
        'is_granted',
        'conditions',
        'applies_during_trial',
        'trial_permission_override',
    ];

    protected $casts = [
        'is_granted' => 'boolean',
        'applies_during_trial' => 'boolean',
        'trial_permission_override' => 'boolean',
        'conditions' => 'array',
    ];

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

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

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

    public function isEffectivePermission(bool $isOnTrial = false): bool
    {
        if ($isOnTrial && $this->applies_during_trial && $this->trial_permission_override !== null) {
            return $this->trial_permission_override;
        }

        return $this->is_granted;
    }
}
