<?php

namespace App\Console\Commands\Billing;

use App\Console\Commands\BaseCommand;
use App\Http\Controllers\Billing\AdminController;
use Carbon\Carbon;

use App\Models\Billing\BillingCommit;

// Create an enum just to make things readable
enum CsvColumn: string {
    case CustomerId = '0';
    case ProductId = '1';
    case Commit = '2';
    case Currency = '3';
};

class ImportCommits extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'billing:commit-import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import existing commits from a CSV';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        // Get options - Gross, but clean
        $options = (new AdminController)->get_overage_options()->original;

        // Get file handler
        $handle = fopen(storage_path('commits.csv'), 'r');

        //  Skip first line
        fgetcsv($handle);

        // Go over each line
        while(($overage = fgetcsv($handle)) !== false)
        {
            // Easy to handle these - Commit is the real pain that makes my code less pretty :(
            $customer_id = $overage[CsvColumn::CustomerId->value];
            $product_id = $overage[CsvColumn::ProductId->value];

            $currency_amount = str_replace('$', '', substr($overage[CsvColumn::Currency->value], 0, -3));
            $currency_unit = substr($overage[CsvColumn::Currency->value], -3);

            // Need to handle the commit
            $commit = strtoupper($overage[CsvColumn::Commit->value]);

            if(str_contains($commit, 'MB')) {
                $commit = str_replace('MB', '', $commit);
            }
            elseif(str_contains($commit, 'G')) {
                $commit = str_replace('G', '', $commit) * 1000;
            }

            if($customer_id != '' && $product_id != '' && $currency_amount != '' && $currency_unit != '' && $commit != '') {
                // Retrieve searchable names
                $search_name = '';
                $service_name = '';

                if(($account = array_values(array_filter($options['accounts']['gsl'], function($x) use($customer_id) { return $x['id'] == $customer_id; }))) != []) {
                    $search_name = $account[0]['name'];

                    if(($service = array_values(array_filter($account[0]['services'], function($x) use($product_id) { return $x['id'] == $product_id; }))) != []) {
                        $service_name = $service[0]['name'];
                    }
                }

                BillingCommit::create([
                    'effective_at'      => Carbon::now()->subMonth(),
                    'billing_day'       => 1,
                    'commit'            => $commit,
                    'price_per_unit'    => $currency_amount,
                    'whmcs_brand'       => 'gsl',
                    'whmcs_client_id'   => $customer_id,
                    'whmcs_service_id'  => $product_id,
                    'search_name'       => $search_name,
                    'search_service'    => $service_name,
                    'search_brand'      => config('creatia.automation.main_organisation_name'),
                    'currency'          => $currency_unit
                ])->save();
            }
        }

        fclose($handle);

    }
}
