<?php

namespace App\Http\Controllers;

use A7kz\Platform\Models\UniModel;
use A7kz\Platform\Modules\Platform\Segment\Facades\Segment;
use App\Modules\auto\Enums\AutoStatusEnums;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class Sync1cApiController extends Controller
{

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

        try {
            return Carbon::parse($date);
        } catch (\Exception $e) {
            return null;
        }
    }
    public function syncAutoData(Request $request)
    {
        try {

            Log::error('Запрос машин пришел');

            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) {
                    $inspectionKit = null;

                    if (isset($value['КомпректацияДляОсмотра'])) {
                        if (is_array($value['КомпректацияДляОсмотра'])) {
                            $inspectionKit = $value['КомпректацияДляОсмотра'];
                        }
                        elseif (is_string($value['КомпректацияДляОсмотра']) && json_validate($value['КомпректацияДляОсмотра'])) {
                            $inspectionKit = json_decode($value['КомпректацияДляОсмотра'], true);
                        }
                    }

                    if ($value['ПометкаУдаления'] == 'Да' or $value['НеИспользовать'] == 'Да') {
                        $class_id = UniModel::model('pipi_auto_classes', $segment->connector)
                            ->where('name', $value['Класс'])->first()?->id;

                        $type_id = UniModel::model('pipi_auto_types', $segment->connector)
                            ->where('name', $value['Тип'])->first();

                        $brand_id = UniModel::model('pipi_auto_brands', $segment->connector)
                            ->where('name', $value['Марка'])->first();

                        $color_id = UniModel::model('pipi_auto_colors', $segment->connector)
                            ->where('name', $value['Цвет'])->first();

                        $model = UniModel::model('pipi_brand_models', $segment->connector)
                            ->where('name', $value['Модель'])
                            ->where('brand_id', $brand_id?->id)
                            ->where('year', $this->formatDate($value['ГодПроизводства'])?->format('Y'))
                            ->first();
                    }
                    else {
                        $class_id = UniModel::model('pipi_auto_classes', $segment->connector)
                            ->firstOrCreate(['name' => $value['Класс']])->id;
                        $type_id = UniModel::model('pipi_auto_types', $segment->connector)
                            ->firstOrCreate(['name' => $value['Тип']]);
                        $brand_id = UniModel::model('pipi_auto_brands', $segment->connector)
                            ->firstOrCreate(['name' => $value['Марка']]);
                        $color_id = UniModel::model('pipi_auto_colors', $segment->connector)
                            ->firstOrCreate(['name' => $value['Цвет']]);
                        $model = UniModel::model('pipi_brand_models', $segment->connector)
                            ->firstOrCreate([
                                'name' => $value['Модель'],
                                'brand_id' => $brand_id->id,
                                'year' => $this->formatDate($value['ГодПроизводства'])?->format('Y'),
                            ]);
                    }
                    UniModel::model('pipi_auto', $segment->connector)->updateOrCreate(
                        [
                            'guid' => $value['id'],
                        ],
                        [
                            'code' => $value['Код'],
                            'name' => $value['Наименование'],
                            'type_id' => $type_id?->id,
                            'class_id' => $class_id,
                            'brand_id' => $brand_id?->id,
                            'model_id' => $model?->id,
                            'color_id' => $color_id?->id,
                            'serial_number' => $value['СерийныйНомер'],
                            'state_number' => $value['ГосНомер'],
                            'manufacture_year' => $this->formatDate($value['ГодПроизводства'])?->format('Y-m-d'),
                            'passport_number' => $value['НомерТехПаспорта'],
                            'passport_date' => $this->formatDate($value['ДатаТехпаспорта'])?->format('Y-m-d'),
                            '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' => $value['НеИспользовать'] == 'Да',
                            'is_predefined' => (bool)$value['Предопределенный'],
                            'predefined_data_name' => $value['ИмяПредопределенныхДанных'],
                            'inspection_kit' => $inspectionKit,
                            'deleted_at' => $value['ПометкаУдаления'] == 'Да' ? now() : null,
                        ]
                    );

                    $model->class_id = $class_id;
                    $model->save();
                }
            }

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

            Log::error('Запрос владельцев пришел');

            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(
                        [
                            'guid' => $value['id'],
                        ],
                        [
                            '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' => $this->formatDate($value['УдДата'])?->format('Y-m-d'),
                            '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 {

            Log::error('Запрос контрактов пришел');

            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(
                        [
                            'guid' => $value['id'],
                        ],
                        [
                            'code' => $value['Код'],
                            'is_group' => (bool)$value['ЭтоГруппа'],
                            'name' => $value['Наименование'],
                            'comments' => $value['Комментарий'],
                            'organization' => $value['Организация'],
                            'contract_number' => $value['НомерДоговора'],
                            'contract_date' => $this->formatDate($value['ДатаДоговора'])?->format('Y-m-d'),
                            'started_at' => $this->formatDate($value['ДатаНачалаДействияДоговора'])?->format('Y-m-d'),
                            'ended_at' => $this->formatDate($value['ДатаОкончанияДействияДоговора'])?->format('Y-m-d'),
                            '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);
        }
    }

    public function syncCarCalendar(Request $request) {
        try {

            Log::error('Запрос календаря пришел');

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

            DB::beginTransaction();

            $segments = Segment::listActive();

            foreach ($segments as $segment) {
                foreach ($request->all() as $value) {
                    UniModel::model('pipi_auto_calendar', $segment->connector)->updateOrCreate(
                        [
                            'auto_id' => UniModel::model('pipi_auto')->where('guid', $value['id'])->first()?->id,
                            'date' => $this->formatDate($value['Дата']),
                        ],
                        [
                            'auto_id' => UniModel::model('pipi_auto')->where('guid', $value['id'])->first()?->id,
                            'date' => $this->formatDate($value['Дата']),
                            'status' => AutoStatusEnums::from($value['Статус'])->name
                        ]
                    );
                }
            }


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