<?php

namespace App\Modules\applications\Logic;

use A7kz\Platform\Models\UniModel;
use A7kz\Platform\Modules\Platform\Acl\Facades\Acl;
use A7kz\Platform\Modules\Platform\Core\Services\Base\Logic;
use App\Http\Notifications\TelegramNotification;
use App\Models\User;
use App\Modules\applications\Enum\ApplicationStatus;
use App\Modules\auto\Enums\AutoStatusEnums;
use Carbon\CarbonPeriod;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;

class Approve extends Logic
{
    public function run()
    {
        $user = new User();

        if (!isset($this->row->user_id)) {
            $checkUser = UniModel::model('core_users')->where('email', $this->row->user_email)->first();
            if (isset($checkUser)) {
                $this->row->user_id = $checkUser->id;
                $this->row->save();
            } else {
                $password = Str::random(8);
                $user->forceFill([
                    'name' => $this->row->user_name . ' ' . $this->row->surname_name,
                    'username' => $this->row->user_email,
                    'email' => $this->row->user_email,
                    'phone' => $this->row->user_phone,
                    'password' => Hash::make($password),
                    'active' => true
                ]);

                $user->save();

                $this->row->user_id = $user->id;
                $this->row->save();
                $userRole = UniModel::model('core_roles')
                    ->where('alias', 'user')
                    ->first();

                if (!empty($userRole)) {
                    $userRoleModel = UniModel::model('core_user_roles');

                    $userRoleModel->forceFill([
                        'user_id' => $user->id,
                        'role_id' => $userRole->id
                    ]);

                    $userRoleModel->save();
                }
                $company = UniModel::model(config('platform.company.tables.company'))
                    ->firstOrCreate([
                        'name'      => $this->row->user_name . ' ' . $this->row->surname_name,
                        'biniin'    => $this->row->biniin ?? '',
                        'fullname'  => $this->row->user_name . ' ' . $this->row->surname_name,
                        'segment'   => 'sol'
                    ]);

                $ucr = UniModel::model(config('platform.company.tables.company_user_role'))
                    ->firstOrCreate([
                        'user_id' => $user->id,
                        'role_id' => 7,
                        'company_id' => $company->id
                    ]);
                if (!$ucr) {
                    UniModel::model(config('platform.company.tables.company_user_role'))
                        ->create([
                            'user_id' => $user->id,
                            'role_id' => 6,
                            'company_id' => $company->id
                        ]);
                }

                UniModel::model(config('platform.company.tables.company_user'))
                    ->firstOrCreate([
                        'company_id' => $company->id,
                        'user_id'    => $user->id,
                        'default'    => true,
                    ]);
                $text = [
                    'Сообщение' => __('Пользователь создан'),
                    'Логин' => 'Логин: ' . $user->email,
                    'Пароль' => 'Пароль: ' . $password
                ];
                Notification::send([$text], new TelegramNotification($text));
            }
        }

        $this->fillCalendar($this->row);

        $this->row->status = ApplicationStatus::approved->value;
        $this->row->save();

        return $this->response();
    }

    private function fillCalendar($row): void
    {
        $period = CarbonPeriod::create($row->started_at, $row->ended_at);

        $dates = array_map(fn($date) => $date->toDateString(), iterator_to_array($period));
        foreach ($dates as $date) {
            UniModel::model('pipi_auto_calendar')->create([
                'auto_id' => $row->car_id,
                'date' => $date,
                'status' => AutoStatusEnums::Rent->name
            ]);
        }
    }
}
