<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

class Tenancy extends Model
{
    use SoftDeletes;

    protected $table = 'tenancies';
    protected $primaryKey = 'id';
    public $incrementing = true;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'customer_id',
        'unit_id',
        'company_id',
        'CompanyID', // For backward compatibility
        'status_id',
        'start_date',
        'end_date',
        'monthly_rent',
        'security_deposit',
        'move_in_date',
        'move_out_date',
        'move_in_notes',
        'move_out_notes',
        'lease_document_path',
        'contract_number',
        'created_by',
        'updated_by',
    ];
    
    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'start_date' => 'date:Y-m-d',
        'end_date' => 'date:Y-m-d',
        'move_in_date' => 'date:Y-m-d',
        'move_out_date' => 'date:Y-m-d',
        'monthly_rent' => 'decimal:2',
        'security_deposit' => 'decimal:2',
    ];
    
    /**
     * Get the status of the tenancy.
     */
    public function status()
    {
        return $this->belongsTo(TenancyStatus::class, 'status_id');
    }

    /**
     * The "booted" method of the model.
     */
    /**
     * The "booted" method of the model.
     */
    protected static function booted()
    {
        static::addGlobalScope('company', function ($builder) {
            if (Auth::check() && !is_null(Auth::user()->CompanyID)) {
                $builder->where('company_id', Auth::user()->CompanyID);
            }
        });
    }
    
    /**
     * Get the company that owns the tenancy.
     */
    public function company()
    {
        return $this->belongsTo(Company::class, 'company_id', 'CompanyID');
    }

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

    /**
     * Get the unit that is being rented.
     */
    public function unit()
    {
        return $this->belongsTo(ProUnit::class, 'unit_id', 'UnitID');
    }

    /**
     * Get the user who created the tenancy.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the user who last updated the tenancy.
     */
    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Scope a query to only include active tenancies.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->whereHas('status', function($q) {
            $q->where('name', 'active');
        });
    }

    /**
     * Scope a query to only include pending tenancies.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePending($query)
    {
        return $query->whereHas('status', function($q) {
            $q->where('name', 'pending');
        });
    }

    /**
     * Scope a query to only include terminated tenancies.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeTerminated($query)
    {
        return $query->whereHas('status', function($q) {
            $q->where('name', 'terminated');
        });
    }
    
    /**
     * Check if the tenancy is active.
     *
     * @return bool
     */
    public function isActive(): bool
    {
        return optional($this->status)->name === 'active';
    }
    
    /**
     * Check if the tenancy is pending.
     *
     * @return bool
     */
    public function isPending(): bool
    {
        return optional($this->status)->name === 'pending';
    }
    
    /**
     * Check if the tenancy is terminated.
     *
     * @return bool
     */
    public function isTerminated(): bool
    {
        return optional($this->status)->name === 'terminated';
    }



    /**
     * Get the duration of the tenancy in months.
     */
    public function getDurationInMonths(): ?int
    {
        if (!$this->start_date) {
            return null;
        }

        $endDate = $this->end_date ?? now();
        
        return $this->start_date->diffInMonths($endDate) + 1; // Add 1 to include both start and end months
    }

    /**
     * Get the next payment due date.
     */
    public function getNextPaymentDueDate()
    {
        if (!$this->isActive()) {
            return null;
        }

        $lastPayment = $this->payments()->latest('payment_date')->first();
        
        if ($lastPayment) {
            return $lastPayment->payment_date->addMonth();
        }
        
        return $this->start_date;
    }
}
