<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Asset;
use App\Models\AssetHistory;
use App\Models\AssetStatus;
use App\Models\AssetType;
use App\Models\MakeAndModel;
use App\Models\TechnicalSpecs;

class TQT195MixupAssets extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'MixupAssets:mix';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Mix up assets on TQT-195';

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

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

        $assetTypes = AssetType::whereIn('slug', ['desktop', 'laptop', 'tablet'])->get();

        foreach ($assetTypes as $assetType) {

            $totalAssetCount = Asset::where('asset_type_id', $assetType->id)->count();
            $makeAndModels = MakeAndModel::select('id')->where('asset_type_id', $assetType->id)->get();

            // $techSpecs = TechnicalSpecs::with('assets')->whereIn('make_and_model_id', $makeAndModels)->get();

            $techSpecs = TechnicalSpecs::whereIn('make_and_model_id', $makeAndModels)->get();

            $devicePerSpec = intval($totalAssetCount / $techSpecs->count());

            $limit = $devicePerSpec; // number of records to retrieve

            for ($i = 0; $i < $techSpecs->count(); $i++) {

                // $this->info($assetType->name . " - " . $techSpecs[$i]->makeAndModel->name . ' - ' . $techSpecs[$i]->details . ' -  ' . $techSpecs[$i]->assets->count());
                $offset = $devicePerSpec * $i;

                $totalAssets = Asset::where('asset_type_id', $assetType->id)->skip($offset)->take($limit)->get();

                foreach ($totalAssets as $asset) {
                    $asset->update(['make_and_model_id' => $techSpecs[$i]->make_and_model_id, 'technical_spec_id' => $techSpecs[$i]->id]);
                }

                // $this->info("Assets from " . $offset . " to " . $limit + $offset . ' ==> ' . $techSpecs[$i]->makeAndModel->name);
            }
        }

        $this->info("Assets mixed.");
    }
}
