<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use App\Models\LmsCourseCategory;

class LicenseDetail extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $with = ['server'];
    protected $appends  = ['services'];
    protected $fillable = [
        'order_id',
        'product_token_no',
        'server_id',
        'front_end_url',
        'back_end_url',
        'product_id',
        'product_price_id',
        'billing_interval_id',
        'quantity',
        'taxable_rate',
        'discount_type',
        'discount_value',
        'registration_date',
        'first_activation',
        'billing_start_date',
        'production',
        'maintenance_mode',
        'type',
        'status',
        'plan_and_packages_id'
    ];

    public function license_registered(): HasOne
    {
        return $this->hasOne(LicenseRegistered::class, 'id', 'order_id');
    }

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

    public function product_price(): HasOne
    {
        return $this->hasOne(ProductPrice::class, 'id', 'product_id');
    }

    public function billing_interval(): HasOne
    {
        return $this->hasOne(BilingInterval::class, 'id', 'billing_interval_id');
    }

    public function server(): HasOne
    {
        return $this->hasOne(Server::class, 'id', 'server_id');
    }

    public function license_activation_history(): HasOne
    {
        return $this->hasOne(LicenseActivationHistory::class, 'license_id', 'id')->latest();
    }

    public function getServicesAttribute()
    {
        $detail = LicenseDetail::select(
            'license_details.*',
            'products.name',
            'license_activation_histories.expiry_date'
        )
            ->leftJoin('license_products', 'license_products.license_id', 'license_details.id')
            ->leftJoin('products', 'products.id', 'license_products.product_id')
            ->leftJoin('license_activation_histories', 'license_activation_histories.license_id', 'license_details.id')
            ->where('license_details.id', $this->id)
            ->first();

        $products = '';

        // foreach ($details as $key => $detail) {
            if (isset($detail->name) && $detail->name != '') {
                $products .= '<b>' . $detail->name . '</b> (' . formatedDate($detail->expiry_date) . ')<br>';
            }
        // }

        return $products;
    }
}
