<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Builder;

class Subscription extends Model
{
    protected $fillable = [
        'client_id',
        'package_id',
        'start_date',
        'end_date',
        'status',
        'payment_method',
        'payment_status',
        'amount_paid',
        'notes',
        'cancelled_at',
    ];

    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'end_date' => 'date',
            'amount_paid' => 'decimal:2',
            'cancelled_at' => 'datetime',
        ];
    }

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

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

    public function propertyTypes(): BelongsToMany
    {
        return $this->belongsToMany(PropertyType::class, 'subscription_properties')
            ->withPivot('quantity')
            ->withTimestamps();
    }

    public function facilities(): BelongsToMany
    {
        return $this->belongsToMany(AdditionalFacility::class, 'subscription_facilities')
            ->withPivot('quantity', 'unit_price', 'total_price')
            ->withTimestamps();
    }

    public function getIsExpiredAttribute(): bool
    {
        return $this->end_date < now()->toDateString() && $this->status === 'active';
    }

    public function getFacilitiesTotalAttribute(): float
    {
        return $this->facilities->sum('pivot.total_price');
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('status', 'active')
            ->where('end_date', '>=', now()->toDateString());
    }

    public function scopeExpired(Builder $query): Builder
    {
        return $query->where(function ($q) {
            $q->where('status', 'expired')
                ->orWhere(function ($q2) {
                    $q2->where('status', 'active')
                        ->where('end_date', '<', now()->toDateString());
                });
        });
    }
}
