<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class LicenseRegistered extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $with     = ['bill_to', 'project', 'manager'];
    protected $appends  = ['services', 'tax'];
    protected $fillable = [
        'order_date',
        'license_date',
        'license_no',
        'project_code',
        'bill_to_account_id',
        'ship_to_account_id',
        'billing_company_id',
        'license_note',
        'client_remarks',
        'license_status',
        'project_id',
        'partner_id',
        'sales_person_id',
        'last_issue_count',
        'account_manager_id',
        'license_key',
        'license_secret',
    ];
    /**
     * Get child record.
     */
    public function bill_to(): HasOne
    {
        return $this->HasOne(Account::class, 'id', 'bill_to_account_id');
    }

    public function manager(): HasOne
    {
        return $this->HasOne(Account::class, 'id', 'account_manager_id');
    }

    /**
     * Get child record.
     */
    public function project(): HasOne
    {
        return $this->HasOne(Projects::class, 'id', 'project_id');
    }

    public function license_detail(): HasOne
    {
        return $this->HasOne(LicenseDetail::class, 'order_id', 'id')->with('license_activation_history');
    }

    public function getServicesAttribute()
    {
        $details = 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('order_id', $this->id)
            ->get();

        $products = '';

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

        return $products;
    }

    public function getTaxAttribute()
    {
        $product = LicenseDetail::select(
            'license_details.*',
            'tax_masters.name AS tax'
        )
            ->leftJoin('license_products', 'license_products.license_id', 'license_details.id')
            ->leftJoin('products', 'products.id', 'license_products.product_id')
            ->leftJoin('tax_masters', 'tax_masters.id', 'products.tax_slab_id')
            ->where('order_id', $this->id)
            ->first();

        return isset($product->tax) ? $product->tax : ''; 
    }
}
