<?php

namespace App\Models;

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

class GymClass extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'trainer_id',
        'schedule', // This will store JSON
        'duration_minutes',
        'max_capacity',
        'current_attendees',
        'status'
    ];

    protected $casts = [
        'schedule' => 'array',
        'duration_minutes' => 'integer',
        'max_capacity' => 'integer',
        'current_attendees' => 'integer'
    ];

    protected $attributes = [
        'current_attendees' => 0,
        'status' => 'active'
    ];

    /**
     * Get the trainer for this class
     */
    public function trainer(): BelongsTo
    {
        return $this->belongsTo(Trainer::class)->withDefault([
            'first_name' => 'No',
            'last_name' => 'Trainer'
        ]);
    }

    /**
     * Set the schedule attribute
     */
    public function setScheduleAttribute($value)
    {
        if (is_array($value)) {
            $this->attributes['schedule'] = json_encode($value);
        } else {
            $this->attributes['schedule'] = $value;
        }
    }

    /**
     * Get the class date from schedule
     */
    public function getClassDateAttribute()
    {
        return $this->schedule['date'] ?? null;
    }

    /**
     * Get the class time from schedule
     */
    public function getClassTimeAttribute()
    {
        return $this->schedule['time'] ?? null;
    }

    /**
     * Scope for active classes
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }
    // app/Models/GymClass.php
public function registrations()
{
    return $this->hasMany(ClassRegistration::class);
}

    /**
     * Scope for upcoming classes
     */
    public function scopeUpcoming($query)
    {
        return $query->whereJsonContains('schedule->date', '>=', now()->toDateString());
    }
}