<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\ProUnit;
use App\Models\Customer;

class TMP_MeterReading extends Model
{
    protected $table = 'tmp_meterreading';
    protected $primaryKey = 'MeterReadingID';
    public $incrementing = true;

    protected $fillable = [
        'BillingPeriod',
        'ConsType',
        'CustomerID',
        'UnitID',
        'PropID',
        'Reading',
        'ReadingDate',
        'Consumption',
        'ImagePath',
        'BaseOfBilling',
        'ReadingComments',
        'MeterNo',
        'PrvReading',
        'PrvReadingDate',
        'PrvReadingID',
        'CompanyID'
    ];

    protected $dates = ['ReadingDate', 'PrvReadingDate'];

    /**
     * Get the customer that owns the meter reading.
     */
    public function customer()
    {
        return $this->belongsTo(Customer::class, 'CustomerID', 'CustomerID');
    }

    /**
     * Get the unit that owns the meter reading.
     */
    /**
     * Get the unit that owns the meter reading.
     */
    public function unit()
    {
        return $this->belongsTo(ProUnit::class, 'UnitID', 'UnitID');
    }

    /**
     * Get the previous reading for the same unit and consumption type
     */
    public function previousReading()
    {
        return $this->belongsTo(TMP_MeterReading::class, 'PrvReadingID', 'MeterReadingID');
    }

    /**
     * Get the next readings for the same unit and consumption type
     */
    public function nextReadings()
    {
        $query = $this->hasMany(TMP_MeterReading::class, 'UnitID', 'UnitID')
            ->where('ConsType', $this->ConsType);

        if ($this->ReadingDate) {
            $query->where('ReadingDate', '>', $this->ReadingDate);
        }

        return $query->orderBy('ReadingDate', 'asc');
    }
}