<?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 Employee extends Model
{
    use HasFactory, SoftDeletes, BelongsToCompany;

    protected $fillable = [
        'company_id', 'user_id', 'branch_id',
        'first_name', 'last_name', 'email', 'phone', 'document_number',
        'position', 'photo_path', 'bio', 'color',
        'has_commission', 'commission_type', 'commission_value',
        'is_bookable', 'is_active', 'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'has_commission'   => 'boolean',
            'commission_value' => 'decimal:2',
            'is_bookable'      => 'boolean',
            'is_active'        => 'boolean',
        ];
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

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

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

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

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

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

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

    public function fullName(): string
    {
        return trim($this->first_name.' '.$this->last_name);
    }

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