<?php

namespace App\Models;

use App\Traits\Excludable;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class LicenseKey extends Model {
    use Excludable;

    protected $fillable = [
        'product_id',
        'owner_name',
        'owner_email',
        'activation_limit',
        'validity',
        'assigned_at',
        'status'
    ];

    protected $appends = [ 'meta_data' ];

    public function getMetaDataAttribute(): Collection {
        return $this->hasMany( Meta::class, 'item_id' )->select( [ 'key', 'value' ] )->where( 'type', 'license_key' )->get();
    }

    public function getExpiration(): bool|Carbon {
        if ( $this->assigned_at != null && $this->validity > 0 ) {
            $date = Carbon::createFromFormat( 'Y-m-d H:i:s', $this->assigned_at );

            return $date->addDays( $this->validity );
        }

        return false;
    }

    public function isExpired(): bool {
        $expirationDate = $this->getExpiration();
        if ( $expirationDate ) {
            return $expirationDate->isPast();
        }

        return false;
    }

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

    public static function getStatuses(): array {
        return [
            'available' => [
                'text'  => __( 'Available' ),
                'color' => '#2ecc71'
            ],
            'assigned'  => [
                'text'  => __( 'Assigned' ),
                'color' => '#3498db'
            ],
            'reserved'  => [
                'text'  => __( 'Reserved' ),
                'color' => '#8e44ad'
            ],
            'blocked'   => [
                'text'  => __( 'Blocked' ),
                'color' => '#c0392b'
            ],
        ];
    }
}
