<?php

namespace App\Models;

use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Casts\AsCollection;
use Illuminate\Database\Eloquent\Collection as DatabaseCollection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Leenooks\Carbon as LeenooksCarbon;

use App\Interfaces\IDs;
use App\Traits\ScopeServiceUserAuthorised;
use App\Traits\SiteID;

/**
 * Class Service
 * Services that belong to an account
 *
 * Attributes for services:
 * + additional_cost			: Pending additional charges for this service (excluding setup)	//@todo check all these are still valid
 * + billing_charge				: Charge for this service each invoice period	// @todo change to "charge"
 * + billing_interval           : The period that this service is billed for by default
 * + billing_interval_string	: The period that this service is billed for by default as a name
 * + billed_to					: When this service has been billed to	// @todo rename all references to invoice_to
 * + category					: The type of service this is, eg: broadband, phone
 * + category_name				: The type of service this is, eg: Broadband, Telephone (in human friendly)
 * + contract_term				: The term that this service must be active
 * + contract_end				: The date that the contract ends for this service
 * + name                       : Service short name with service address
 * + name_short                 : Service Product short name, eg: phone number, domain name, certificate CN
 * + name_detail                : Service Detail, eg: service_address
 * + product					: Our product that is providing this service
 * + sid                        : System ID for service
 * + supplied					: The model of the supplier's product used for this service.
 *
 * = Terminology:
 *   - Offering, what product we supply (we make offerings from supplier's supplied products) - in the DB these are products/*
 *   - Supplied, our supplier's product that is providing the service - in the DB these are supplier/*
 *   - Type, what service we are providing, made up of a product we supply - in the DB these are service/*
 *
 * @package App\Models
 * @todo "Billing Start Date" = "connection date" for sub types??
 */
class Service extends Model implements IDs
{
	use HasFactory,ScopeServiceUserAuthorised,SiteID;

	protected $casts = [
		'order_info'=>AsCollection::class,
	];

	protected $dates = [
		'invoice_last_at',
		'invoice_next_at',
		'start_at',
		'stop_at',
	];

	protected $appends = [
		'category_name',
		'name_short',
	];

	protected $visible = [
	//	'account_name',
	//	'admin_service_id_url',
		'active',
		'category_name',
	//	'billing_price',
	//	'data_orig',
		'id',
		'name_short',
	//	'next_invoice',
	//	'product.name',
	//	'service_id',
	//	'service_id_url',
	//	'status',
	];

	protected $with = [
		//'invoice_items',
		//'product.type.supplied',
		//'type',
	];

	public const INACTIVE_STATUS = [
		'CANCELLED',
		'ORDER-REJECTED',
		'ORDER-CANCELLED',
	];

