<?php

namespace App\Console\Commands;

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

use App\Models\{Account,Invoice,Site};

class InvoiceGenerate extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'invoice:generate {site} {account?} {--p|preview : Preview} {--l|list : List Items}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Generate Invoices to be Sent';

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		Config::set('site',Site::findOrFail($this->argument('site')));

		if ($this->argument('account'))
			$accounts = collect()->push(Account::find($this->argument('account')));
		else
			$accounts = Account::active()->get();

		foreach ($accounts as $o) {
			$io = new Invoice;
			$io->account_id = $o->id;

			foreach ($o->services(TRUE)->get() as $so) {
				foreach ($so->next_invoice_items(FALSE) as $ooo)
					$io->items->push($ooo);
			}

			// If there are no items, no reason to do anything
			if (! $io->items->count() OR $io->total < 0)
				continue;

			$io->account_id = $o->id;

			if ($this->option('list')) {
				$this->warn(sprintf('|%4s|%4s|%-50s|%8s|',
					'SID',
					'PID',
					'Name',
					'Amount',
				));

				foreach ($io->items as $oo) {
					$this->info(sprintf('|%4s|%4s|%-50s|%8.2f|',
						$oo->service_id,
						$oo->product_id,
						$oo->item_type_name,
						$oo->total,
					));
				}
			}

			if ($this->option('preview')) {
				$this->info(sprintf('Invoice for Account [%d] - [%d] items totalling [%3.2f]',$o->id,$io->items->count(),$io->total));
				continue;
			}

			// Save the invoice
			$io->site_id = 1;   // @todo
			$io->active = 1;

			$io->pushNew();
		}
	}
}