<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AvailabilitySlot extends Model
{
    use HasFactory;

    protected $fillable = [
        'placement_id',
        'date',
        'start_time',
        'end_time',
        'spot_duration',
        'total_spots',
        'booked_spots',
        'status',
        'notes',
    ];

    protected $casts = [
        'date' => 'date',
    ];

    // ============================================================
    // Scopes
    // ============================================================
    public function scopeAvailable($query)
    {
        return $query->where('status', 'available')
                     ->orWhere('status', 'partially_booked');
    }

    public function scopeForDate($query, string $date)
    {
        return $query->where('date', $date);
    }

    public function scopeForDateRange($query, string $start, string $end)
    {
        return $query->whereBetween('date', [$start, $end]);
    }

    // ============================================================
    // Helpers
    // ============================================================
    public function isAvailable(): bool
    {
        return in_array($this->status, ['available', 'partially_booked'])
               && $this->getRemainingSpots() > 0;
    }

    public function getRemainingSpots(): int
    {
        return max(0, $this->total_spots - $this->booked_spots);
    }

    public function getOccupancyPct(): float
    {
        if ($this->total_spots === 0) return 0;
        return round(($this->booked_spots / $this->total_spots) * 100, 1);
    }

    // ============================================================
    // Relationships
    // ============================================================
    public function placement()
    {
        return $this->belongsTo(Placement::class);
    }

    public function bookingItems()
    {
        return $this->hasMany(BookingItem::class);
    }
}