<?php

namespace Hilco\Models;

class VATTax extends UuidModel
{
    protected $table = 'VATTaxes';

    public function parts() {
        return $this->hasMany(Part::class, 'vat_code', 'vat_code');
    }

    public function scopeActive($query) {
        return $query
            ->where(function ($query) {
                return $query
                    ->where('effective_date', '<=', 'DATE(NOW())')
                    ->where('expiration_date', '>=', 'DATE(NOW())')
                ;
            })
            ->orWhere('expiration_date', '=', '0000-00-00')
        ;
    }

    public function scopeCode($query, $code) {
        return $query->where('vat_code', '=', $code);
    }

    public static function rateForCode($code) {
        return self::active()->code($code)->value('tax_percentage');
    }

    public static function standardRate() {
        return self::rateForCode('STD-RATED');
    }

    public static function findByVATCode ($vatCode): ?VATTax {
        return self::where('vat_code', '=', $vatCode)->first();
    }

    public static function findFromPlantAndPart ($plant, $part): ?VATTax {
        $inventoryItem = InventoryItem::findFromPlantAndPart($plant, $part);
        if (is_null($inventoryItem)) {
            return null;
        } else {
            return is_null($inventoryItem->vat_code) ? null : self::findByVATCode($inventoryItem->vat_code);
        }
    }
}
