<?php

namespace App\Console\Commands\Utils;

use App\Models\Backoffice\WebsiteObject;
use App\Models\Cpv;
use App\Models\Department;
use Illuminate\Console\Command;
use App\Services\LocalizationService;
use Illuminate\Support\Facades\File;

class ExportCpvs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'utils:export-cpvs';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Export cpvs to a JSON file';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $jsonFolderPath = base_path('json');

        $cpvs = Cpv::full()->get();

        $cpvsOut = [];
        foreach ($cpvs as $cpv) {
            $cpvsOut[] = [
                'export_id' => $cpv->id,
                'oo_id' => $cpv->migration_object_id,
                'cpvCode' => $cpv->full_code,
                'cpvDescription' => $cpv->title,
            ];
        }

        $jsonFilePath = $jsonFolderPath . '/cpvs-out.json';

        File::put($jsonFilePath, json_encode($cpvsOut, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        $this->info('CPVs exported to ' . $jsonFilePath);

        $departments = Department::full()->get();

        $departmentsOut = [];
        foreach ($departments as $department) {
            $parentId = null;
            if ($department->parent_id != null) {
                $parentId = WebsiteObject::where('website_object_id', $department->parent_id)->first()->object_id;
            }

            $cpvs = [];
            foreach ($department->cpvs as $cpv) {
                $cpvs[] = $cpv->full_code;
            }

            $departmentsOut[] = [
                'export_id' => $department->id,
                'export_parent_id' => $parentId,
                'code' => $department->code,
                'title' => $department->title,
                'cpvs' => $cpvs,
            ];
        }

        $jsonFilePath = $jsonFolderPath . '/departments-out.json';
        File::put($jsonFilePath, json_encode($departmentsOut, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        $this->info('Departments exported to ' . $jsonFilePath);
        return 0;
    }
}
