<?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;
use JetBrains\PhpStorm\NoReturn;

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_owner_contracts')) {
                Schema::connection($segment->connector)->create('pipi_owner_contracts', static function (Blueprint $table) {
                    $table->id();
                    $table->boolean('is_group')->default(false)->comment('Это группа');
                    $table->string('code')->nullable()->comment('Код');
                    $table->string('name')->nullable()->comment('Наименование');
                    $table->string('comments')->nullable()->comment('Комментарий');
                    $table->string('organization')->nullable()->comment('Организация');
                    $table->string('contract_number')->nullable()->comment('Номер договора');
                    $table->date('contract_date')->nullable()->comment('Дата договора');
                    $table->date('started_at')->nullable()->comment('Дата начала действия');
                    $table->date('ended_at')->nullable()->comment('Дата окончания');
                    $table->string('payment_type')->nullable()->comment('Условия оплаты');

                    $table->timestamps();
                    $table->softDeletes();

                    $table->unsignedBigInteger('parent_id')->nullable();
                    $table->foreign('parent_id')->references('id')->on('pipi_owner_contracts');
                });
            }

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

    #[NoReturn] private function seed(): void
    {
        $seed = Storage::disk('pipicar_crm')->get('owner_contracts/seeds/seed.json');

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

        $data = json_decode($seed, true);

        $segments = Segment::listActive();

        $count = UniModel::model('pipi_owner_contracts')->count();

        if ($count === 0) {
            foreach ($segments as $segment) {
                foreach ($data as $value) {
                    if ($value['ПометкаУдаления'] == 'Нет') {
                        $model = UniModel::model('pipi_owner_contracts', $segment->connector);
                        $model->is_group = (bool) $value['ЭтоГруппа'];
                        $model->guid = $value['СсылкаGUID'];
                        $model->code = $value['Код'];
                        $model->name = $value['Наименование'];
                        $model->comments = $value['Комментарий'];
                        $model->organization = $value['Организация'];
                        $model->contract_number = $value['НомерДоговора'];
                        $model->contract_date = $this->formatDate($value['ДатаДоговора'])?->format('Y-m-d');
                        $model->started_at = $this->formatDate($value['ДатаНачалаДействияДоговора'])?->format('Y-m-d');
                        $model->ended_at = $this->formatDate($value['ДатаОкончанияДействияДоговора'])?->format('Y-m-d');
                        $model->payment_type = $value['УсловияОплаты'];
                        $model->save();
                    }
                }
            }

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

                if ($model && $value['Родитель']) {
                    $parent = UniModel::model('pipi_owner_contracts')->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;
        }
    }
};
