<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Subscription extends Model
{
    use HasFactory, SoftDeletes;

    protected $primaryKey = 'subscription_id';

    public function getRouteKeyName(): string
    {
        return 'subscription_id';
    }

    protected $fillable = [
        'customer_id',
        'plan_id',
        'product_id',
        'variant',
        'plan_eful_code',
        'efu_product_name',
        'cert_id',
        'reference_id',
        'policy_number',
        'transaction_id',
        'payment_order_id',
        'payment_order_title',
        'premium',
        'premium_paisa',
        'total_premium',
        'total_premium_paisa',
        'members_count',
        'currency',
        'contribution_age_group',
        'policy_status',
        'subscription_timestamp',
        'coverage_start_date',
        'coverage_end_date',
        'expiry_date',
        'grace_period_days',
        'grace_period_end_date',
        'activated_at',
        'cancelled_at',
        'cancellation_reason',
        'payment_response',
        'activation_response',
        'is_renewal',
        'renewed_from_subscription_id',
    ];

    protected $casts = [
        'premium'                 => 'decimal:2',
        'premium_paisa'           => 'integer',
        'total_premium'           => 'decimal:2',
        'total_premium_paisa'     => 'integer',
        'members_count'           => 'integer',
        'is_renewal'              => 'boolean',
        'subscription_timestamp'  => 'datetime',
        'coverage_start_date'     => 'date',
        'coverage_end_date'       => 'date',
        'expiry_date'             => 'date',
        'grace_period_end_date'   => 'date',
        'activated_at'            => 'datetime',
        'cancelled_at'            => 'datetime',
        'payment_response'        => 'array',
        'activation_response'     => 'array',
        'created_at'              => 'datetime',
        'updated_at'              => 'datetime',
    ];

    // ── Status Constants ───────────────────────────────────────────────────────
    const STATUS_PENDING_PAYMENT = 'pending_payment';
    const STATUS_ACTIVE          = 'active';
    const STATUS_EXPIRED         = 'expired';
    const STATUS_CANCELLED       = 'cancelled';
    const STATUS_FAILED          = 'failed';
    const STATUS_GRACE_PERIOD    = 'grace_period';
    const STATUS_SUSPENDED       = 'suspended';


    // ── Boot: auto-generate reference_id ──────────────────────────────────────
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($subscription) {
            if (empty($subscription->reference_id)) {
                $subscription->reference_id = 'SUB-' . strtoupper(Str::random(4))
                    . '-' . now()->format('YmdHis')
                    . '-' . str_pad($subscription->customer_id ?? 0, 4, '0', STR_PAD_LEFT);
            }
        });
    }

    // ── Relationships ──────────────────────────────────────────────────────────
    public function customer()
    {
        return $this->belongsTo(EasypaisaCustomer::class, 'customer_id', 'customer_id');
    }

    public function plan()
    {
        return $this->belongsTo(Plan::class, 'plan_id', 'plan_id');
    }

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'product_id');
    }

    public function renewedFrom()
    {
        return $this->belongsTo(Subscription::class, 'renewed_from_subscription_id', 'subscription_id');
    }

    public function renewals()
    {
        return $this->hasMany(Subscription::class, 'renewed_from_subscription_id', 'subscription_id');
    }

    public function members()
    {
        return $this->hasMany(SubscriptionMember::class, 'subscription_id', 'subscription_id');
    }

    public function selfMember()
    {
        return $this->hasOne(SubscriptionMember::class, 'subscription_id', 'subscription_id')
                    ->where('member_type', 'self');
    }

    public function dependents()
    {
        return $this->hasMany(SubscriptionMember::class, 'subscription_id', 'subscription_id')
                    ->where('member_type', '!=', 'self');
    }

    // ── Scopes ─────────────────────────────────────────────────────────────────
    public function scopePending($query)
    {
        return $query->where('policy_status', self::STATUS_PENDING_PAYMENT);
    }

    public function scopeActive($query)
    {
        return $query->where('policy_status', self::STATUS_ACTIVE);
    }

    public function scopeExpired($query)
    {
        return $query->where('policy_status', self::STATUS_EXPIRED);
    }

    // ── Helpers ────────────────────────────────────────────────────────────────
    public function isPending(): bool
    {
        return $this->policy_status === self::STATUS_PENDING_PAYMENT;
    }

    public function isActive(): bool
    {
        return $this->policy_status === self::STATUS_ACTIVE;
    }

    public function isExpired(): bool
    {
        return $this->expiry_date && $this->expiry_date->isPast()
            && $this->policy_status !== self::STATUS_ACTIVE;
    }
}