<?php

namespace App\Console\Commands\Billing;

use App\Console\Commands\BaseCommand;
use Carbon\Carbon;

use App\Models\Billing\BillingCommit;
use App\Models\Billing\Invoice;
use App\Repositories\OverageRepository;

class GenerateInvoices extends BaseCommand
{

    protected $signature = 'billing:generate-invoices {--closing=} {--info}';

    protected $description = 'Generates invoices using commits';

    protected $notEnterprise = true;

    public function calculatePeriod($previous_month, $now, $commit) {
        
        return [    
            Carbon::createFromDate($previous_month->year, $previous_month->month, $commit->billing_day, 'Australia/Sydney')->setHour(0)->setMinutes(0)->setSeconds(0),
            Carbon::createFromDate($now->year, $now->month, $commit->billing_day - 1, 'Australia/Sydney')->setHour(23)->setMinutes(59)->setSeconds(59)
        ];
    }

    public function handle()
    {
        $o_repo = new OverageRepository();

        $verbose = ($this->option('info') ?? false) !== false; 
        $billing_day = $this->option('closing') ?? Carbon::now()->day;

        if($verbose) {
            echo "Processing all overages for DAY $billing_day \n";
        }

        // We should iterate over each commit that is presently active
        $recent_commits = BillingCommit::whereIn('id', BillingCommit::selectRaw('MAX(id)')->where([['effective_at', '<=', now()], ['billing_day', '=', $billing_day]])->groupBy('whmcs_brand', 'whmcs_client_id', 'whmcs_service_id')->get())->get();

        foreach($recent_commits as $commit) {

            $now = Carbon::now();
            $previous_month = Carbon::now()->subMonth();

            [$start_of_period, $end_of_period] = $this->calculatePeriod($previous_month, $now, $commit);

            /**
             * Skip any invoice that has already been worked on - We only look back into the past six months, as realistically you shouldn't be generating something that late...
             */

            if(Invoice::where([ [ 'start', '>', Carbon::now()->subMonths(6) ], [ 'month', '=', $previous_month->month ], [ 'whmcs_brand', '=', $commit->whmcs_brand ], [ 'whmcs_client_id', '=', $commit->whmcs_client_id ], [ 'whmcs_service_id', '=', $commit->whmcs_service_id ] ])->count()) {
                if($verbose) {
                    echo "Skipping $commit->whmcs_brand-CLI-$commit->whmcs_client_id-SER-$commit->whmcs_service_id @ $commit->price_per_unit $commit->currency over $commit->commit mbit for $start_of_period - $end_of_period \n";
                }

                continue;
            }

            /**
             * We should pull the invoice, validate it, then create it
             */

            if($verbose) {
                echo "Processing $commit->whmcs_brand-CLI-$commit->whmcs_client_id-SER-$commit->whmcs_service_id @ $commit->price_per_unit $commit->currency over $commit->commit mbit for $start_of_period - $end_of_period with $commit->method aggregate \n";
            }

            $notification = '';

            // Acknowledge that we've done anything with this invoice
            Invoice::create([
                'month'             => $previous_month->month,
                'whmcs_brand'       => $commit->whmcs_brand,
                'whmcs_client_id'   => $commit->whmcs_client_id,
                'whmcs_service_id'  => $commit->whmcs_service_id,
                'start'             => $start_of_period,
                'finish'            => $end_of_period
            ])->save();

            if($commit->whmcs_client_id == 1000659) {
                $commit->method = 'australian';
            }

            if($o_repo->postOverage($commit->whmcs_brand, $commit->whmcs_client_id, $commit->whmcs_service_id, $commit->search_service, $start_of_period->unix(), $end_of_period->unix(), $commit->commit, $commit->price_per_unit, $commit->currency, 2, $commit->method)) {
                $notification = "Overage processed for $commit->search_name on $commit->search_service @ $commit->price_per_unit $commit->currency over $commit->commit mbit for $start_of_period - $end_of_period with $commit->method aggregate using V2";
            }
            else {
                $notification = "Failed to build overage for $commit->search_name on $commit->search_service @ $commit->price_per_unit $commit->currency over $commit->commit mbit for $start_of_period - $end_of_period with $commit->method aggregate using V2";
            }

            if($notification !== '') {
                //Notification::route('slack', env('creatia.webhook.standard'))->notify(new SlackNotification($notification));
                \Log::debug($notification);
                if($verbose) {
                    echo "$notification\n";
                }
            }
        }

        if($verbose) {
            echo "Processed all overages for DAY $billing_day \n";
        }

        return 0;
    }
}
