<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class UnitAssignment extends Model
{
    protected $table = 'unit_assignments';
    
    protected $fillable = [
        'customer_id',
        'unit_id',
        'start_date',
        'end_date',
        'status',
        'notes'
    ];

    protected $dates = [
        'start_date',
        'end_date',
        'created_at',
        'updated_at'
    ];

    protected $casts = [
        'start_date' => 'date:Y-m-d',
        'end_date' => 'date:Y-m-d',
    ];

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class, 'customer_id', 'CustomerID');
    }

    public function unit(): BelongsTo
    {
        return $this->belongsTo(ProUnit::class, 'unit_id', 'UnitID');
    }

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeForCustomer($query, $customerId)
    {
        return $query->where('customer_id', $customerId);
    }

    public function scopeForUnit($query, $unitId)
    {
        return $query->where('unit_id', $unitId);
    }
    
    /**
     * Get the payments for the unit assignment.
     * Payments are filtered to only include those within the assignment period.
     */
    public function payments()
    {
        return $this->hasManyThrough(
            Payment::class,
            Customer::class,
            'CustomerID',  // Foreign key on Customer table
            'CustomerID',  // Foreign key on Payment table
            'customer_id', // Local key on UnitAssignment table
            'CustomerID'   // Local key on Customer table
        )->when($this->start_date, function($query) {
            $query->where('PaymentDate', '>=', $this->start_date);
        })->when($this->end_date, function($query) {
            $query->where('PaymentDate', '<=', $this->end_date);
        });
    }
    
    /**
     * Get the rent service bills for the unit assignment.
     */
    public function bills()
    {
        return $this->hasMany(
            RentServiceBill::class,
            'UnitID',
            'unit_id'
        )->when($this->start_date, function($query) {
            $query->where('BillingDate', '>=', $this->start_date);
        })->when($this->end_date, function($query) {
            $query->where('BillingDate', '<=', $this->end_date);
        });
    }
}
