<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

#[Fillable(['category_id', 'name', 'slug', 'tagline', 'description', 'image', 'icon', 'price_paise', 'original_price_paise', 'duration_minutes', 'is_featured', 'is_active', 'sort_order', 'whats_included', 'faqs'])]
class Service extends Model
{
    use HasFactory;

    protected $casts = [
        'is_featured' => 'boolean',
        'is_active' => 'boolean',
        'sort_order' => 'integer',
        'duration_minutes' => 'integer',
        'price_paise' => 'integer',
        'original_price_paise' => 'integer',
        'whats_included' => 'array',
        'faqs' => 'array',
    ];

    public function category(): BelongsTo
    {
        return $this->belongsTo(ServiceCategory::class, 'category_id');
    }

    public function partners(): BelongsToMany
    {
        return $this->belongsToMany(PartnerProfile::class, 'partner_service', 'service_id', 'partner_id')
            ->withPivot('custom_price_paise', 'is_active');
    }

    public function getPriceRupeesAttribute(): float
    {
        return round($this->price_paise / 100, 2);
    }

    public function getOriginalRupeesAttribute(): ?float
    {
        return $this->original_price_paise ? round($this->original_price_paise / 100, 2) : null;
    }

    public function getDiscountPercentAttribute(): int
    {
        if (!$this->original_price_paise || $this->original_price_paise <= $this->price_paise) {
            return 0;
        }
        return (int) round((($this->original_price_paise - $this->price_paise) / $this->original_price_paise) * 100);
    }

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

    public function scopeFeatured($q)
    {
        return $q->where('is_featured', true);
    }

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