	/**
	 * Valid status shows the applicable next status for an action on a service
	 * Each status can be
	 *
	 * The structure of each item is:
	 * <ORDER_STATUS> => [
	 *   'next' == next possible levels, initiated by who (array).
	 *             who = 'role','system'
	 *   'enter_method' == the method run when we enter this stage - could be used to send email for example, if this method doesnt complete successfully, we dont enter this stage
	 *                     + If it returns NULL, An error condition
	 *                     + If it returns FALSE, the service cannot enter this stage
	 *                     + If it returns TRUE, the service has successfully changed to this stage
	 *                     + If it returns a VIEW/REDIRECT, that resulting page will handle the status change
	 *   'exit_method' == the method that determines that the order can leave this status (true = can, false = cant)
	 *                     + If it returns NULL, An error condition
	 *                     + If it returns FALSE, the service CANNOT leave this stage
	 *                     + If it returns TRUE, the service CAN leave this stage
	 *                    it will receive the next method as an argument
	 *   'title' == title shown on the menu, for the user to choose
	 * ]
	 * So when an order goes to the next state, the exit method will be tested immediately (if there is only 1 exit method for the user)
	 * to see if it can proceed further if not, it'll wait here for user/admin intervention
	 *
	 * @var array
	 * @todo This needs an overhaul, its not implemented correctly.
	 */
	private const ACTION_PROGRESS = [
		// Order Submitted @todo redo
		'ORDER-SUBMIT' => [
			'fail'=>FALSE,
			// Progress to next stages by who
			'next'=>[
				'ORDER-ACCEPT'=>['customer'],
				'SETUP-PAYMENT-WAIT'=>['reseller','wholesaler']
			],
			// Manual or System moves to the next stage
			'system'=>TRUE,
			'method'=>'action_order_submit',
			'title'=>'Order Submit',
		],
		// Client accepts order, if performed by RW @todo redo
		'ORDER-ACCEPT' => [
			'fail'=>FALSE,
			'next'=>[
				'SETUP-PAYMENT-WAIT'=>['customer'],
			],
			'system'=>FALSE,
			'method'=>'action_order_accept',
			'title'=>'Client Accept Order',
		],
		// If the product has a setup, collect payment information @todo redo
		'SETUP-PAYMENT-WAIT' => [
			'fail'=>FALSE,
			'next'=>[
				'PAYMENT-WAIT'=>['customer'],
			],
			'system'=>FALSE,
			'method'=>'action_setup_payment_wait',
			'title'=>'Setup Payment',
		],
		//  @todo redo
		'PAYMENT-WAIT' => [
			'fail'=>FALSE,
			'next'=>[
				'PAYMENT-CHECK'=>['reseller','wholesaler'],
			],
			'system'=>FALSE,
			'method'=>'action_payment_wait',
			'title'=>'Service Payment',
		],
		//  @todo redo
		'PAYMENT-CHECK' => [
			'fail'=>'ORDER-HOLD',
			'next'=>[
				'ORDER-SENT'=>['wholesaler'],
			],
			'system'=>TRUE,
			'method'=>'action_payment_check',
			'title'=>'Validate Payment Method',
		],
		// Order On Hold (Reason) @todo redo
		'ORDER-HOLD' => ['release'=>'ORDER-SUBMIT','update_reference'=>'ORDER-SENT'],
		// Order Rejected (Reason) @todo redo
		'ORDER-REJECTED' => [],
		// Order Cancelled @todo redo
		'ORDER-CANCELLED' => [],
		// Order Sent to Supplier @todo redo
		'ORDER-SENT' => [
			'fail'=>'ORDER-HOLD',
			'next'=>[
				'ORDERED'=>['wholesaler'],
			],
			'system'=>FALSE,
			'method'=>'action_order_sent',
			'title'=>'Send Order',
		],
		// Order Confirmed by Supplier @todo redo
		'ORDERED' => [
			'fail'=>false,
			'next'=>[
				'PROVISION-HOLD'=>['wholesaler'],
				'PROVISION-PLANNED'=>['wholesaler'],
				'PROVISIONED'=>['wholesaler'],
			],
			'system'=>FALSE,
			'method'=>'action_ordered',
			'title'=>'Service Ordered',
		],
		// Service confirmed by supplier, optional connection date @todo redo
		'PROVISION-PLANNED' => [
			'fail'=>false,
			'next'=>[
				'PROVISIONED'=>['wholesaler'],
			],
			'system'=>FALSE,
			'method'=>'action_provision_planned',
			'title'=>'Provision Planned',
		],
		// Service has been provisioned by supplier @todo redo
		'PROVISIONED' => [
			'fail'=>false,
			'next'=>[
				'ACTIVE'=>['wholesaler'],
			],
			'system'=>FALSE,
			'method'=>'action_provisioned',
			'title'=>'Provisioned',
		],
		// Service is Active
		'ACTIVE' => [
			'next'=>[
				'CANCEL-REQUEST'=>['customer'],
				'CHANGE-REQUEST'=>['customer'],
			],
			'exit'=>'action_active_exit',
			'title'=>'Service Active',
		],
		// Service to be Upgraded
		'CANCEL-CANCEL' => [
			'next'=>[
				'ACTIVE'=>['wholesaler'],
			],
			'enter_method'=>'action_cancel_cancel',
			'title'=>'Cancel Cancellation Request',
		],
		// Service to be Cancelled
		'CANCEL-REQUEST' => [
			'next'=>[
				'CANCEL-CANCEL'=>['wholesaler'],
				'CANCEL-PENDING'=>['wholesaler'],
			],
			'enter_method'=>'action_request_enter_redirect',
			'exit_method'=>'action_cancel_request_exit',
			'title'=>'Cancel Request',
		],
		// Service Cancellation being processed
		'CANCEL-PENDING' => [
			'next'=>[
				'CANCELLED'=>['wholesaler'],
			],
			'enter_method'=>'action_cancel_pending_enter',
			'exit_method'=>'action_cancel_pending_exit',
			'title'=>'Cancel Pending',
		],
		// Service to be Upgraded
		'CHANGE-CANCEL' => [
			'next'=>[
				'ACTIVE'=>['wholesaler'],
			],
			'enter_method'=>'action_change_cancel',
			'title'=>'Cancel Change Request',
		],
		// Service to be Upgraded
		'CHANGE-REQUEST' => [
			'next'=>[
				'CHANGE-PENDING'=>['wholesaler'],
				'CHANGE-CANCEL'=>['wholesaler'],
			],
			'enter_method'=>'action_request_enter_redirect',
			'title'=>'Change Service',
		],

		'CHANGE-PENDING' => [
			'next'=>[
				'ACTIVE'=>['wholesaler'],
			],
			'enter_method'=>'action_request_enter_redirect',
			'title'=>'Activate Change',
		],
	];

