<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
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\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Support\PublicMedia;

class Service extends Model
{
    use HasFactory, SoftDeletes, BelongsToCompany;

    protected $fillable = [
        'company_id', 'service_category_id',
        'name', 'slug', 'description', 'image_path',
        'price', 'promo_price',
        'duration_minutes', 'buffer_minutes', 'cancellation_min_notice_minutes',
        'requires_deposit', 'deposit_amount',
        'is_home_service', 'is_active', 'is_public',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'price'             => 'decimal:2',
            'promo_price'       => 'decimal:2',
            'deposit_amount'    => 'decimal:2',
            'cancellation_min_notice_minutes' => 'integer',
            'requires_deposit'  => 'boolean',
            'is_home_service'   => 'boolean',
            'is_active'         => 'boolean',
            'is_public'         => 'boolean',
        ];
    }

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

    public function employees(): BelongsToMany
    {
        return $this->belongsToMany(Employee::class, 'employee_services')
            ->withPivot('company_id', 'custom_price', 'custom_duration_minutes')
            ->withTimestamps()
            ->using(\App\Models\Pivot\EmployeeServicePivot::class);
    }

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

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

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

    public function effectivePrice(): float
    {
        return (float) ($this->promo_price ?? $this->price);
    }

    public function imageUrl(): ?string
    {
        return PublicMedia::url($this->image_path);
    }
}
