<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class MexcoEventLicense extends Model
{
    protected $table = 'mexco_event_licenses';

    protected $fillable = [
        'event_id',
        'plan_id',
        'status',
        'price_cents',
        'discount_cents',
        'currency',
        'starts_at',
        'ends_at',
        'activated_at',
        'suspended_at',
        'is_campus_sponsored',
        'is_trial',
        'trial_ends_at',
        'sponsorship_value_cents',
        'retention_expires_at',
        'retention_warned_at',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'activated_at' => 'datetime',
            'suspended_at' => 'datetime',
            'retention_expires_at' => 'datetime',
            'is_campus_sponsored' => 'boolean',
            'is_trial' => 'boolean',
            'trial_ends_at' => 'datetime',
            'retention_warned_at' => 'array',
            'metadata' => 'array',
        ];
    }

    public function event(): BelongsTo
    {
        return $this->belongsTo(MeetupEvent::class, 'event_id');
    }

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

    public function eventAddons(): HasMany
    {
        return $this->hasMany(MexcoEventAddon::class, 'event_license_id');
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    public function isTrialActive(): bool
    {
        return $this->is_trial
            && $this->trial_ends_at
            && $this->trial_ends_at->isFuture();
    }

    public function trialDaysRemaining(): ?int
    {
        if (! $this->is_trial || ! $this->trial_ends_at) {
            return null;
        }

        return max(0, (int) now()->diffInDays($this->trial_ends_at, false));
    }
}
