<?php

namespace App\Console\Commands;

use App\Models\CrmQbProfile;
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\Services\SPSERPService;

/**
 * using job instead with cutofftime
 * 2024-04-04 - added multi profile support
 */
class MapCrmQb2 extends Command
{
  /**
   * The name and signature of the console command.
   *
   * @var string
   */
  protected $signature = 'qbdata:crmmap2';
  protected $ato;
  protected $qbs;
  protected $spserpService;

  /**
   * The console command description.
   *
   * @var string
   */
  protected $description = 'CRM-QB mapping2';

  /**
   * Create a new command instance.
   *
   * @return void
   */
  public function __construct()
  {
    parent::__construct();
    $this->spserpService = new SPSERPService();
    $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()
  {
    // only if have one successfuly init
    if (!DB::table('qb_syncs')->where('type', 'init')->where('status', 2)->exists()) return;

    // pending? nope
    if (DB::table('qb_crm_mappings2')->where('status', 1)->whereNull('deleted_at')->exists()) return;

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

    $now = now();
    // $cutOffTime = $lastSync ? $lastSync->created_at : null;
    $cutOffTime = null;

    $syncId = DB::table('qb_crm_mappings2')->insertGetId([
      'uuid' => Str::uuid(), 'created_at' => $now, 'cut_off_time' => $cutOffTime, 'status' => 1
    ]);

    $amountOfTimeSec = 1800;
    set_time_limit($amountOfTimeSec);

    // mapped using client with job. add if none
    $allCwithJ = $this->spserpService->getAllCompaniesWithServices(true, true, $cutOffTime);
    $added = [];
    foreach ($allCwithJ as $cj) {
      // split departments
      $deptArr = explode(',', $cj['department_ids']);

      // get business entity
      foreach ($deptArr as $d) {
        $entityWithAccess = DB::table('providers_accesses')
          ->where('status', 1)->where('entity_type', 'department')->where('entity_id', $d)->where('access_type', 'include')
          ->first();

        if (!$entityWithAccess) continue;


        // get related profiles
        $cqmData = CrmQbProfile::where([
          ['client_id', '=', $cj['client_id']], ['entity_id', '=', $entityWithAccess->provider_id]
        ])
          ->whereNull('deleted_at')
          ->get();
        if (!$cqmData || count($cqmData) == 0) {
          // none. create
          $cqmData = CrmQbProfile::create([
            'client_id' => $cj['client_id'], 'entity_id' => $entityWithAccess->provider_id, 'crm_name' => $cj['client_name']
          ]);
          array_push($added, $entityWithAccess->provider_id . '-' . $cj['client_id']);
        } else {
          // if (count($cqmData) > 1) Log::debug($cj['client_id'] . " data: " . count($cqmData));
          // update each
          foreach ($cqmData as $cqd) {
            $cqd->crm_name = $cj['client_name'];
            $cqd->save();
            array_push($added, $entityWithAccess->provider_id . '-' . $cj['client_id']);
          }
        }
      }
    }

    // add crm data for existing with missing data
    $allCompanies = $this->spserpService->getCompaniesBasic(false, false, false, null, false);
    foreach ($allCompanies as $ac) {
      // get cqm records with null crm data
      $cqmData = CrmQbProfile::where([
        ['client_id', '=', $ac['id']]
      ])
        ->whereNull('crm_name')
        ->whereNull('deleted_at')
        ->get();
      foreach ($cqmData as $cqd) {
        $cqd->crm_name = $ac['name'];
        $cqd->save();
        array_push($added, $ac['id']);
      }
    }

    DB::table('qb_crm_mappings2')->where([
      ['status', '=', 1], ['id', '=', $syncId]
    ])->whereNull('deleted_at')->update([
      'mapped_count' => count($added), 'status' => 2,
      'completed_at' => $now
    ]);
  }
}
