<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;

use App\Models\{Service,Site};

class ServiceList extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'service:list'.
		' {--i|inactive : Include Inactive}'.
		' {--t|type= : Type}'.
		' {--f|fix : Fix start_date}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'List all services';

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		$header = '|%13s|%-14s|%-35s|%-40s|%8s|%17s|%12s|%12s|%12s|%12s|%14s|';

		$this->warn(sprintf($header,
			'ID',
			'Type',
			'Product',
			'Name',
			'active',
			'status',
			'invoice next',
			'start date',
			'stop date',
			'connect date',
			'first invoice'
		));

		foreach (Service::withoutGlobalScope(\App\Models\Scopes\SiteScope::class)->with(['site'])->cursor() as $o) {
			if ((! $this->option('inactive')) AND ! $o->isActive())
				continue;

			Config::set('site',$o->site);

			if ($this->option('type') AND ($o->product->getProductTypeAttribute() !== $this->option('type')))
				continue;

			$c = $o->invoice_items->filter(function($item) {return $item->item_type === 0; })->sortby('start_at')->first();

			if ($this->option('fix') AND ! $o->start_at AND $c AND $c->start_at AND $o->type AND $o->type->connect_at AND $c->start_at->format('Y-m-d') == $o->type->connect_at->format('Y-m-d')) {
				$o->start_at = $o->type->connect_at;
				$o->save();
			}

			$this->info(sprintf($header,
				$o->sid,
				$o->product->getProductTypeAttribute(),
				substr($o->product->getNameAttribute(),0,35),
				substr($o->name_short,0,40),
				$o->active ? 'active' : 'inactive',
				$o->status,
				$o->invoice_next ? $o->invoice_next->format('Y-m-d') : NULL,
				$o->start_at ? $o->start_at->format('Y-m-d') : NULL,
				$o->stop_at ? $o->stop_at->format('Y-m-d') : NULL,
				($o->type AND $o->type->connect_at) ? $o->type->connect_at->format('Y-m-d') : NULL,
				($c && $c->date_start) ? $c->date_start->format('Y-m-d') : NULL,
			));
		}
	}
}