	/* INTERFACES */

	/**
	 * Service Local ID
	 *
	 * @return string
	 */
	public function getLIDattribute(): string
	{
		return sprintf('%05s',$this->id);
	}

	/**
	 * Services System ID
	 *
	 * @return string
	 */
	public function getSIDAttribute(): string
	{
		return sprintf('%02s-%04s.%s',$this->site_id,$this->account_id,$this->getLIDattribute());
	}

	/* RELATIONS */

	/**
	 * Account the service belongs to
	 *
	 * @return BelongsTo
	 */
	public function account()
	{
		return $this->belongsTo(Account::class);
	}

	/**
	 * Return automatic billing details
	 *
	 * @return HasOne
	 */
	public function billing()
	{
		return $this->hasOne(AccountBilling::class);
	}

	/**
	 * Return Charges associated with this Service
	 *
	 * @return HasMany
	 */
	public function charges()
	{
		return $this->hasMany(Charge::class)
			->where('active','=',TRUE)
			->orderBy('created_at');
	}

	// @todo changed to invoiced_items
	public function invoice_items($active=TRUE)
	{
		$query = $this->hasMany(InvoiceItem::class)
			->where('item_type','=',0)
			->orderBy('start_at');

		// @todo Change to $query->active();
		if ($active)
			$query->where('active','=',TRUE);

		return $query;
	}

	/**
	 * Invoices for this service
	 */
	public function invoices($active=TRUE)
	{
		$query = $this->hasManyThrough(Invoice::class,InvoiceItem::class,NULL,'id',NULL,'invoice_id')
			->distinct('id')
			->where('invoices.site_id','=',$this->site_id)
			->where('invoice_items.site_id','=',$this->site_id)
			->orderBy('created_at')
			->orderBy('due_at');

		if ($active)
			$query->where('invoice_items.active','=',TRUE)
				->where('invoices.active','=',TRUE);

		return $query;
	}

	/**
	 * Account that ordered the service
	 *
	 * @return BelongsTo
	 */
	public function orderedby()
	{
		return $this->belongsTo(Account::class);
	}

	/**
	 * Product of the service
	 *
	 * @return BelongsTo
	 */
	public function product()
	{
		return $this->belongsTo(Product::class);
	}

	/**
	 * Return a child model with details of the service
	 *
	 * @return MorphTo
	 */
	public function type()
	{
		return $this->morphTo(null,'model','id','service_id');
	}

	/* SCOPES */

	/**
	 * Only query active categories
	 */
	public function scopeActive($query)
	{
		return $query->where(function () use ($query) {
			$query->where($this->getTable().'.active',TRUE)
				->orWhereNotIn('order_status',self::INACTIVE_STATUS);
		});
	}

	/**
	 * Find inactive services.
	 *
	 * @param $query
	 * @return mixed
	 */
	public function scopeInActive($query)
	{
		return $query->where(function () use ($query) {
			$query->where($this->getTable().'.active',FALSE)
				->orWhereIn('order_status',self::INACTIVE_STATUS);
		});
	}

	/**
	 * Enable to perform queries without eager loading
	 *
	 * @param $query
	 * @return mixed
	 */
	public function scopeNoEagerLoads($query){
		return $query->setEagerLoads([]);
	}

	/**
	 * Search for a record
	 *
	 * @param        $query
	 * @param string $term
	 * @return mixed
	 */
	public function scopeSearch($query,string $term)
	{
		$t = '%'.$term.'%';

		return $query->select('services.*')
			->where('services.id','like',$t)
			->leftJoin('service_broadband',['service_broadband.service_id'=>'services.id'])
			->orWhere('service_broadband.service_number','like',$t)
			->orWhere('service_broadband.service_address','like',$t)
			->orWhere('service_broadband.ipaddress','like',$t)
			->leftJoin('service_phone',['service_phone.service_id'=>'services.id'])
			->orWhere('service_phone.service_number','like',$t)
			->orWhere('service_phone.service_address','like',$t)
			->leftJoin('service_domain',['service_domain.service_id'=>'services.id'])
			->orWhere('service_domain.domain_name','like',$t)
			->leftJoin('service_email',['service_email.service_id'=>'services.id'])
			->orWhere('service_email.domain_name','like',$t)
			->leftJoin('service_host',['service_host.service_id'=>'services.id'])
			->orWhere('service_host.domain_name','like',$t);
	}

