<?php

declare(strict_types=1);

namespace App\Models;

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

class PlanConfigOption extends Model
{
    use HasFactory;

    protected $fillable = [
        'group_id',
        'name',
        'description',
        'type',
        'provisioning_key',
        'required',
        'is_active',
        'min_qty',
        'max_qty',
        'step',
        'unit_label',
        'hourly_price',
        'monthly_price',
        'quarterly_price',
        'semi_annual_price',
        'annual_price',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'required' => 'boolean',
            'is_active' => 'boolean',
            'min_qty' => 'integer',
            'max_qty' => 'integer',
            'step' => 'integer',
            'hourly_price' => 'decimal:4',
            'monthly_price' => 'decimal:2',
            'quarterly_price' => 'decimal:2',
            'semi_annual_price' => 'decimal:2',
            'annual_price' => 'decimal:2',
            'sort_order' => 'integer',
        ];
    }

    public function group(): BelongsTo
    {
        return $this->belongsTo(PlanConfigGroup::class, 'group_id');
    }

    public function values(): HasMany
    {
        return $this->hasMany(PlanConfigValue::class, 'option_id')->orderBy('sort_order');
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function isSlider(): bool
    {
        return $this->type === 'slider';
    }

    public function isQuantity(): bool
    {
        return $this->type === 'quantity';
    }

    public function isDropdown(): bool
    {
        return $this->type === 'dropdown';
    }

    public function isRadio(): bool
    {
        return $this->type === 'radio';
    }

    public function isCheckbox(): bool
    {
        return $this->type === 'checkbox';
    }

    public function isText(): bool
    {
        return $this->type === 'text';
    }

    public function calculatePrice(int $quantity, string $cycle): float
    {
        $priceField = match ($cycle) {
            'hourly' => 'hourly_price',
            'monthly' => 'monthly_price',
            'quarterly' => 'quarterly_price',
            'semi_annual' => 'semi_annual_price',
            'annual' => 'annual_price',
            default => 'monthly_price',
        };

        return (float) (($this->{$priceField} ?? 0) * $quantity);
    }

    public function getHourlyPrice(int $quantity): float
    {
        return (float) (($this->hourly_price ?? 0) * $quantity);
    }
}
