<?php

namespace App\Http\Controllers;

use A7kz\Platform\Models\UniModel;
use A7kz\Platform\Modules\Platform\Segment\Facades\Segment;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class Sync1cApiController extends Controller
{
    public function syncAutoData(Request $request)
    {
        try {
            DB::beginTransaction();

            $segments = Segment::listActive();

            Storage::disk('local')->put('last_req_auto.json', json_encode($request->json()->all(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

            foreach ($segments as $segment) {
                foreach ($request->all() as $value) {
                    UniModel::model('pipi_auto', $segment->connector)->updateOrCreate(
                        [
                            'code' => $value['Код'],
                        ],
                        [
                            'name' => $value['Наименование'],
                            'type_id' => UniModel::model('pipi_auto_types', $segment->connector)
                                ->firstOrCreate(['name' => $value['Тип']])->id,
                            'class_id' => UniModel::model('pipi_auto_classes', $segment->connector)
                                ->firstOrCreate(['name' => $value['Класс']])->id,
                            'brand_id' => UniModel::model('pipi_auto_brands', $segment->connector)
                                ->firstOrCreate(['name' => $value['Марка']])->id,
                            'model_id' => UniModel::model('pipi_brand_models', $segment->connector)
                                ->firstOrCreate([
                                    'name' => $value['Модель'],
                                    'brand_id' => UniModel::model('pipi_auto_brands', $segment->connector)
                                        ->firstOrCreate(['name' => $value['Марка']])->id,
                                ])->id,
                            'color_id' => UniModel::model('pipi_auto_colors', $segment->connector)
                                ->firstOrCreate(['name' => $value['Цвет']])->id,
                            'serial_number' => $value['СерийныйНомер'],
                            'state_number' => $value['ГосНомер'],
                            'manufacture_year' => $value['ГодПроизводства'],
                            'passport_number' => $value['НомерТехПаспорта'],
                            'passport_date' => $value['ДатаТехпаспорта'],
                            'estimated_cost' => $value['ОценочнаяСтоимость'],
                            'owner_id' => UniModel::model('pipi_owners', $segment->connector)
                                ->firstOrCreate(['name' => $value['ВладелецИмущества']])->id,
                            'is_trust_management' => (bool)$value['ВДоверенномУправлении'],
                            'owner_percentage' => $value['ПроцентВладельца'],
                            'is_inactive' => (bool)$value['НеИспользовать'],
                            'is_predefined' => (bool)$value['Предопределенный'],
                            'predefined_data_name' => $value['ИмяПредопределенныхДанных'],
                            'inspection_kit' => json_validate($value['КомпректацияДляОсмотра']) ? $value['КомпректацияДляОсмотра'] : null,
                            'deleted_at' => $value['ПометкаУдаления'] ? now() : null,
                        ]
                    );
                }
            }

            DB::commit();
            return response()->json(['message' => 'Data synchronized successfully'], 200);
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('Error syncing auto data: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to synchronize data'], 500);
        }
    }
    public function syncOwners(Request $request)
    {
        try {
            DB::beginTransaction();

            Storage::disk('local')->put('last_req_owners.json', json_encode($request->json()->all(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

            $segments = Segment::listActive();

            foreach ($segments as $segment) {
                foreach ($request->all() as $value) {
                    UniModel::model('pipi_owners', $segment->connector)->updateOrCreate(
                        [
                            'code' => $value['Код'],
                        ],
                        [
                            'is_group' => (bool)$value['ЭтоГруппа'],
                            'name' => $value['Наименование'],
                            'comments' => $value['Комментарий'],
                            'iin' => $value['ИдентификационныйКодЛичности'],
                            'kbe' => $value['КБЕ'],
                            'okpo_code' => $value['КодПоОКПО'],
                            'main_contact' => $value['ОсновноеКонтактноеЛицо'],
                            'bank_account' => $value['ОсновнойБанковскийСчет'],
                            'address' => $value['Адрес'],
                            'phone' => $value['Телефон'],
                            'mail' => $value['Почта'],
                            'id_number' => $value['УдНомер'],
                            'id_date' => $value['УдДата'],
                            'issued' => $value['УдВыдан'],
                            'contract_id' => $value['ОсновнойДоговор'] ? UniModel::model('pipi_owner_contracts', $segment->connector)->firstOrCreate([
                                'name' => $value['ОсновнойДоговор']
                            ])->id : null,
                            'deleted_at' => $value['ПометкаУдаления'] ? now() : null,
                        ]
                    );
                }
            }

            foreach ($request->all() 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();
                    }
                }
            }

            DB::commit();
            return response()->json(['message' => 'Owners synchronized successfully'], 200);
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('Error syncing owners: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to synchronize owners'], 500);
        }
    }

    public function syncOwnerContracts(Request $request)
    {
        try {
            DB::beginTransaction();

            Storage::disk('local')->put('last_req_contracts.json', json_encode($request->json()->all(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

            $segments = Segment::listActive();

            foreach ($segments as $segment) {
                foreach ($request->all() as $value) {
                    UniModel::model('pipi_owner_contracts', $segment->connector)->updateOrCreate(
                        [
                            'code' => $value['Код'],
                        ],
                        [
                            'is_group' => (bool)$value['ЭтоГруппа'],
                            'name' => $value['Наименование'],
                            'comments' => $value['Комментарий'],
                            'organization' => $value['Организация'],
                            'contract_number' => $value['НомерДоговора'],
                            'contract_date' => $value['ДатаДоговора'],
                            'started_at' => $value['ДатаНачалаДействияДоговора'],
                            'ended_at' => $value['ДатаОкончанияДействияДоговора'],
                            'payment_type' => $value['УсловияОплаты'],
                            'deleted_at' => $value['ПометкаУдаления'] ? now() : null,
                        ]
                    );
                }
            }

            foreach ($request->all() 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();
                    }
                }
            }

            DB::commit();
            return response()->json(['message' => 'Owner contracts synchronized successfully'], 200);
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('Error syncing owner contracts: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to synchronize owner contracts'], 500);
        }
    }
}
