<?php

use A7kz\Platform\Models\UniModel;
use A7kz\Platform\Modules\Platform\Core\Facades\Core;
use A7kz\Platform\Modules\Platform\Segment\Facades\Segment;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use \A7kz\Platform\Commands\InstallScript;

return new class extends \A7kz\Platform\Commands\InstallScript {

    public function install($module_name, $module_version)
    {
    }

    public function update($module_name, $module_version): void
    {
        $this->upgrade();
        $this->seed();
    }

    private function upgrade(): void
    {
        $segments = Segment::listActive();
        foreach ($segments as $segment) {
            if (!Schema::connection($segment->connector)->hasTable('pipi_owners')) {
                Schema::connection($segment->connector)->create('pipi_owners', static function (Blueprint $table) {
                    $table->id();
                    $table->string('name')->nullable()->comment('Наименование');
                    $table->boolean('is_group')->default(false)->comment('Это группа');
                    $table->string('code')->nullable()->comment('Код');
                    $table->string('iin')->nullable()->comment('ИИН');
                    $table->string('kbe')->nullable()->comment('КБЕ');
                    $table->string('okpo_code')->nullable()->comment('Код по ОКПО');
                    $table->string('comments')->nullable()->comment('Комментарий');
                    $table->string('main_contact')->nullable()->comment('Основное контактное лицо');
                    $table->string('bank_account')->nullable()->comment('Оснойной банковский счет');
                    $table->string('address')->nullable()->comment('Адрес');
                    $table->string('phone')->nullable()->comment('Телефон');
                    $table->string('mail')->nullable()->comment('Почта');
                    $table->string('id_number')->nullable()->comment('Номер удостоверения');
                    $table->date('id_date')->nullable()->comment('Дата удостоверения');
                    $table->string('issued')->nullable()->comment('Удостоверение выдано');
                    $table->timestamps();
                    $table->softDeletes();

                    $table->unsignedBigInteger('contract_id')->nullable()->comment('id Договора');
                    $table->foreign('contract_id')->references('id')->on('pipi_owner_contracts')->onDelete('cascade');
                    $table->unsignedBigInteger('parent_id')->nullable()->comment('Парент');
                    $table->foreign('parent_id')->references('id')->on('pipi_owners');
                    $table->unsignedBigInteger('user_id')->nullable()->comment('Пользователь в системе');
                    $table->foreign('user_id')->references('id')->on('core_users');
                });
            }

            if (!Schema::connection($segment->connector)->hasColumn('pipi_owners', 'guid')) {
                Schema::connection($segment->connector)->table('pipi_owners', static function (Blueprint $table) {
                    $table->string('guid')->unique()->nullable();
                });
            }
        }
    }

    private function seed(): void
    {
        $seed = Storage::disk('pipicar_crm')->get('owners/seeds/seed.json');

        if (str_starts_with($seed, "\xef\xbb\xbf")) {
            $seed = substr($seed, 3); // Удаляем первые 3 байта
        }

        $data = json_decode($seed, true);

        $count = UniModel::model('pipi_owners')->count();
        if ($count === 0) {
            $segments = Segment::listActive();
            foreach ($segments as $segment) {
                foreach ($data as $value) {
                    if ($value['ПометкаУдаления'] == 'Нет') {
                        $model = UniModel::model('pipi_owners', $segment->connector);
                        $model->is_group = (bool) $value['ЭтоГруппа'];
                        $model->guid = $value['СсылкаGUID'];
                        $model->code = $value['Код'];
                        $model->name = $value['Наименование'];
                        $model->comments = $value['Комментарий'];
                        $model->iin = $value['ИдентификационныйКодЛичности'];
                        $model->kbe = $value['КБЕ'];
                        $model->okpo_code = $value['КодПоОКПО'];
                        $model->main_contact = $value['ОсновноеКонтактноеЛицо'];
                        $model->bank_account = $value['ОсновнойБанковскийСчет'];
                        $model->address = $value['Адрес'];
                        $model->phone = $value['Телефон'];
                        $model->mail = $value['Почта'];
                        $model->id_number = $value['УдНомер'];
                        if ($value['УдДата']) {
                            $model->id_date = $this->formatDate($value['УдДата'])->format('Y-m-d');
                        }
                        $model->issued = $value['УдВыдан'];
                        if ($value['ОсновнойДоговор']) {
                            $model->contract_id = UniModel::model('pipi_owner_contracts', $segment->connector)
                                ->firstOrCreate([
                                    'name' => $value['ОсновнойДоговор']
                                ])->id;
                        }
                        $model->save();
                    }
                }
            }

            foreach ($data as $value) {
                $model = UniModel::model('pipi_owners')->where('name', $value['Наименование'])->first();

                if ($model && $value['Родитель']) {
                    $parent = UniModel::model('pipi_owners')->where('name', $value['Родитель'])->first();
                    if ($parent) {
                        $model->parent_id = $parent->id;
                        $model->save();
                    }
                }
            }
        }
    }

    private function formatDate($date): ?Carbon
    {
        $date = trim($date);

        try {
            return Carbon::parse($date);
        } catch (\Exception $e) {
            return null;
        }
    }
};
