<?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;
use App\Models\QbSync;
use Exception;

/**
 * PENDING
 * - get changes
 */

class PrepQbData extends Command
{
  protected $signature = 'qbdata:prep';
  protected $ato;
  protected $qbs;

  protected $description = 'Prep prior sync';

  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 (QbSync::where('status', 1)->whereNull('deleted_at')->exists()) return;

    $qbComponents = DB::table('qb_objects')->where('status', 1)->get()->pluck('name')->toArray();
    if (count($qbComponents) == 0) return;

    // get last sync
    $lastSync = QbSync::where('status', 2)->whereNull('deleted_at')->orderBy('id', 'desc')->first();

    // just create new
    $sync = QbSync::create([
      'uuid' => Str::uuid(), 'created_at' => now(),
    ]);

    $cutOffTime = null;

    if ($lastSync) {
      $sync->cut_off_time = $lastSync->created_at;
      // set last created sync date time. qb requires iso date
      $cutOffTime = date_format(date_create($lastSync->created_at), 'c');
    }

    try {
      $prepData = [];
      $newDataSize = 0;
      foreach ($this->ato as $anAto) {
        $prepData[$anAto->entity_id] = $this->qbs->prepBatchOp2(Crypt::decrypt($anAto->token_object), Str::uuid(), $cutOffTime);

        foreach ($qbComponents as $qc) {
          $newDataSize += intval($prepData[$anAto->entity_id]->$qc);
        }
      }
      $sync->prep_data_size = $newDataSize;
      $sync->prepared_object = base64_encode(json_encode($prepData));
      $sync->prepared_at = now();
      $sync->save();
    } catch (Exception $ex) {
      $sync->error_object = 'error prepping sync data';
      $sync->status = 0;
      $sync->save();
    }
  }
}