	/* ATTRIBUTES */

	/**
	 * How much do we charge for this service, base on the current recur schedule
	 *
	 * @return float
	 */
	public function getBillingChargeAttribute(): float
	{
		// @todo Temporary for services that dont have recur_schedule set.
		if (is_null($this->recur_schedule) OR is_null($this->product->getBaseChargeAttribute($this->recur_schedule,$this->account->group)))
			$this->price=0;

		return $this->addTax(is_null($this->price) ? $this->product->getBaseChargeAttribute($this->recur_schedule,$this->account->group) : $this->price);
	}

	/**
	 * Return the service billing period
	 *
	 * @return int
	 */
	public function getBillingIntervalAttribute(): int
	{
		return $this->recur_schedule ?: $this->product->getBillingIntervalAttribute();
	}

	/**
	 * Return a human friendly name for the billing interval
	 *
	 * @return string
	 */
	public function getBillingIntervalStringAttribute(): string
	{
		return Invoice::billing_name($this->getBillingIntervalAttribute());
	}

	/**
	 * Determine a monthly price for a service, even if it is billed at a different frequency
	 *
	 * @return float
	 * @throws Exception
	 */
	public function getBillingMonthlyPriceAttribute(): float
	{
		return number_format($this->getBillingChargeAttribute()/Arr::get(Invoice::billing_periods,$this->recur_schedule.'.interval',1),2);
	}

	public function getCategoryAttribute(): string
	{
		return $this->product->category;
	}

	public function getCategoryNameAttribute(): string
	{
		return $this->product->category_name;
	}

	/**
	 * The date the contract ends
	 *
	 * Service contracts end the later of the start_date + contract_term or the expire date.
	 *
	 * @return Carbon
	 */
	public function getContractEndAttribute(): ?Carbon
	{
		// If we have no start date or expire date, then NULL;
		if (! $this->start_at && ! $this->type->expire_at)
			return NULL;

		// If we dont have a start date, use the expire date
		if (! $this->start_at)
			return $this->type->expire_at;

		$end = $this->start_at->addMonths($this->getContractTermAttribute());

		// If we dont have an expire date, use the start date + contract_term
		if (! $this->type->expire_at)
			return $end;

		// We have both, so it's the later of the two.
		return ($end < $this->type->expire_at) ? $this->type->expire_at : $end;
	}

	/**
	 * This function will determine the minimum contract term for a service, which is the maximum of
	 * supplier->type->contract_term, or the product->type->contract_term;
	 *
	 * @return int
	 */
	public function getContractTermAttribute(): int
	{
		return $this->getSuppliedAttribute()->contract_term;
	}

	/**
	 * Date the service expires, also represents when it is paid up to
	 *
	 * @return string
	 * @todo
	 */
	public function getExpiresAttribute(): string
	{
		abort(500,'Not implemented');
		return 'TBA';
	}

	/**
	 * Return the date for the next invoice
	 *
	 * @return LeenooksCarbon
	 */
	public function getInvoiceNextAttribute(): LeenooksCarbon
	{
		$last = $this->getInvoiceToAttribute();
		return $last
			? $last->addDay()
			: ($this->invoice_next_at ? $this->invoice_next_at->clone() : ($this->start_at ?: LeenooksCarbon::now()));
	}

	/**
	 * We need to cast some dates to LeenooksCarbon to get access to startOfHalf()/endOfHalf() methods
	 *
	 * @param $value
	 * @return LeenooksCarbon|null
	 */
	public function getInvoiceNextAtAttribute($value): ?LeenooksCarbon
	{
		return $value ? LeenooksCarbon::create($value) : NULL;
	}

