<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Subscription extends Model
{
    protected $fillable = [
        'user_id', 'plan', 'status',
        'midtrans_order_id', 'midtrans_transaction_id',
        'payment_method', 'payment_channel',
        'amount', 'started_at', 'expired_at', 'midtrans_payload',
    ];

    protected $casts = [
        'started_at'       => 'datetime',
        'expired_at'       => 'datetime',
        'midtrans_payload' => 'array',
    ];

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

    // ── Helpers ───────────────────────────────────────────────────
    public function isActive(): bool
    {
        return $this->status === 'active'
            && ($this->expired_at === null || $this->expired_at->isFuture());
    }

    public function isPro(): bool
    {
        return $this->isActive() && $this->plan === 'pro';
    }

    public function isEnterprise(): bool
    {
        return $this->isActive() && $this->plan === 'enterprise';
    }

    public function daysLeft(): int
    {
        if (!$this->expired_at) return 0;
        return max(0, now()->diffInDays($this->expired_at, false));
    }

    // ── Harga per plan ────────────────────────────────────────────
    public static function planPrice(string $plan): int
    {
        return match($plan) {
            'pro'        => 299000,
            'enterprise' => 0, // custom / hubungi kami
            default      => 0,
        };
    }

    public static function planLabel(string $plan): string
    {
        return match($plan) {
            'pro'        => 'Pro',
            'enterprise' => 'Enterprise',
            default      => 'Gratis',
        };
    }
}