<?php

namespace App\Models;

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

class Panel extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'category',
        'price',
        'image',
        'description',
        'roi_percentage',
        'roi_interval',
        'duration',
        'return_capital',
        'status',
        'sort_order',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'roi_percentage' => 'decimal:2',
        'duration' => 'integer',
        'return_capital' => 'boolean',
        'sort_order' => 'integer',
    ];

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

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeCategory($query, ?string $category)
    {
        if ($category && in_array($category, ['solar', 'wall'], true)) {
            return $query->where('category', $category);
        }

        return $query;
    }

    public function getImageUrlAttribute(): ?string
    {
        return $this->image ? asset('dash/' . $this->image) : null;
    }

    public function getCategoryLabelAttribute(): string
    {
        return $this->category === 'wall' ? 'Wall Panel' : 'Solar Panel';
    }

    public static function roiIntervals(): array
    {
        return [
            'Monthly',
            'Weekly',
            'Daily',
            'Hourly',
            'Every 30 Minutes',
            'Every 10 Minutes',
        ];
    }

    public function calculateNextPayoutFrom(\Carbon\Carbon $from): \Carbon\Carbon
    {
        return match ($this->roi_interval) {
            'Monthly' => $from->copy()->addDays(30),
            'Weekly' => $from->copy()->addWeek(),
            'Daily' => $from->copy()->addDay(),
            'Hourly' => $from->copy()->addHour(),
            'Every 30 Minutes' => $from->copy()->addMinutes(30),
            'Every 10 Minutes' => $from->copy()->addMinutes(10),
            default => $from->copy()->addDay(),
        };
    }
}