	/**
	 * Return the end date for the next invoice
	 *
	 * @return mixed
	 * @throws Exception
	 */
	public function getInvoiceNextEndAttribute()
	{
		switch ($this->recur_schedule) {
			case Invoice::BILL_WEEKLY:
				$date = $this->product->price_recur_strict
					? $this->getInvoiceNextAttribute()->endOfWeek()
					: $this->getInvoiceNextAttribute()->addWeek()->subDay();
				break;

			case Invoice::BILL_MONTHLY:
				$date = $this->product->price_recur_strict
					? $this->getInvoiceNextAttribute()->endOfMonth()
					: $this->getInvoiceNextAttribute()->addMonth()->subDay();
				break;

			case Invoice::BILL_QUARTERLY:
				$date = $this->product->price_recur_strict
					? $this->getInvoiceNextAttribute()->endOfQuarter()
					: $this->getInvoiceNextAttribute()->addQuarter()->subDay();
				break;

			case Invoice::BILL_SEMI_YEARLY:
				$date = $this->product->price_recur_strict
					? $this->getInvoiceNextAttribute()->endOfHalf()
					: $this->getInvoiceNextAttribute()->addQuarter(2)->subDay();
				break;

			case Invoice::BILL_YEARLY:
				$date = $this->product->price_recur_strict
					? $this->getInvoiceNextAttribute()->endOfYear()
					: $this->getInvoiceNextAttribute()->addYear()->subDay();
				break;

			case Invoice::BILL_TWOYEARS:
				if (! $this->product->price_recur_strict) {
					$date = $this->getInvoiceNextAttribute()->addYear(2)->subDay();

				} else {
					$date = $this->getInvoiceNextAttribute()->addYear(2)->subDay()->endOfYear();

					if ($date->clone()->addDay()->year%2)
						$date = $date->subYear();
				}
				break;

			// NOTE: price_recur_strict ignored
			case Invoice::BILL_THREEYEARS:
				$date = $this->getInvoiceNextAttribute()->addYear(3)->subDay();
				break;

			// NOTE: price_recur_strict ignored
			case Invoice::BILL_FOURYEARS:
				$date = $this->getInvoiceNextAttribute()->addYear(4)->subDay();
				break;

			// NOTE: price_recur_strict ignored
			case Invoice::BILL_FIVEYEARS:
				$date = $this->getInvoiceNextAttribute()->addYear(5)->subDay();
				break;

			default:
				throw new Exception('Unknown recur_schedule');
		}

		// If the invoice has an end date, our invoice period shouldnt be greater than that.
		if ($this->stop_at AND $this->stop_at < $date)
			$date = $this->stop_at;

		return $date;
	}

	/**
	 * Determine how much quantity (at the charge rate) is required for the next invoice
	 *
	 * @return float
	 * @throws Exception
	 */
	public function getInvoiceNextQuantityAttribute(): float
	{
		// If we are not rounding to the first day of the cycle, then it is always a full cycle
		if (! $this->product->price_recur_strict)
			return 1;

		$n = $this->invoice_next->diff($this->invoice_next_end)->days+1;

		switch ($this->recur_schedule) {
			case Invoice::BILL_WEEKLY:
				$d = $this->invoice_next->addWeek()->startOfWeek()->diff($this->invoice_next_end->startOfWeek())->days;
				break;

			case Invoice::BILL_MONTHLY:
				$d = $this->invoice_next->addMonth()->startOfMonth()->diff($this->invoice_next_end->startOfMonth())->days;
				break;

			case Invoice::BILL_QUARTERLY:
				$d = $this->invoice_next->addQuarter()->startOfQuarter()->diff($this->invoice_next_end->startOfQuarter())->days;
				break;

			case Invoice::BILL_SEMI_YEARLY:
				$d = $this->invoice_next->addQuarter(2)->startOfHalf()->diff($this->invoice_next_end->startOfHalf())->days;
				break;

			case Invoice::BILL_YEARLY:
				$d = $this->invoice_next->addYear()->startOfYear()->diff($this->invoice_next_end->startOfYear())->days;
				break;

			case Invoice::BILL_TWOYEARS:
				$d = $this->invoice_next->addYear(2)->startOfYear()->diff($this->invoice_next_end->subyear(2))->days-1;
				break;

			case Invoice::BILL_THREEYEARS:
				$d = $this->invoice_next->addYear(3)->startOfYear()->diff($this->invoice_next_end->subyear(3))->days-1;
				break;

			case Invoice::BILL_FOURYEARS:
				$d = $this->invoice_next->addYear(3)->startOfYear()->diff($this->invoice_next_end->subyear(4))->days-1;
				break;

			case Invoice::BILL_FIVEYEARS:
				$d = $this->invoice_next->addYear(3)->startOfYear()->diff($this->invoice_next_end->subyear(5))->days-1;
				break;

			default:
				throw new Exception('Unknown recur_schedule');
		}

		return round($n/$d,2);
	}

	/**
	 * Get the date that the service has been invoiced to
	 *
	 * @return LeenooksCarbon|null
	 */
	public function getInvoiceToAttribute(): ?LeenooksCarbon
	{
		return ($x=$this->invoice_items->filter(function($item) { return $item->item_type === 0;}))->count()
			? $x->last()->stop_at
			: NULL;
	}

	/**
	 * The full name for a service, comprised of the short name and the description
	 *
	 * @return string
	 */
	public function getNameAttribute(): string
	{
		return $this->getNameShortAttribute().(($x=$this->getNameDetailAttribute()) ? ': '.$x : '');
	}

