<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Plan extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name', 'slug', 'description',
        'price_monthly', 'price_yearly', 'currency',
        'promo_price_monthly', 'promo_price_yearly',
        'promo_starts_at', 'promo_ends_at',
        'max_employees', 'max_services', 'max_bookings_month',
        'max_branches', 'max_customers',
        'is_active', 'is_featured', 'is_public',
        'trial_days', 'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'price_monthly'        => 'decimal:2',
            'price_yearly'         => 'decimal:2',
            'promo_price_monthly'  => 'decimal:2',
            'promo_price_yearly'   => 'decimal:2',
            'promo_starts_at'      => 'date',
            'promo_ends_at'        => 'date',
            'is_active'            => 'boolean',
            'is_featured'          => 'boolean',
            'is_public'            => 'boolean',
        ];
    }

    public function modules(): BelongsToMany
    {
        return $this->belongsToMany(Module::class, 'plan_modules')
            ->withPivot('is_enabled')
            ->withTimestamps();
    }

    public function companies(): HasMany
    {
        return $this->hasMany(Company::class);
    }

    public function subscriptions(): HasMany
    {
        return $this->hasMany(Subscription::class);
    }

    /* Scopes */
    public function scopeActive(Builder $q): Builder
    {
        return $q->where('is_active', true);
    }

    public function scopePublic(Builder $q): Builder
    {
        return $q->where('is_public', true);
    }

    public function scopeOrdered(Builder $q): Builder
    {
        return $q->orderBy('sort_order')->orderBy('price_monthly');
    }

    /* Helpers */
    public function isPromoActive(): bool
    {
        $now = now();
        return $this->promo_starts_at && $this->promo_ends_at
            && $now->between($this->promo_starts_at, $this->promo_ends_at);
    }

    public function effectivePriceMonthly(): float
    {
        return (float) ($this->isPromoActive() && $this->promo_price_monthly !== null
            ? $this->promo_price_monthly
            : $this->price_monthly);
    }

    public function effectivePriceYearly(): float
    {
        return (float) ($this->isPromoActive() && $this->promo_price_yearly !== null
            ? $this->promo_price_yearly
            : $this->price_yearly);
    }

    public function hasModule(string $key): bool
    {
        return $this->modules()
            ->where('key', $key)
            ->wherePivot('is_enabled', true)
            ->exists();
    }
}
