<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

use App\Models\Service;

class ServiceList extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'service:list '.
		'{--a|active : Active Only}'.
		'{--category= : Category}'.
		'{--f|fix : Fix start_date}';

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

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		DB::listen(function($query) {
			Log::debug('- SQL',['sql'=>$query->sql,'binding'=>$query->bindings]);
		});

		$this->warn(sprintf('|%10s|%-6s|%-20s|%-50s|%8s|%14s|%10s|%10s|%10s|%10s|%10s|',
			'ID',
			'CAT',
			'Product',
			'Name',
			'active',
			'status',
			'invoice next',
			'start date',
			'stop date',
			'connect date',
			'first invoice'
			));

		foreach (Service::all() as $o) {
			if ($this->option('active') AND ! $o->isActive())
				continue;

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

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

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

			$this->info(sprintf('|%10s|%-6s|%-20s|%-50s|%8s|%14s|%10s|%10s|%10s|%10s|%10s|',
				$o->sid,
				$o->product->category,
				$o->product_name,
				$o->name_short,
				$o->active ? 'active' : 'inactive',
				$o->status,
				$o->invoice_next ? $o->invoice_next->format('Y-m-d') : NULL,
				$o->date_start ? $o->date_start->format('Y-m-d') : NULL,
				$o->date_end ? $o->date_end->format('Y-m-d') : NULL,
				($o->type AND $o->type->service_connect_date) ? $o->type->service_connect_date->format('Y-m-d') : NULL,
				$c ? $c->date_start->format('Y-m-d') : NULL,
			));
		}
	}
}