	/**
	 * Return the short name for the service.
	 *
	 * EG:
	 * + For ADSL, this would be the phone number,
	 * + For Hosting, this would be the domain name, etc
	 */
	public function getNameShortAttribute()
	{
		return $this->type->getServiceNameAttribute() ?: 'SID:'.$this->sid;
	}

	/**
	 * Return the service description.
	 * For:
	 * + Broadband, this is the service address
	 * + Domains, blank
	 * + Hosting, blank
	 * + SSL, blank
	 *
	 * @return string
	 */
	public function getNameDetailAttribute()
	{
		return $this->type->getServiceDescriptionAttribute();
	}

	/**
	 * The product we supply for this service
	 *
	 * @return Model
	 */
	public function getOfferingAttribute(): Model
	{
		return $this->product->type;
	}

	public function getOrderInfoNotesAttribute(): ?string
	{
		return $this->getOrderInfoValue('notes');
	}

	public function getOrderInfoReferenceAttribute(): ?string
	{
		return $this->getOrderInfoValue('reference');
	}

	/**
	 * Work out when this service has been paid to.
	 *
	 * @return Carbon
	 */
	public function getPaidToAttribute(): Carbon
	{
		foreach ($this->invoices->reverse() as $o)
			if ($o->due == 0)
				break;

		return $o->items
			->filter(function($item) {
				return $item->item_type === 0;
			})
			->last()
			->stop_at;
	}

	/**
	 * Return the billing recurring configuration for this service
	 *
	 * @param $value
	 * @return int
	 */
	public function getRecurScheduleAttribute($value): int
	{
		// If recur_schedule not set, default to quarterly
		return $value ?? Invoice::BILL_QUARTERLY;
	}

	/**
	 * We need to cast some dates to LeenooksCarbon to get access to startOfHalf()/endOfHalf() methods
	 *
	 * @param $value
	 * @return LeenooksCarbon
	 */
	public function getStartAtAttribute($value): LeenooksCarbon
	{
		return LeenooksCarbon::create($value);
	}

	/**
	 * Return the Service Status
	 *
	 * @return string
	 */
	public function getStatusAttribute(): string
	{
		if (! $this->order_status)
			return $this->active ? 'ACTIVE' : 'INACTIVE';
		else
			return $this->order_status;
	}

	/**
	 * Return an HTML status box
	 *
	 * @return string
	 * @todo Add in the other status'
	 */
	public function getStatusHTMLAttribute(): string
	{
		$class = NULL;

		if ($this->isPending())
			$class = 'badge-warning';

		else
			switch ($this->status)
			{
				case 'ACTIVE':
					$class = 'badge-success';
					break;
				case 'INACTIVE':
					$class = 'badge-danger';
					break;
			}

		return $class
			? sprintf('<span class="badge %s">%s</span>',$class,$this->status)
			: $this->status;
	}

	/**
	 * Return the product that supplies this service
	 * ie: product/*
	 *
	 * @return Model
	 */
	public function getSuppliedAttribute(): Model
	{
		return $this->getOfferingAttribute()->supplied;
	}

	/* METHODS */

	/**
	 * Processing when service has been ordered.
	 *
	 * @return bool|null
	 * @todo Check
	 */
	private function action_ordered(): ?bool
	{
		// N/A
		return TRUE;
	}

	/**
	 * Process for an order when status ORDER-ACCEPT stage.
	 * This method should have the client confirm/accept the order, if it was placed by a reseller/wholesaler.
	 *
	 * @return bool
	 * @todo Check
	 */
	private function action_order_accept(): ?bool
	{
		// @todo TO IMPLEMENT
		return TRUE;
	}

	/**
	 * Action method when status ORDER_SENT
	 * This method redirects to a form, where updating the form will progress to the next stage.
	 *
	 * @todo Check
	 */
	private function action_order_sent(string $next)
	{
		// We can proceed to the ordered status
		if ($next == 'ORDERED' AND $this->order_info_reference)
			return TRUE;

		throw new HttpException(301,url('r/service/update',$this->id));
	}

	/**
	 * Action method when status ORDER_SUBMIT
	 *
	 * @return bool
	 * @todo Check
	 */
	private function action_order_submit(): ?bool
	{
		// @todo TO IMPLEMENT
		return TRUE;
	}

	/**
	 * Action when supplier has confirmed provisioning.
	 *
	 * @param string $next
	 * @return bool
	 * @todo Check
	 */
	private function action_provision_planned(string $next)
	{
		throw new HttpException(301,url('r/service/update',$this->id));
	}

	/**
	 * Process for an order when status SETUP-PAYMENT-WAIT stage.
	 * This method should collect any setup fees payment.
	 *
	 * @return bool
	 * @todo Check
	 */
	private function action_setup_payment_wait(): ?bool
	{
		// @todo TO IMPLEMENT
		return TRUE;
	}

