<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Services\QuickbookService;
use Illuminate\Support\Facades\Crypt;

class PrepQbData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'qbdata:prep';
    protected $ato;
    protected $qbs;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Prep prior sync';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->qbs = new QuickbookService();
        $this->ato = $this->qbs->getStoredAto();
    }

    /**
     * Execute the console command.
     * - v1 - just get new data each sync
     * @return int
     */
    public function handle()
    {
        // dont prep if there's one pending
        if(DB::table('qb_syncs')->where('status', 1)->whereNull('deleted_at')->exists()) return;
        
        // get last sync
        $lastSync = DB::table('qb_syncs')->where([
            ['status', '=', 2]
        ])->whereNull('deleted_at')->orderBy('id', 'desc')->first();
        if($lastSync){
            // get changes. PENDING
            
            // set last created sync date time
            $isoDatetime = date_format(date_create($lastSync->created_at),'c');
            // Log::debug("prep: " . $isoDatetime);

            // just create new
            $syncUuid = Str::uuid();
            $syncId = DB::table('qb_syncs')->insertGetId([
                'uuid' => $syncUuid, 'created_at' => now(), 'cut_off_time' => $lastSync->created_at
            ]);
            try{
                $prepData = [];
                $newDataSize = 0;
                foreach($this->ato as $anAto){
                    $ui = Str::uuid();
                    $prepData[$anAto->entity_id] = $this->qbs->prepBatchOp2(Crypt::decrypt($anAto->token_object), $ui, $isoDatetime);
                    // $prepData[$anAto->entity_id] = $this->qbs->prepBatchOp(Crypt::decrypt($anAto->token_object), $ui);


                    // old. working. fixed
                    $newDataSize += (intval($prepData[$anAto->entity_id]->Invoice) + intval($prepData[$anAto->entity_id]->Item) + intval($prepData[$anAto->entity_id]->Payment) + 
                        intval($prepData[$anAto->entity_id]->PaymentMethod) + intval($prepData[$anAto->entity_id]->Customer) + intval($prepData[$anAto->entity_id]->CreditMemo));
                }
                // Log::debug("new data size: " . $newDataSize);
                DB::table('qb_syncs')->where([
                    ['status', '=', 1], ['id', '=', $syncId]
                ])->whereNull('deleted_at')->update([
                    'prepared_at' => now(), 'prepared_object' => base64_encode(json_encode($prepData))
                ]);
            }catch(Exception $ex){
                DB::table('qb_syncs')->where([
                    ['status', '=', 1], ['id', '=', $syncId]
                ])->whereNull('deleted_at')->update([
                    'status' => 0, 'error_object' => 'error prepping sync data',
                ]);
            }


        }else{
            // do batch data retrievel
            // Log::debug('syncing data for the first time...');

            $syncUuid = Str::uuid();
            $syncId = DB::table('qb_syncs')->insertGetId([
                'uuid' => $syncUuid, 'created_at' => now()
            ]);
            $prepData = [];
            $newDataSize = 0;
            foreach($this->ato as $anAto){
                $ui = Str::uuid();
                // Log::debug($ui);
                // $prepData[$anAto->entity_id] = $this->qbs->prepBatchOp(Crypt::decrypt($anAto->token_object), $ui);
                $prepData[$anAto->entity_id] = $this->qbs->prepBatchOp2(Crypt::decrypt($anAto->token_object), $ui, null);
                $newDataSize += (intval($prepData[$anAto->entity_id]->Invoice) + intval($prepData[$anAto->entity_id]->Item) + intval($prepData[$anAto->entity_id]->Payment) + 
                    intval($prepData[$anAto->entity_id]->PaymentMethod) + intval($prepData[$anAto->entity_id]->Customer) + intval($prepData[$anAto->entity_id]->CreditMemo));
            }
            // Log::debug("new data size: " . $newDataSize);
            DB::table('qb_syncs')->where([
                ['status', '=', 1], ['id', '=', $syncId]
            ])->whereNull('deleted_at')->update([
                'prepared_at' => now(), 'prepared_object' => base64_encode(json_encode($prepData))
            ]);
        }
    }
}
