<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class LockerRegistration extends Model
{
    protected $fillable = [
        'client_id',
        'locker_id',
        'locker_password',
        'membership_plan_id',
        'registration_date',
        'locker_amount',
        'locker_discount',
        'commission_amount',
        'total_commission_used',
        'start_date',
        'end_date',
        'access_type',
        'status',
        'auth_count',
        'safebox_count',
        'contract_start_date',
        'contract_end_date',
        'payment_terms',
        'stamping_fee',
        'key_deposit',
        'insurance_charges',
        'discount_amount',
        'referred_member_by',
        'referred_commission'
    ];

    protected $casts = [
        'locker_amount' => 'decimal:2',
        'locker_discount' => 'decimal:2',
        'commission_amount' => 'decimal:2',
        'total_commission_used' => 'decimal:2',
        'start_date' => 'date',
        'end_date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * Get the client that owns the registration.
     */
    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function items()
    {
        return $this->hasMany(LockerRegistrationItem::class, 'registration_id');
    }

    /**
     * Get the locker for this registration.
     */
    public function locker(): BelongsTo
    {
        return $this->belongsTo(Locker::class);
    }

    /**
     * Get the documents for this registration.
     */
    public function documents(): HasMany
    {
        return $this->hasMany(LockerDocument::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class, 'registration_id');
    }

    /**
     * Get the membership plan for this registration.
     */
    public function membershipPlan(): BelongsTo
    {
        return $this->belongsTo(MembershipPlan::class);
    }

    /**
     * Scope to get active registrations.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'Active');
    }

    /**
     * Scope to get expired registrations.
     */
    public function scopeExpired($query)
    {
        return $query->where('status', 'Expired');
    }

    /**
     * Scope to get cancelled registrations.
     */
    public function scopeCancelled($query)
    {
        return $query->where('status', 'Cancelled');
    }

    /**
     * Check if registration is currently active.
     */
    public function isActive(): bool
    {
        return $this->status === 'Active' &&
            (!$this->end_date || $this->end_date >= now());
    }
}
