<?php

namespace MtcPharmacy\Multisite\Console\Commands;

use Illuminate\Console\Command;
use MtcPharmacy\Multisite\Classes\MultisiteBaseEntity;
use MtcPharmacy\Multisite\Classes\MultisiteConstants;

/**
 * Examples:
 *     php artisan multisite:delete_custom_records shop_item 22
 */

class DeleteCustomRecordsCommand extends Command
{
    protected $signature = 'multisite:delete_custom_records {entity_type} {entity_id}';

    protected $description = 'Delete custom records and reset the parent one to be in single-site mode.';

    public function handle()
    {
        $this->info(__METHOD__);

        $entity_type = $this->argument('entity_type');
        $entity_id = $this->argument('entity_id');

        $ms_record = MultisiteBaseEntity::query()
            ->where('concrete_entity_type', $entity_type)
            ->where('concrete_entity_id', $entity_id)
            ->first();

        if ($ms_record) {
            $this->info("Found id:{$ms_record->id}.");

            $this->info('Removing any related custom entities (abstract and concrete).');
            foreach ($ms_record->custom_entities as $custom_entity) {
                $custom_entity->getConcreteEntity()->delete();
            }
            $ms_record->custom_entities()->delete();

            $this->info('Resetting [mode] to single-site.');
            $ms_record->mode = MultisiteConstants::MODE_SINGLE_SITE;
            $ms_record->save();
        }

        $this->info('Done.');
    }
}
