<?php

namespace App\Console\Commands;

use Carbon\Carbon;
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'
		.' {--l|list : List Items}'
		.' {--p|preview : Preview}'
		.' {--s|site : Site ID}'
		.' {id?}';

	/**
	 * 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',
			$this->option('site')
				? Site::findOrFail($this->option('site'))
				: Site::where('url',config('app.url'))->sole()
		);

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

		foreach ($accounts as $o) {
			$items = $o->invoice_next(Carbon::now());

			if (! $items->count()) {
				$this->warn(sprintf('No items for account (%s) [%d]',$o->name,$o->id));
				continue;
			}

			$this->info(sprintf('Account: %s [%d]',$o->name,$o->lid));
			$io = new Invoice;
			$io->account_id = $o->id;

			foreach ($items as $oo)
				$io->items_active->push($oo);

			// If there are no items, no reason to do anything
			if ($io->total < 0) {
				$this->warn(sprintf(' - Invoice totals [%3.2f] - skipping',$io->total));
				continue;
			}

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

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

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

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

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

			$io->pushNew();
		}

		return self::SUCCESS;
	}
}