<?php

namespace App\Models;

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

class VipCardOrder extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'order_number',
        'user_id',
        'vip_card_id',
        'amount',
        'payment_method',
        'payment_status',
        'payment_proof',
        'status',
        'activated_at',
        'expires_at',
        'admin_note',
    ];

    protected $casts = [
        'amount'       => 'decimal:2',
        'activated_at' => 'datetime',
        'expires_at'   => 'datetime',
    ];

    // ---------- boot ----------
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($order) {
            if (empty($order->order_number)) {
                do {
                    $number = 'VIP-' . strtoupper(Str::random(8));
                } while (static::withTrashed()->where('order_number', $number)->exists());
                $order->order_number = $number;
            }
        });
    }

    // ---------- relationships ----------
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function vipCard()
    {
        return $this->belongsTo(VipCard::class);
    }

    // ---------- scopes ----------
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

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

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

    public function scopeExpired($query)
    {
        return $query->where(function ($q) {
            $q->where('status', 'expired')
              ->orWhere(function ($q2) {
                  $q2->where('status', 'active')
                     ->where('expires_at', '<=', now());
              });
        });
    }

    // ---------- helpers ----------
    public function getIsActiveAttribute()
    {
        return $this->status === 'active' && $this->expires_at && $this->expires_at->isFuture();
    }

    public function getIsExpiredAttribute()
    {
        return $this->status === 'active' && $this->expires_at && $this->expires_at->isPast();
    }

    public function getDaysRemainingAttribute()
    {
        if (!$this->is_active) {
            return 0;
        }
        return (int) now()->diffInDays($this->expires_at, false);
    }

    /**
     * Activate membership: set activated_at, expires_at, status = active
     */
    public function activate()
    {
        $this->update([
            'status'       => 'active',
            'activated_at' => now(),
            'expires_at'   => now()->addDays($this->vipCard->duration_days),
        ]);
    }
}
