<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SubscriptionPlan extends Model
{
    protected $table = 'subscription_plans';

    protected $fillable = [
        'name',
        'description',
        'base_price_monthly',
        'base_price_yearly',
        'per_employee_price',
        'employee_limit',
        'billing_type',
        'modules',
        'default',
        'is_popular',
        'active',
        'is_custom',
        'discount_type',
        'discount_value',
        'strike_price_yearly',
        'currency_code',
        'currency_symbol',
        'position',
    ];

    protected $casts = [
        'base_price_monthly' => 'decimal:2',
        'base_price_yearly' => 'decimal:2',
        'per_employee_price' => 'decimal:2',
        'employee_limit' => 'integer',
        'is_popular' => 'boolean',
        'active' => 'boolean',
        'is_custom' => 'boolean',
        'discount_value' => 'decimal:2',
        'strike_price_yearly' => 'decimal:2',
        'modules' => 'array',
    ];

    public function companies(): HasMany
    {
        return $this->hasMany(Company::class, 'subscription_plan_id');
    }

    public function planFeatures(): HasMany
    {
        return $this->hasMany(PlanFeature::class, 'plan_id');
    }

    public function addons(): BelongsToMany
    {
        return $this->belongsToMany(Addon::class, 'addon_subscription_plan');
    }

    public function effectiveYearlyPrice(): float
    {
        $base = (float) $this->base_price_yearly;
        $type = $this->discount_type ?: 'none';
        $value = (float) $this->discount_value;

        if ($type === 'percent' && $value > 0) {
            return max(0, round($base - ($base * $value / 100), 2));
        }

        if ($type === 'fixed' && $value > 0) {
            return max(0, round($base - $value, 2));
        }

        return round($base, 2);
    }

    public function planDiscountAmount(): float
    {
        return max(0, round((float) $this->base_price_yearly - $this->effectiveYearlyPrice(), 2));
    }

    public function displayStrikePrice(): ?float
    {
        if ($this->strike_price_yearly !== null && (float) $this->strike_price_yearly > $this->effectiveYearlyPrice()) {
            return (float) $this->strike_price_yearly;
        }

        if ($this->planDiscountAmount() > 0) {
            return (float) $this->base_price_yearly;
        }

        return null;
    }

    public function isSelfServe(): bool
    {
        return ! $this->is_custom && (float) $this->base_price_yearly >= 0 && ($this->default ?? 'no') !== 'yes';
    }

    public function isFreeDefault(): bool
    {
        return ($this->default ?? 'no') === 'yes' || strcasecmp((string) $this->name, 'Free') === 0;
    }
}