	/**
	 * Process for an order when status PAYMENT-CHECK stage.
	 * This method should validate any payment details.
	 *
	 * @return bool
	 * @todo Check
	 */
	private function action_payment_check(): ?bool
	{
		// @todo TO IMPLEMENT
		return TRUE;
	}

	/**
	 * Process for an order when status PAYMENT-WAIT stage.
	 * This method should collect any service payment details.
	 *
	 * @return bool
	 * @todo Check
	 */
	private function action_payment_wait(): ?bool
	{
		// @todo TO IMPLEMENT
		return TRUE;
	}

	/**
	 * Work out the next applicable actions for this service status, taking into account the user's role
	 *
	 * @notes
	 *       + Clients can only progress 1 step, if they are in the next step.
	 *       + Resellers/Wholesales can progress to the next Reseller/Wholesaler and any steps in between.
	 * @return Collection
	 */
	public function actions(): Collection
	{
		$next = $this->getStageParameters($this->order_status)->get('next');
		return $next
			? $next->map(function($item,$key) {
				$authorized = FALSE;

				if ($x=Arr::get(self::ACTION_PROGRESS,$key))
					foreach ($item as $role) {
						if ($this->isAuthorised($role)) {
							$authorized = TRUE;
							break;
						}
					}

				return $authorized ? $x['title'] : NULL;
			})->filter()->sort()
			: collect();
	}

	/**
	 * Add applicable tax to the cost
	 *
	 * @todo This needs to be calculated, not fixed at 1.1
	 * @todo move all tax calculations into product
	 * @param float $value
	 * @return float
	 */
	private function addTax(float $value): float
	{
		return round($value*1.1,2);
	}

	private function getOrderInfoValue(string $key): ?string
	{
		return $this->order_info ? $this->order_info->get($key) : NULL;
	}

	/**
	 * Get the stage parameters
	 *
	 * @param string $stage
	 * @return Collection
	 */
	public function getStageParameters(string $stage): Collection
	{
		$result = Arr::get(self::ACTION_PROGRESS,$stage);
		$myrole = array_search(Auth::user()->role(),User::role_order);

		// If we have no valid next stage, return an empty collection.
		if (($myrole === FALSE) || (! $result))
			return collect();

		// Filter the result based on who we are
		$next = collect();

		if (array_key_exists('next',$result) && count($result['next'])) {
			foreach ($result['next'] as $action => $roles) {
				// Can the current user do this role?
				$cando = FALSE;

				foreach ($roles as $role) {
					if ($myrole <= array_search($role,User::role_order)) {
						$cando = TRUE;

						break;
					}
				}

				if ($cando)
					$next->put($action,$roles);
			}

			$result['next'] = $next;
		}

		return collect($result);
	}

	/**
	 * Does this service have traffic data to be graphed
	 *
	 * @return bool
	 */
	public function hasUsage(): bool
	{
		return $this->product->hasUsage();
	}

	/**
	 * Determine if a service is active. It is active, if active=1, or the order_status is not in self::INACTIVE_STATUS[]
	 *
	 * @return bool
	 * @todo Remove active and have order_status reflect whether active or not
	 */
	public function isActive(): bool
	{
		return $this->active OR ($this->order_status AND ! in_array($this->order_status,self::INACTIVE_STATUS));
	}

	/**
	 * Determine if the current user has the role for this service
	 *
	 * @param string $role
	 * @return bool
	 * @todo Can we use the gates to achieve this?
	 */
	public function isAuthorised(string $role): bool
	{
		switch(Auth::user()->role()) {
			// Wholesalers are site admins, they can see everything
			case 'wholesaler':
				return TRUE;

			case 'reseller':
				switch ($role) {
					case 'wholesaler':
						return FALSE;

					// Check service is in the resellers/customers list
					case 'reseller':
					case 'customer':
						return TRUE;

					default:
						abort(500,'Unknown role for reseller: '.$role);
				}

			case 'customer':
				switch ($role) {
					case 'reseller':
					case 'wholesaler':
						return FALSE;

					// Check service is in the customers list
					case 'customer':
						return TRUE;

					default:
						abort(500,'Unknown role for customer: '.$role);
				}

			default:
				abort(500,'Unknown user role: ',Auth::user()->role());
		}

		return FALSE;
	}

	/**
	 * Do we bill for this service
	 *
	 * @return bool
	 */
	public function isBilled(): bool
	{
		return ! ($this->external_billing && $this->suspend_billing);
	}

	/**
	 * Should this service be invoiced soon
	 *
	 * @param int $days
	 * @return bool
	 */
	public function isInvoiceDueSoon($days=30): bool
	{
		return $this->isBilled() AND $this->getInvoiceNextAttribute()->lessThan(now()->addDays($days));
	}

	/**
	 * Identify if a service is being ordered, ie: not active yet nor cancelled
	 *
	 * @return bool
	 */
	public function isPending(): bool
	{
		return ! $this->active
			AND ! is_null($this->order_status)
			AND ! in_array($this->order_status,array_merge(self::INACTIVE_STATUS,['INACTIVE']));
	}

	/**
	 * Generate a collection of invoice_item objects that will be billed for the next invoice
	 *
	 * @param bool $future Next item to be billed (not in the next x days)
	 * @param Carbon|null $billdate
	 * @return Collection
	 * @throws Exception
	 * @todo This query is expensive.
	 */
	public function next_invoice_items(bool $future,Carbon $billdate=NULL): Collection
	{
		if ($this->wasCancelled() OR (! $this->isBilled()) OR (! $future AND ! $this->active))
			return collect();

		if (is_null($billdate))
			$billdate = Carbon::now()->addDays(30);

		// If pending, add any connection charges
		// Connection charges are only charged once
		if ((! $this->invoice_items->filter(function($item) { return $item->item_type==4; })->sum('total'))
			AND ($this->isPending() OR is_null($this->invoice_to))
			AND $this->product->getSetupChargeAttribute($this->recur_schedule,$this->account->group))
		{
			$o = new InvoiceItem;

			$o->active = TRUE;
			$o->service_id = $this->id;
			$o->product_id = $this->product_id;
			$o->item_type = 4; // @todo change to const or something
			$o->price_base = $this->product->getSetupChargeAttribute($this->recur_schedule,$this->account->group);
			//$o->recurring_schedule = $this->recur_schedule;
			$o->start_at = $this->invoice_next;
			$o->stop_at = $this->invoice_next;
			$o->quantity = 1;
			$o->site_id = 1; // @todo

			$o->addTaxes($this->account->country->taxes);
			$this->invoice_items->push($o);
		}

		// If the service is active, there will be service charges
		if ((! $this->invoice_items->filter(function($item) { return $item->item_type==0 AND ! $item->exists; })->count())
			AND ($this->active OR $this->isPending())
			AND (
				(($future == TRUE) AND $this->invoice_next < $this->invoice_next_end) OR
				(($future == FALSE) AND ($this->invoice_to < ($this->stop_at ?: $billdate)))
			))
		{
			do {
				$o = new InvoiceItem;
				$o->active = TRUE;
				$o->service_id = $this->id;
				$o->product_id = $this->product_id;
				$o->item_type = 0;
				$o->price_base = is_null($this->price)
					? (is_null($this->price_override) ? $this->product->getBaseChargeAttribute($this->recur_schedule,$this->account->group) : $this->price_override)
					: $this->price; // @todo change to a method in this class
				$o->recur_schedule = $this->recur_schedule;
				$o->start_at = $this->invoice_next;
				$o->stop_at = $this->invoice_next_end;
				$o->quantity = $this->invoice_next_quantity;
				$o->site_id = 1; // @todo

				$o->addTaxes($this->account->country->taxes);
				$this->invoice_items->push($o);
			} while ($future == FALSE AND ($this->invoice_to < ($this->stop_at ?: $billdate)));
		}

		// Add additional charges
		if ((($future == TRUE) OR (($future == FALSE) AND ($this->invoice_to >= $billdate)))
			AND ! $this->invoice_items->filter(function($item) { return $item->module_id == 30 AND ! $item->exists; })->count())
		{
			foreach ($this->charges->filter(function($item) { return ! $item->processed; }) as $oo) {
				$o = new InvoiceItem;
				$o->active = TRUE;
				$o->service_id = $oo->service_id;
				$o->product_id = $this->product_id;
				$o->quantity = $oo->quantity;
				$o->item_type = $oo->type;
				$o->price_base = $oo->amount;
				$o->start_at = $oo->start_at;
				$o->stop_at = $oo->stop_at;
				$o->module_id = 30; // @todo This shouldnt be hard coded
				$o->module_ref = $oo->id;
				$o->site_id = 1; // @todo

				$o->addTaxes($this->account->country->taxes);
				$this->invoice_items->push($o);
			}
		}

		return $this->invoice_items->filter(function($item) { return ! $item->exists; });
	}

	/**
	 * Service that was cancelled or never provisioned
	 *
	 * @return bool
	 */
	public function wasCancelled(): bool
	{
		return in_array($this->order_status,self::INACTIVE_STATUS);
	}
}